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 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 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 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 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 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 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 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 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 aClass = resolverCtx.isPreviewMode() ? BasicIdeaProject.class : IdeaProject.class; - ModelBuilder 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 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 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 aClass = resolverCtx.isPreviewMode() ? BasicIdeaProject.class : IdeaProject.class; + ModelBuilder 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 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 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 toRemove, @Nonnull Project project, boolean synchronous) { - } + @Override + public void removeData(@Nonnull Collection 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 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 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 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(); + } + }); } - return null; - } - private static File getProjectConfigurationFile(ProjectSystemId externalSystemId, String externalProjectPath) { - return new File(getProjectConfigurationDir(externalSystemId), Integer.toHexString(externalProjectPath.hashCode()) + "/project.dat"); - } + 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 File getProjectConfigurationDir(ProjectSystemId externalSystemId) { - return getPluginSystemDir(externalSystemId, "Projects"); - } + @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 static File getPluginSystemDir(ProjectSystemId externalSystemId, String folder) { - return new File(ContainerPathManager.get().getSystemPath(), externalSystemId.getId().toLowerCase() + "/" + folder).getAbsoluteFile(); - } + input = new Input(new FileInputStream(configurationFile)); + return myKryo.readObject(input, DefaultExternalProject.class); + } + catch (Exception e) { + LOG.error(e); + } + finally { + StreamUtil.closeStream(input); + } + + return null; + } - private static class FileSerializer extends Serializer { - private final Kryo myStdKryo; + private static File getProjectConfigurationFile(ProjectSystemId externalSystemId, String externalProjectPath) { + return new File( + getProjectConfigurationDir(externalSystemId), + Integer.toHexString(externalProjectPath.hashCode()) + "/project.dat" + ); + } - public FileSerializer() { - myStdKryo = new Kryo(); - myStdKryo.register(File.class); - myStdKryo.setInstantiatorStrategy(new StdInstantiatorStrategy()); + private static File getProjectConfigurationDir(ProjectSystemId externalSystemId) { + return getPluginSystemDir(externalSystemId, "Projects"); } - @Override - public void write(Kryo kryo, Output output, File object) { - myStdKryo.writeObject(output, object); + private static File getPluginSystemDir(ProjectSystemId externalSystemId, String folder) { + return new File( + ContainerPathManager.get().getSystemPath(), + externalSystemId.getId().toLowerCase() + "/" + folder + ).getAbsoluteFile(); } - @Override - public File read(Kryo kryo, Input input, Class type) { - File file = myStdKryo.readObject(input, File.class); - return new File(file.getPath()); + private static class FileSerializer extends Serializer { + private final Kryo myStdKryo; + + public FileSerializer() { + myStdKryo = new Kryo(); + myStdKryo.register(File.class); + myStdKryo.setInstantiatorStrategy(new StdInstantiatorStrategy()); + } + + @Override + public void write(Kryo kryo, Output output, File object) { + myStdKryo.writeObject(output, object); + } + + @Override + public File read(Kryo kryo, Input input, Class type) { + File file = myStdKryo.readObject(input, File.class); + return new File(file.getPath()); + } } - } // private static class StdSerializer extends Serializer { // private final Kryo myStdKryo; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleArtifactsContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleArtifactsContributor.java index 8953680..ac20e8a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleArtifactsContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleArtifactsContributor.java @@ -37,56 +37,60 @@ */ @ExtensionImpl public class GradleArtifactsContributor implements GradleMethodContextContributor { + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.isEmpty() || methodCallInfo.size() < 2 || !"artifacts".equals(methodCallInfo.get(1))) { + return; + } + final String text = place.getText(); + if (!methodCallInfo.contains(text) && place instanceof GrReferenceExpressionImpl) { + GradleResolverUtil.addImplicitVariable(processor, state, (GrReferenceExpressionImpl)place, Object.class.getName()); + return; + } - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.isEmpty() || methodCallInfo.size() < 2 || !"artifacts".equals(methodCallInfo.get(1))) { - return; + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GradleCommonClassNames.GRADLE_API_ARTIFACT_HANDLER); + PsiClass contributorClass = + psiManager.findClassWithCache(GradleCommonClassNames.GRADLE_API_ARTIFACT_HANDLER, place.getResolveScope()); + if (contributorClass != null) { + // assuming that the method call is addition of an artifact to the given configuration. + processAtrifactAddition(methodCallInfo.get(0), contributorClass, processor, state, place); + } } - final String text = place.getText(); - if (!methodCallInfo.contains(text) && place instanceof GrReferenceExpressionImpl) { - GradleResolverUtil.addImplicitVariable(processor, state, (GrReferenceExpressionImpl)place, Object.class.getName()); - return; - } - - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GradleCommonClassNames.GRADLE_API_ARTIFACT_HANDLER); - PsiClass contributorClass = psiManager.findClassWithCache(GradleCommonClassNames.GRADLE_API_ARTIFACT_HANDLER, place.getResolveScope()); - if (contributorClass != null) { - // assuming that the method call is addition of an artifact to the given configuration. - processAtrifactAddition(methodCallInfo.get(0), contributorClass, processor, state, place); - } - } - private static void processAtrifactAddition(@Nonnull String gradleConfigurationName, - @Nonnull PsiClass artifactHandlerClass, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - GrLightMethodBuilder builder = new GrLightMethodBuilder(place.getManager(), gradleConfigurationName); - PsiClassType type = PsiType.getJavaLangObject(place.getManager(), place.getResolveScope()); - builder.addParameter(new GrLightParameter("artifactInfo", type, builder)); - processor.execute(builder, state); + private static void processAtrifactAddition( + @Nonnull String gradleConfigurationName, + @Nonnull PsiClass artifactHandlerClass, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + GrLightMethodBuilder builder = new GrLightMethodBuilder(place.getManager(), gradleConfigurationName); + PsiClassType type = PsiType.getJavaLangObject(place.getManager(), place.getResolveScope()); + builder.addParameter(new GrLightParameter("artifactInfo", type, builder)); + processor.execute(builder, state); - GrMethodCall call = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); - if (call == null) { - return; - } - GrArgumentList args = call.getArgumentList(); - if (args == null) { - return; - } + GrMethodCall call = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); + if (call == null) { + return; + } + GrArgumentList args = call.getArgumentList(); + if (args == null) { + return; + } - int argsCount = GradleResolverUtil.getGrMethodArumentsCount(args); - argsCount++; // Configuration name is delivered as an argument. + int argsCount = GradleResolverUtil.getGrMethodArumentsCount(args); + argsCount++; // Configuration name is delivered as an argument. - for (PsiMethod method : artifactHandlerClass.findMethodsByName("add", false)) { - if (method.getParameterList().getParametersCount() == argsCount) { - builder.setNavigationElement(method); - } + for (PsiMethod method : artifactHandlerClass.findMethodsByName("add", false)) { + if (method.getParameterList().getParametersCount() == argsCount) { + builder.setNavigationElement(method); + } + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleBuildScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleBuildScriptContributor.java index 203bc50..a8b8722 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleBuildScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleBuildScriptContributor.java @@ -23,7 +23,7 @@ */ @ExtensionImpl public class GradleBuildScriptContributor extends GradleSimpleContributor { - public GradleBuildScriptContributor() { - super("buildscript", GradleCommonClassNames.GRADLE_API_SCRIPT_HANDLER); - } + public GradleBuildScriptContributor() { + super("buildscript", GradleCommonClassNames.GRADLE_API_SCRIPT_HANDLER); + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleCommonClassNames.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleCommonClassNames.java index ef446f1..1ae9177 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleCommonClassNames.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleCommonClassNames.java @@ -22,46 +22,90 @@ * @since 9/3/13 */ public final class GradleCommonClassNames { - @NonNls public static final String GRADLE_API_SCRIPT = "org.gradle.api.Script"; - @NonNls public static final String GRADLE_API_PROJECT = "org.gradle.api.Project"; - @NonNls public static final String GRADLE_API_CONFIGURATION_CONTAINER = "org.gradle.api.artifacts.ConfigurationContainer"; - @NonNls public static final String GRADLE_API_CONFIGURATION = "org.gradle.api.artifacts.Configuration"; - @NonNls public static final String GRADLE_API_ARTIFACT_HANDLER = "org.gradle.api.artifacts.dsl.ArtifactHandler"; - @NonNls public static final String GRADLE_API_DEPENDENCY_HANDLER = "org.gradle.api.artifacts.dsl.DependencyHandler"; - @NonNls public static final String GRADLE_API_ARTIFACTS_EXTERNAL_MODULE_DEPENDENCY = "org.gradle.api.artifacts.ExternalModuleDependency"; - @NonNls public static final String GRADLE_API_ARTIFACTS_MODULE_DEPENDENCY = "org.gradle.api.artifacts.ModuleDependency"; - @NonNls public static final String GRADLE_API_ARTIFACTS_DEPENDENCY_ARTIFACT = "org.gradle.api.artifacts.DependencyArtifact"; - @NonNls public static final String GRADLE_API_REPOSITORY_HANDLER = "org.gradle.api.artifacts.dsl.RepositoryHandler"; - @NonNls public static final String GRADLE_API_SOURCE_DIRECTORY_SET = "org.gradle.api.file.SourceDirectorySet"; - @NonNls public static final String GRADLE_API_SOURCE_SET = "org.gradle.api.tasks.SourceSet"; - @NonNls public static final String GRADLE_API_SOURCE_SET_CONTAINER = "org.gradle.api.tasks.SourceSetContainer"; - @NonNls public static final String GRADLE_API_SCRIPT_HANDLER = "org.gradle.api.initialization.dsl.ScriptHandler"; - @NonNls public static final String GRADLE_API_TASK = "org.gradle.api.Task"; - @NonNls public static final String GRADLE_API_DEFAULT_TASK = "org.gradle.api.DefaultTask"; - @NonNls public static final String GRADLE_API_TASKS_DELETE = "org.gradle.api.tasks.Delete"; - @NonNls public static final String GRADLE_API_TASKS_BUNDLING_JAR = "org.gradle.api.tasks.bundling.Jar"; - @NonNls public static final String GRADLE_API_TASKS_BUNDLING_WAR = "org.gradle.api.tasks.bundling.War"; - @NonNls public static final String GRADLE_API_TASKS_COMPILE_JAVA_COMPILE = "org.gradle.api.tasks.compile.JavaCompile"; - @NonNls public static final String GRADLE_API_TASKS_WRAPPER_WRAPPER = "org.gradle.api.tasks.wrapper.Wrapper"; - @NonNls public static final String GRADLE_API_TASKS_JAVADOC_JAVADOC = "org.gradle.api.tasks.javadoc.Javadoc"; - @NonNls public static final String GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_REPORT_TASK = "org.gradle.api.tasks.diagnostics.DependencyReportTask"; - @NonNls public static final String GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_INSIGHT_REPORT_TASK = "org.gradle.api.tasks.diagnostics.DependencyInsightReportTask"; - @NonNls public static final String GRADLE_API_TASKS_DIAGNOSTICS_PROJECT_REPORT_TASK = "org.gradle.api.tasks.diagnostics.ProjectReportTask"; - @NonNls public static final String GRADLE_API_TASKS_DIAGNOSTICS_PROPERTY_REPORT_TASK = "org.gradle.api.tasks.diagnostics.PropertyReportTask"; - @NonNls public static final String GRADLE_API_TASKS_DIAGNOSTICS_TASK_REPORT_TASK = "org.gradle.api.tasks.diagnostics.TaskReportTask"; - @NonNls public static final String GRADLE_API_TASKS_TESTING_TEST = "org.gradle.api.tasks.testing.Test"; - @NonNls public static final String GRADLE_API_TASKS_UPLOAD = "org.gradle.api.tasks.Upload"; - @NonNls public static final String GRADLE_API_ARTIFACTS_REPOSITORIES_FLAT_DIRECTORY_ARTIFACT_REPOSITORY = "org.gradle.api.artifacts.repositories.FlatDirectoryArtifactRepository"; - @NonNls public static final String GRADLE_LANGUAGE_JVM_TASKS_PROCESS_RESOURCES = "org.gradle.language.jvm.tasks.ProcessResources"; - @NonNls public static final String GRADLE_BUILDSETUP_TASKS_SETUP_BUILD = "org.gradle.buildsetup.tasks.SetupBuild"; - @NonNls public static final String GRADLE_API_TASK_CONTAINER = "org.gradle.api.tasks.TaskContainer"; - @NonNls public static final String GRADLE_API_JAVA_ARCHIVES_MANIFEST = "org.gradle.api.java.archives.Manifest"; - @NonNls public static final String GRADLE_API_NAMED_DOMAIN_OBJECT_COLLECTION = "org.gradle.api.NamedDomainObjectCollection"; - @NonNls public static final String GRADLE_API_ARTIFACTS_REPOSITORIES_MAVEN_ARTIFACT_REPOSITORY = "org.gradle.api.artifacts.repositories.MavenArtifactRepository"; - @NonNls public static final String GRADLE_API_ARTIFACTS_MAVEN_MAVEN_DEPLOYER = "org.gradle.api.artifacts.maven.MavenDeployer"; - @NonNls public static final String GRADLE_API_PLUGINS_MAVEN_REPOSITORY_HANDLER_CONVENTION = "org.gradle.api.plugins.MavenRepositoryHandlerConvention"; - @NonNls public static final String GRADLE_API_INITIALIZATION_SETTINGS = "org.gradle.api.initialization.Settings"; + @NonNls + public static final String GRADLE_API_SCRIPT = "org.gradle.api.Script"; + @NonNls + public static final String GRADLE_API_PROJECT = "org.gradle.api.Project"; + @NonNls + public static final String GRADLE_API_CONFIGURATION_CONTAINER = "org.gradle.api.artifacts.ConfigurationContainer"; + @NonNls + public static final String GRADLE_API_CONFIGURATION = "org.gradle.api.artifacts.Configuration"; + @NonNls + public static final String GRADLE_API_ARTIFACT_HANDLER = "org.gradle.api.artifacts.dsl.ArtifactHandler"; + @NonNls + public static final String GRADLE_API_DEPENDENCY_HANDLER = "org.gradle.api.artifacts.dsl.DependencyHandler"; + @NonNls + public static final String GRADLE_API_ARTIFACTS_EXTERNAL_MODULE_DEPENDENCY = "org.gradle.api.artifacts.ExternalModuleDependency"; + @NonNls + public static final String GRADLE_API_ARTIFACTS_MODULE_DEPENDENCY = "org.gradle.api.artifacts.ModuleDependency"; + @NonNls + public static final String GRADLE_API_ARTIFACTS_DEPENDENCY_ARTIFACT = "org.gradle.api.artifacts.DependencyArtifact"; + @NonNls + public static final String GRADLE_API_REPOSITORY_HANDLER = "org.gradle.api.artifacts.dsl.RepositoryHandler"; + @NonNls + public static final String GRADLE_API_SOURCE_DIRECTORY_SET = "org.gradle.api.file.SourceDirectorySet"; + @NonNls + public static final String GRADLE_API_SOURCE_SET = "org.gradle.api.tasks.SourceSet"; + @NonNls + public static final String GRADLE_API_SOURCE_SET_CONTAINER = "org.gradle.api.tasks.SourceSetContainer"; + @NonNls + public static final String GRADLE_API_SCRIPT_HANDLER = "org.gradle.api.initialization.dsl.ScriptHandler"; + @NonNls + public static final String GRADLE_API_TASK = "org.gradle.api.Task"; + @NonNls + public static final String GRADLE_API_DEFAULT_TASK = "org.gradle.api.DefaultTask"; + @NonNls + public static final String GRADLE_API_TASKS_DELETE = "org.gradle.api.tasks.Delete"; + @NonNls + public static final String GRADLE_API_TASKS_BUNDLING_JAR = "org.gradle.api.tasks.bundling.Jar"; + @NonNls + public static final String GRADLE_API_TASKS_BUNDLING_WAR = "org.gradle.api.tasks.bundling.War"; + @NonNls + public static final String GRADLE_API_TASKS_COMPILE_JAVA_COMPILE = "org.gradle.api.tasks.compile.JavaCompile"; + @NonNls + public static final String GRADLE_API_TASKS_WRAPPER_WRAPPER = "org.gradle.api.tasks.wrapper.Wrapper"; + @NonNls + public static final String GRADLE_API_TASKS_JAVADOC_JAVADOC = "org.gradle.api.tasks.javadoc.Javadoc"; + @NonNls + public static final String GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_REPORT_TASK = + "org.gradle.api.tasks.diagnostics.DependencyReportTask"; + @NonNls + public static final String GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_INSIGHT_REPORT_TASK = + "org.gradle.api.tasks.diagnostics.DependencyInsightReportTask"; + @NonNls + public static final String GRADLE_API_TASKS_DIAGNOSTICS_PROJECT_REPORT_TASK = "org.gradle.api.tasks.diagnostics.ProjectReportTask"; + @NonNls + public static final String GRADLE_API_TASKS_DIAGNOSTICS_PROPERTY_REPORT_TASK = "org.gradle.api.tasks.diagnostics.PropertyReportTask"; + @NonNls + public static final String GRADLE_API_TASKS_DIAGNOSTICS_TASK_REPORT_TASK = "org.gradle.api.tasks.diagnostics.TaskReportTask"; + @NonNls + public static final String GRADLE_API_TASKS_TESTING_TEST = "org.gradle.api.tasks.testing.Test"; + @NonNls + public static final String GRADLE_API_TASKS_UPLOAD = "org.gradle.api.tasks.Upload"; + @NonNls + public static final String GRADLE_API_ARTIFACTS_REPOSITORIES_FLAT_DIRECTORY_ARTIFACT_REPOSITORY = + "org.gradle.api.artifacts.repositories.FlatDirectoryArtifactRepository"; + @NonNls + public static final String GRADLE_LANGUAGE_JVM_TASKS_PROCESS_RESOURCES = "org.gradle.language.jvm.tasks.ProcessResources"; + @NonNls + public static final String GRADLE_BUILDSETUP_TASKS_SETUP_BUILD = "org.gradle.buildsetup.tasks.SetupBuild"; + @NonNls + public static final String GRADLE_API_TASK_CONTAINER = "org.gradle.api.tasks.TaskContainer"; + @NonNls + public static final String GRADLE_API_JAVA_ARCHIVES_MANIFEST = "org.gradle.api.java.archives.Manifest"; + @NonNls + public static final String GRADLE_API_NAMED_DOMAIN_OBJECT_COLLECTION = "org.gradle.api.NamedDomainObjectCollection"; + @NonNls + public static final String GRADLE_API_ARTIFACTS_REPOSITORIES_MAVEN_ARTIFACT_REPOSITORY = + "org.gradle.api.artifacts.repositories.MavenArtifactRepository"; + @NonNls + public static final String GRADLE_API_ARTIFACTS_MAVEN_MAVEN_DEPLOYER = "org.gradle.api.artifacts.maven.MavenDeployer"; + @NonNls + public static final String GRADLE_API_PLUGINS_MAVEN_REPOSITORY_HANDLER_CONVENTION = + "org.gradle.api.plugins.MavenRepositoryHandlerConvention"; + @NonNls + public static final String GRADLE_API_INITIALIZATION_SETTINGS = "org.gradle.api.initialization.Settings"; - private GradleCommonClassNames() { - } + private GradleCommonClassNames() { + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsContributor.java index 77aa1aa..3694183 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsContributor.java @@ -32,45 +32,45 @@ @ExtensionImpl public class GradleConfigurationsContributor implements GradleMethodContextContributor { - private static final String CONFIGURATIONS = "configurations"; + private static final String CONFIGURATIONS = "configurations"; - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.isEmpty()) { - return; - } - final String methodCall = methodCallInfo.get(0); + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.isEmpty()) { + return; + } + final String methodCall = methodCallInfo.get(0); - String contributorClass = null; - if (methodCallInfo.size() == 1) { - if (methodCall.startsWith(CONFIGURATIONS + '.')) { - contributorClass = GradleCommonClassNames.GRADLE_API_CONFIGURATION; - } - else if (CONFIGURATIONS.equals(methodCall)) { - contributorClass = GradleCommonClassNames.GRADLE_API_CONFIGURATION_CONTAINER; - if (place instanceof GrReferenceExpressionImpl) { - GradleResolverUtil - .addImplicitVariable(processor, state, (GrReferenceExpressionImpl)place, GradleCommonClassNames.GRADLE_API_CONFIGURATION); - return; + String contributorClass = null; + if (methodCallInfo.size() == 1) { + if (methodCall.startsWith(CONFIGURATIONS + '.')) { + contributorClass = GradleCommonClassNames.GRADLE_API_CONFIGURATION; + } + else if (CONFIGURATIONS.equals(methodCall)) { + contributorClass = GradleCommonClassNames.GRADLE_API_CONFIGURATION_CONTAINER; + if (place instanceof GrReferenceExpressionImpl placeRefExpr) { + GradleResolverUtil.addImplicitVariable(processor, state, placeRefExpr, GradleCommonClassNames.GRADLE_API_CONFIGURATION); + return; + } + } } - } - } - else if (methodCallInfo.size() == 2) { - if (CONFIGURATIONS.equals(methodCallInfo.get(1))) { - contributorClass = GradleCommonClassNames.GRADLE_API_CONFIGURATION_CONTAINER; - if (place instanceof GrReferenceExpressionImpl) { - GradleResolverUtil - .addImplicitVariable(processor, state, (GrReferenceExpressionImpl)place, GradleCommonClassNames.GRADLE_API_CONFIGURATION); - return; + else if (methodCallInfo.size() == 2) { + if (CONFIGURATIONS.equals(methodCallInfo.get(1))) { + contributorClass = GradleCommonClassNames.GRADLE_API_CONFIGURATION_CONTAINER; + if (place instanceof GrReferenceExpressionImpl placeRefExpr) { + GradleResolverUtil.addImplicitVariable(processor, state, placeRefExpr, GradleCommonClassNames.GRADLE_API_CONFIGURATION); + return; + } + } + } + if (contributorClass != null) { + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, contributorClass); } - } - } - if (contributorClass != null) { - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations(psiManager, processor, state, place, contributorClass); } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java index cf08999..f4d889f 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java @@ -45,70 +45,73 @@ */ @ExtensionImpl public class GradleConfigurationsNonCodeMembersContributor extends NonCodeMembersContributor { + private static final String METHOD_GET_BY_NAME = "getByName"; - private static final String METHOD_GET_BY_NAME = "getByName"; + @Override + public void processDynamicElements( + @Nonnull PsiType qualifierType, + PsiClass aClass, + PsiScopeProcessor processor, + PsiElement place, + ResolveState state + ) { + if (place == null || aClass == null) { + return; + } - @Override - public void processDynamicElements(@Nonnull PsiType qualifierType, - PsiClass aClass, - PsiScopeProcessor processor, - PsiElement place, - ResolveState state) { - if (place == null || aClass == null) { - return; - } + if (!GRADLE_API_CONFIGURATION_CONTAINER.equals(aClass.getQualifiedName())) { + return; + } - if (!GRADLE_API_CONFIGURATION_CONTAINER.equals(aClass.getQualifiedName())) { - return; + // Assuming that the method call is equivalent to calling ConfigurationContainer.getByName() + processConfigurationAddition(aClass, processor, state, place); } - // Assuming that the method call is equivalent to calling ConfigurationContainer.getByName() - processConfigurationAddition(aClass, processor, state, place); - } - - @SuppressWarnings("MethodMayBeStatic") - private void processConfigurationAddition(@Nonnull PsiClass dependencyHandlerClass, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { + @SuppressWarnings("MethodMayBeStatic") + private void processConfigurationAddition( + @Nonnull PsiClass dependencyHandlerClass, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { - GrMethodCall call = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); - if (call == null) { - // TODO replace with groovy implicit method - GrReferenceExpressionImpl expression = (GrReferenceExpressionImpl)place; - String expr = expression.getCanonicalText(); - GrImplicitVariableImpl myPsi = new GrImplicitVariableImpl(place.getManager(), expr, GRADLE_API_CONFIGURATION, place); - processor.execute(myPsi, state); - setNavigation(myPsi, dependencyHandlerClass, METHOD_GET_BY_NAME, 1); - return; - } - GrArgumentList args = call.getArgumentList(); - if (args == null) { - return; - } - int argsCount = GradleResolverUtil.getGrMethodArumentsCount(args); + GrMethodCall call = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); + if (call == null) { + // TODO replace with groovy implicit method + GrReferenceExpressionImpl expression = (GrReferenceExpressionImpl)place; + String expr = expression.getCanonicalText(); + GrImplicitVariableImpl myPsi = new GrImplicitVariableImpl(place.getManager(), expr, GRADLE_API_CONFIGURATION, place); + processor.execute(myPsi, state); + setNavigation(myPsi, dependencyHandlerClass, METHOD_GET_BY_NAME, 1); + return; + } + GrArgumentList args = call.getArgumentList(); + if (args == null) { + return; + } + int argsCount = GradleResolverUtil.getGrMethodArumentsCount(args); - argsCount++; // Configuration name is delivered as an argument. + argsCount++; // Configuration name is delivered as an argument. - if (argsCount == 1) { - GrLightMethodBuilder builder = new GrLightMethodBuilder(place.getManager(), METHOD_GET_BY_NAME); - PsiClassType type = PsiType.getJavaLangObject(place.getManager(), place.getResolveScope()); - builder.addParameter(new GrLightParameter("s", type, builder)); - processor.execute(builder, state); + if (argsCount == 1) { + GrLightMethodBuilder builder = new GrLightMethodBuilder(place.getManager(), METHOD_GET_BY_NAME); + PsiClassType type = PsiType.getJavaLangObject(place.getManager(), place.getResolveScope()); + builder.addParameter(new GrLightParameter("s", type, builder)); + processor.execute(builder, state); - argsCount++; // we need method with extra argument of type Closure. - setNavigation(builder, dependencyHandlerClass, METHOD_GET_BY_NAME, argsCount); + argsCount++; // we need method with extra argument of type Closure. + setNavigation(builder, dependencyHandlerClass, METHOD_GET_BY_NAME, argsCount); + } } - } - @SuppressWarnings("MethodMayBeStatic") - private void setNavigation(LightElement element, PsiClass dependencyHandlerClass, String methodName, int parametersCount) { - for (PsiMethod method : dependencyHandlerClass.findMethodsByName(methodName, false)) { - int methodParameterCount = method.getParameterList().getParametersCount(); - if (methodParameterCount == parametersCount && - method.getParameterList().getParameters()[methodParameterCount - 1].getType().equalsToText(GROOVY_LANG_CLOSURE)) { - element.setNavigationElement(method); - } + @SuppressWarnings("MethodMayBeStatic") + private void setNavigation(LightElement element, PsiClass dependencyHandlerClass, String methodName, int parametersCount) { + for (PsiMethod method : dependencyHandlerClass.findMethodsByName(methodName, false)) { + int methodParameterCount = method.getParameterList().getParametersCount(); + if (methodParameterCount == parametersCount && + method.getParameterList().getParameters()[methodParameterCount - 1].getType().equalsToText(GROOVY_LANG_CLOSURE)) { + element.setNavigationElement(method); + } + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java index a1a99ff..7e6f225 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java @@ -33,42 +33,63 @@ */ @ExtensionImpl public class GradleDependenciesContributor implements GradleMethodContextContributor { + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.isEmpty()) { + return; + } - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.isEmpty()) return; + String methodCall = ContainerUtil.getLastItem(methodCallInfo); + if (methodCall == null) { + return; + } - String methodCall = ContainerUtil.getLastItem(methodCallInfo); - if (methodCall == null) return; + if (!StringUtil.equals(methodCall, "dependencies")) { + return; + } - if (!StringUtil.equals(methodCall, "dependencies")) return; - - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - if (methodCallInfo.size() == 2) { - GradleResolverUtil.processDeclarations( - psiManager, processor, state, place, GradleCommonClassNames.GRADLE_API_ARTIFACTS_EXTERNAL_MODULE_DEPENDENCY); - // Assuming that the method call is addition of new dependency into configuration. - PsiClass contributorClass = - psiManager.findClassWithCache(GradleCommonClassNames.GRADLE_API_DEPENDENCY_HANDLER, place.getResolveScope()); - if (contributorClass == null) return; - GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place, "add"); - } - else if (methodCallInfo.size() == 3) { - GradleResolverUtil.processDeclarations(psiManager, processor, state, place, - GradleCommonClassNames.GRADLE_API_DEPENDENCY_HANDLER, - GradleCommonClassNames.GRADLE_API_ARTIFACTS_EXTERNAL_MODULE_DEPENDENCY, - GradleCommonClassNames.GRADLE_API_ARTIFACTS_DEPENDENCY_ARTIFACT, - GradleCommonClassNames.GRADLE_API_PROJECT); - } - else if (methodCallInfo.size() == 4) { - // Assuming that the method call is addition of new dependency into configuration. - PsiClass contributorClass = - psiManager.findClassWithCache(GradleCommonClassNames.GRADLE_API_DEPENDENCY_HANDLER, place.getResolveScope()); - if (contributorClass == null) return; - GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place, "add"); + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + if (methodCallInfo.size() == 2) { + GradleResolverUtil.processDeclarations( + psiManager, + processor, + state, + place, + GradleCommonClassNames.GRADLE_API_ARTIFACTS_EXTERNAL_MODULE_DEPENDENCY + ); + // Assuming that the method call is addition of new dependency into configuration. + PsiClass contributorClass = + psiManager.findClassWithCache(GradleCommonClassNames.GRADLE_API_DEPENDENCY_HANDLER, place.getResolveScope()); + if (contributorClass == null) { + return; + } + GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place, "add"); + } + else if (methodCallInfo.size() == 3) { + GradleResolverUtil.processDeclarations( + psiManager, + processor, + state, + place, + GradleCommonClassNames.GRADLE_API_DEPENDENCY_HANDLER, + GradleCommonClassNames.GRADLE_API_ARTIFACTS_EXTERNAL_MODULE_DEPENDENCY, + GradleCommonClassNames.GRADLE_API_ARTIFACTS_DEPENDENCY_ARTIFACT, + GradleCommonClassNames.GRADLE_API_PROJECT + ); + } + else if (methodCallInfo.size() == 4) { + // Assuming that the method call is addition of new dependency into configuration. + PsiClass contributorClass = + psiManager.findClassWithCache(GradleCommonClassNames.GRADLE_API_DEPENDENCY_HANDLER, place.getResolveScope()); + if (contributorClass == null) { + return; + } + GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place, "add"); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleIdeaPluginScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleIdeaPluginScriptContributor.java index 0c33242..ec5cef4 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleIdeaPluginScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleIdeaPluginScriptContributor.java @@ -24,7 +24,7 @@ */ @ExtensionImpl public class GradleIdeaPluginScriptContributor extends GradleSimpleContributor { - public GradleIdeaPluginScriptContributor() { - super("idea", "org.gradle.plugins.ide.idea.model.IdeaModel"); - } + public GradleIdeaPluginScriptContributor() { + super("idea", "org.gradle.plugins.ide.idea.model.IdeaModel"); + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleImplicitContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleImplicitContributor.java index e719e61..373aca6 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleImplicitContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleImplicitContributor.java @@ -52,161 +52,197 @@ */ @ExtensionImpl public class GradleImplicitContributor implements GradleMethodContextContributor { - private final static Map BUILT_IN_TASKS = ContainerUtil.newHashMap( - new Pair("assemble", GRADLE_API_DEFAULT_TASK), - new Pair("build", GRADLE_API_DEFAULT_TASK), - new Pair("buildDependents", GRADLE_API_DEFAULT_TASK), - new Pair("buildNeeded", GRADLE_API_DEFAULT_TASK), - new Pair("clean", GRADLE_API_TASKS_DELETE), - new Pair("jar", GRADLE_API_TASKS_BUNDLING_JAR), - new Pair("war", GRADLE_API_TASKS_BUNDLING_WAR), - new Pair("classes", GRADLE_API_DEFAULT_TASK), - new Pair("compileJava", GRADLE_API_TASKS_COMPILE_JAVA_COMPILE), - new Pair("compileTestJava", GRADLE_API_DEFAULT_TASK), - new Pair("processTestResources", GRADLE_API_DEFAULT_TASK), - new Pair("testClasses", GRADLE_API_DEFAULT_TASK), - new Pair("processResources", GRADLE_LANGUAGE_JVM_TASKS_PROCESS_RESOURCES), - new Pair("setupBuild", GRADLE_BUILDSETUP_TASKS_SETUP_BUILD), - new Pair("wrapper", GRADLE_API_TASKS_WRAPPER_WRAPPER), - new Pair("javadoc", GRADLE_API_TASKS_JAVADOC_JAVADOC), - new Pair("dependencies", GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_REPORT_TASK), - new Pair("dependencyInsight", GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_INSIGHT_REPORT_TASK), - new Pair("projects", GRADLE_API_TASKS_DIAGNOSTICS_PROJECT_REPORT_TASK), - new Pair("properties", GRADLE_API_TASKS_DIAGNOSTICS_PROPERTY_REPORT_TASK), - new Pair("tasks", GRADLE_API_TASKS_DIAGNOSTICS_TASK_REPORT_TASK), - new Pair("check", GRADLE_API_DEFAULT_TASK), - new Pair("test", GRADLE_API_TASKS_TESTING_TEST), - new Pair("uploadArchives", GRADLE_API_TASKS_UPLOAD) - ); - - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.isEmpty()) { - checkForAvailableTasks(0, place.getText(), processor, state, place); - return; - } + private final static Map BUILT_IN_TASKS = ContainerUtil.newHashMap( + new Pair("assemble", GRADLE_API_DEFAULT_TASK), + new Pair("build", GRADLE_API_DEFAULT_TASK), + new Pair("buildDependents", GRADLE_API_DEFAULT_TASK), + new Pair("buildNeeded", GRADLE_API_DEFAULT_TASK), + new Pair("clean", GRADLE_API_TASKS_DELETE), + new Pair("jar", GRADLE_API_TASKS_BUNDLING_JAR), + new Pair("war", GRADLE_API_TASKS_BUNDLING_WAR), + new Pair("classes", GRADLE_API_DEFAULT_TASK), + new Pair("compileJava", GRADLE_API_TASKS_COMPILE_JAVA_COMPILE), + new Pair("compileTestJava", GRADLE_API_DEFAULT_TASK), + new Pair("processTestResources", GRADLE_API_DEFAULT_TASK), + new Pair("testClasses", GRADLE_API_DEFAULT_TASK), + new Pair("processResources", GRADLE_LANGUAGE_JVM_TASKS_PROCESS_RESOURCES), + new Pair("setupBuild", GRADLE_BUILDSETUP_TASKS_SETUP_BUILD), + new Pair("wrapper", GRADLE_API_TASKS_WRAPPER_WRAPPER), + new Pair("javadoc", GRADLE_API_TASKS_JAVADOC_JAVADOC), + new Pair("dependencies", GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_REPORT_TASK), + new Pair("dependencyInsight", GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_INSIGHT_REPORT_TASK), + new Pair("projects", GRADLE_API_TASKS_DIAGNOSTICS_PROJECT_REPORT_TASK), + new Pair("properties", GRADLE_API_TASKS_DIAGNOSTICS_PROPERTY_REPORT_TASK), + new Pair("tasks", GRADLE_API_TASKS_DIAGNOSTICS_TASK_REPORT_TASK), + new Pair("check", GRADLE_API_DEFAULT_TASK), + new Pair("test", GRADLE_API_TASKS_TESTING_TEST), + new Pair("uploadArchives", GRADLE_API_TASKS_UPLOAD) + ); + + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.isEmpty()) { + checkForAvailableTasks(0, place.getText(), processor, state, place); + return; + } - final String methodCall = consulo.util.collection.ContainerUtil.getLastItem(methodCallInfo); - if (methodCall == null) return; + final String methodCall = consulo.util.collection.ContainerUtil.getLastItem(methodCallInfo); + if (methodCall == null) { + return; + } - if (!methodCall.equals("task")) { - if (methodCallInfo.size() == 1) { - checkForAvailableTasks(1, place.getText(), processor, state, place); - } - if (methodCallInfo.size() == 2) { - processAvailableTasks(methodCallInfo, methodCall, processor, state, place); - } - } + if (!methodCall.equals("task")) { + if (methodCallInfo.size() == 1) { + checkForAvailableTasks(1, place.getText(), processor, state, place); + } + if (methodCallInfo.size() == 2) { + processAvailableTasks(methodCallInfo, methodCall, processor, state, place); + } + } - if (methodCallInfo.size() >= 3 && Arrays.equals( - ContainerUtil.ar("dirs", "flatDir", "repositories"), methodCallInfo.subList(0, 3).toArray())) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations( - psiManager, processor, state, place, GRADLE_API_ARTIFACTS_REPOSITORIES_FLAT_DIRECTORY_ARTIFACT_REPOSITORY); - } + if (methodCallInfo.size() >= 3 && Arrays.equals( + ContainerUtil.ar("dirs", "flatDir", "repositories"), + methodCallInfo.subList(0, 3).toArray() + )) { + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations( + psiManager, + processor, + state, + place, + GRADLE_API_ARTIFACTS_REPOSITORIES_FLAT_DIRECTORY_ARTIFACT_REPOSITORY + ); + } - if (methodCallInfo.size() == 3) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - if ("manifest".equals(methodCallInfo.get(1)) && "jar".equals(methodCallInfo.get(2))) { - GradleResolverUtil.processDeclarations( - psiManager, processor, state, place, GRADLE_API_JAVA_ARCHIVES_MANIFEST); - } - } + if (methodCallInfo.size() == 3) { + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + if ("manifest".equals(methodCallInfo.get(1)) && "jar".equals(methodCallInfo.get(2))) { + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GRADLE_API_JAVA_ARCHIVES_MANIFEST); + } + } - if (place instanceof GrExpression && GradleResolverUtil.getTypeOf((GrExpression)place) == null) { - GrClosableBlock closableBlock = GradleResolverUtil.findParent(place, GrClosableBlock.class); - if (closableBlock != null && closableBlock.getParent() instanceof GrMethodCallExpression) { - PsiType psiType = GradleResolverUtil.getTypeOf(((GrExpression)closableBlock.getParent())); - if (psiType != null) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations( - psiManager, processor, state, place, psiType.getCanonicalText()); + if (place instanceof GrExpression && GradleResolverUtil.getTypeOf((GrExpression)place) == null) { + GrClosableBlock closableBlock = GradleResolverUtil.findParent(place, GrClosableBlock.class); + if (closableBlock != null && closableBlock.getParent() instanceof GrMethodCallExpression methodCallExpression) { + PsiType psiType = GradleResolverUtil.getTypeOf(methodCallExpression); + if (psiType != null) { + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, psiType.getCanonicalText()); + } + } } - } - } - } - - public static void processImplicitDeclarations(@Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (!place.getText().equals("resources")) { - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GRADLE_API_PROJECT); - } - } - - private static void checkForAvailableTasks(int level, - @Nullable String taskName, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (taskName == null) return; - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - PsiClass gradleApiProjectClass = psiManager.findClassWithCache(GRADLE_API_PROJECT, place.getResolveScope()); - if (canBeMethodOf(taskName, gradleApiProjectClass)) return; - if (canBeMethodOf(GroovyPropertyUtils.getGetterNameNonBoolean(taskName), gradleApiProjectClass)) return; - - final String className = BUILT_IN_TASKS.get(taskName); - if (className != null) { - if (level <= 1) { - GradleResolverUtil.addImplicitVariable(processor, state, place, className); - } - processTask(taskName, className, psiManager, processor, state, place); - return; } - Module module = ModuleUtilCore.findModuleForPsiElement(place); - if (module == null) return; - String path = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY); - GradleLocalSettings localSettings = GradleLocalSettings.getInstance(place.getProject()); - Collection taskPojos = localSettings.getAvailableTasks().get(path); - if (taskPojos == null) return; - - for (ExternalTaskPojo taskPojo : taskPojos) { - if (taskName.equals(taskPojo.getName())) { - processTask(taskName, GRADLE_API_TASK, psiManager, processor, state, place); - return; - } + public static void processImplicitDeclarations( + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (!place.getText().equals("resources")) { + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GRADLE_API_PROJECT); + } } - } - - private static void processTask(@Nonnull String taskName, - @Nonnull String fqName, - @Nonnull GroovyPsiManager psiManager, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (taskName.equals(place.getText())) { - if (!(place instanceof GrClosableBlock)) { - GrLightMethodBuilder methodBuilder = GradleResolverUtil.createMethodWithClosure(taskName, fqName, null, place, psiManager); - if (methodBuilder == null) return; - processor.execute(methodBuilder, state); - PsiClass contributorClass = - psiManager.findClassWithCache(fqName, place.getResolveScope()); - if (contributorClass == null) return; - GradleResolverUtil.processMethod(taskName, contributorClass, processor, state, place); - } + + private static void checkForAvailableTasks( + int level, + @Nullable String taskName, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (taskName == null) { + return; + } + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + PsiClass gradleApiProjectClass = psiManager.findClassWithCache(GRADLE_API_PROJECT, place.getResolveScope()); + if (canBeMethodOf(taskName, gradleApiProjectClass)) { + return; + } + if (canBeMethodOf(GroovyPropertyUtils.getGetterNameNonBoolean(taskName), gradleApiProjectClass)) { + return; + } + + final String className = BUILT_IN_TASKS.get(taskName); + if (className != null) { + if (level <= 1) { + GradleResolverUtil.addImplicitVariable(processor, state, place, className); + } + processTask(taskName, className, psiManager, processor, state, place); + return; + } + + Module module = ModuleUtilCore.findModuleForPsiElement(place); + if (module == null) { + return; + } + String path = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY); + GradleLocalSettings localSettings = GradleLocalSettings.getInstance(place.getProject()); + Collection taskPojos = localSettings.getAvailableTasks().get(path); + if (taskPojos == null) { + return; + } + + for (ExternalTaskPojo taskPojo : taskPojos) { + if (taskName.equals(taskPojo.getName())) { + processTask(taskName, GRADLE_API_TASK, psiManager, processor, state, place); + return; + } + } } - else { - GradleResolverUtil.processDeclarations(psiManager, processor, state, place, fqName); + + private static void processTask( + @Nonnull String taskName, + @Nonnull String fqName, + @Nonnull GroovyPsiManager psiManager, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (taskName.equals(place.getText())) { + if (!(place instanceof GrClosableBlock)) { + GrLightMethodBuilder methodBuilder = + GradleResolverUtil.createMethodWithClosure(taskName, fqName, null, place, psiManager); + if (methodBuilder == null) { + return; + } + processor.execute(methodBuilder, state); + PsiClass contributorClass = psiManager.findClassWithCache(fqName, place.getResolveScope()); + if (contributorClass == null) { + return; + } + GradleResolverUtil.processMethod(taskName, contributorClass, processor, state, place); + } + } + else { + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, fqName); + } } - } - - private static void processAvailableTasks(List methodCallInfo, @Nonnull String taskName, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - PsiClass gradleApiProjectClass = psiManager.findClassWithCache(GRADLE_API_PROJECT, place.getResolveScope()); - if (canBeMethodOf(taskName, gradleApiProjectClass)) return; - if (canBeMethodOf(GroovyPropertyUtils.getGetterNameNonBoolean(taskName), gradleApiProjectClass)) return; - final String className = BUILT_IN_TASKS.get(taskName); - if (className != null) { - GradleResolverUtil.processDeclarations( - methodCallInfo.size() > 0 ? methodCallInfo.get(0) : null, psiManager, processor, state, place, className); + + private static void processAvailableTasks( + List methodCallInfo, + @Nonnull String taskName, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + PsiClass gradleApiProjectClass = psiManager.findClassWithCache(GRADLE_API_PROJECT, place.getResolveScope()); + if (canBeMethodOf(taskName, gradleApiProjectClass)) { + return; + } + if (canBeMethodOf(GroovyPropertyUtils.getGetterNameNonBoolean(taskName), gradleApiProjectClass)) { + return; + } + final String className = BUILT_IN_TASKS.get(taskName); + if (className != null) { + String methodName = methodCallInfo.size() > 0 ? methodCallInfo.get(0) : null; + GradleResolverUtil.processDeclarations(methodName, psiManager, processor, state, place, className); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenArtifactRepositoryContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenArtifactRepositoryContributor.java index 8793642..38f32a2 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenArtifactRepositoryContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenArtifactRepositoryContributor.java @@ -30,9 +30,9 @@ * * e.g. * repositories { - * maven { - * url "http://snapshots.repository.codehaus.org/" - * } + * maven { + * url "http://snapshots.repository.codehaus.org/" + * } * } * * @author Vladislav.Soroka @@ -40,23 +40,24 @@ */ @ExtensionImpl public class GradleMavenArtifactRepositoryContributor implements GradleMethodContextContributor { - - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.isEmpty() || methodCallInfo.size() < 3 || - !"repositories".equals(methodCallInfo.get(2)) || !"maven".equals(methodCallInfo.get(1))) { - return; + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.isEmpty() || methodCallInfo.size() < 3 + || !"repositories".equals(methodCallInfo.get(2)) || !"maven".equals(methodCallInfo.get(1))) { + return; + } + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + String fqName = GradleCommonClassNames.GRADLE_API_ARTIFACTS_REPOSITORIES_MAVEN_ARTIFACT_REPOSITORY; + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, fqName); + PsiClass contributorClass = psiManager.findClassWithCache(fqName, place.getResolveScope()); + if (contributorClass == null) { + return; + } + GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place); } - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations( - psiManager, processor, state, place, - GradleCommonClassNames.GRADLE_API_ARTIFACTS_REPOSITORIES_MAVEN_ARTIFACT_REPOSITORY); - PsiClass contributorClass = psiManager.findClassWithCache( - GradleCommonClassNames.GRADLE_API_ARTIFACTS_REPOSITORIES_MAVEN_ARTIFACT_REPOSITORY, place.getResolveScope()); - if (contributorClass == null) return; - GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place); - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenDeployerContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenDeployerContributor.java index 0f6edd3..20ff71c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenDeployerContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenDeployerContributor.java @@ -30,9 +30,9 @@ * * e.g. * repositories { - * maven { - * url "http://snapshots.repository.codehaus.org/" - * } + * maven { + * url "http://snapshots.repository.codehaus.org/" + * } * } * * @author Vladislav.Soroka @@ -40,23 +40,24 @@ */ @ExtensionImpl public class GradleMavenDeployerContributor implements GradleMethodContextContributor { - - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.isEmpty() || methodCallInfo.size() < 3 || - !"repositories".equals(methodCallInfo.get(2)) || !"mavenDeployer".equals(methodCallInfo.get(1))) { - return; + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.isEmpty() || methodCallInfo.size() < 3 + || !"repositories".equals(methodCallInfo.get(2)) || !"mavenDeployer".equals(methodCallInfo.get(1))) { + return; + } + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + String fqName = GradleCommonClassNames.GRADLE_API_ARTIFACTS_MAVEN_MAVEN_DEPLOYER; + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, fqName); + PsiClass contributorClass = psiManager.findClassWithCache(fqName, place.getResolveScope()); + if (contributorClass == null) { + return; + } + GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place); } - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations( - psiManager, processor, state, place, - GradleCommonClassNames.GRADLE_API_ARTIFACTS_MAVEN_MAVEN_DEPLOYER); - PsiClass contributorClass = psiManager.findClassWithCache( - GradleCommonClassNames.GRADLE_API_ARTIFACTS_MAVEN_MAVEN_DEPLOYER, place.getResolveScope()); - if (contributorClass == null) return; - GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place); - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java index 1c86f92..4dcbac0 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java @@ -47,21 +47,21 @@ */ @ExtensionAPI(ComponentScope.APPLICATION) public interface GradleMethodContextContributor { + ExtensionPointName EP_NAME = ExtensionPointName.create(GradleMethodContextContributor.class); - ExtensionPointName EP_NAME = - ExtensionPointName.create(GradleMethodContextContributor.class); - - /** - * Tries to resolve target element. - * - * @param methodCallInfo information about method call hierarchy which points to the target place. Every entry is a method name - * and the deepest one is assumed to be added the head - * @param processor the processor receiving the declarations. - * @param state current resolve state - * @param place the original element from which the tree up walk was initiated. - */ - void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place); + /** + * Tries to resolve target element. + * + * @param methodCallInfo information about method call hierarchy which points to the target place. Every entry is a method name + * and the deepest one is assumed to be added the head + * @param processor the processor receiving the declarations. + * @param state current resolve state + * @param place the original element from which the tree up walk was initiated. + */ + void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ); } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java index 90fc6ee..134ffe1 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java @@ -23,8 +23,11 @@ */ @ExtensionImpl public class GradleRepositoriesContributor extends GradleSimpleContributor { - public GradleRepositoriesContributor() { - super("repositories", GradleCommonClassNames.GRADLE_API_REPOSITORY_HANDLER, - GradleCommonClassNames.GRADLE_API_PLUGINS_MAVEN_REPOSITORY_HANDLER_CONVENTION); - } + public GradleRepositoriesContributor() { + super( + "repositories", + GradleCommonClassNames.GRADLE_API_REPOSITORY_HANDLER, + GradleCommonClassNames.GRADLE_API_PLUGINS_MAVEN_REPOSITORY_HANDLER_CONVENTION + ); + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java index 16ea997..12d1950 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java @@ -48,204 +48,221 @@ * @since 8/30/13 */ public class GradleResolverUtil { - - public static int getGrMethodArumentsCount(@Nonnull GrArgumentList args) { - int argsCount = 0; - boolean namedArgProcessed = false; - for (GroovyPsiElement arg : args.getAllArguments()) { - if (arg instanceof GrNamedArgument) { - if (!namedArgProcessed) { - namedArgProcessed = true; - argsCount++; + public static int getGrMethodArumentsCount(@Nonnull GrArgumentList args) { + int argsCount = 0; + boolean namedArgProcessed = false; + for (GroovyPsiElement arg : args.getAllArguments()) { + if (arg instanceof GrNamedArgument) { + if (!namedArgProcessed) { + namedArgProcessed = true; + argsCount++; + } + } + else { + argsCount++; + } } - } - else { - argsCount++; - } + return argsCount; } - return argsCount; - } - - public static void addImplicitVariable(@Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull GrReferenceExpressionImpl expression, - @Nonnull String type) { - if (expression.getQualifier() == null) { - PsiVariable myPsi = new GrImplicitVariableImpl(expression.getManager(), expression.getReferenceName(), type, expression); - processor.execute(myPsi, state); + + public static void addImplicitVariable( + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull GrReferenceExpressionImpl expression, + @Nonnull String type + ) { + if (expression.getQualifier() == null) { + PsiVariable myPsi = new GrImplicitVariableImpl(expression.getManager(), expression.getReferenceName(), type, expression); + processor.execute(myPsi, state); + } } - } - - public static void addImplicitVariable(@Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement element, - @Nonnull String type) { - PsiVariable myPsi = new GrImplicitVariableImpl(element.getManager(), element.getText(), type, element); - processor.execute(myPsi, state); - } - - - @Nullable - public static GrLightMethodBuilder createMethodWithClosure(@Nonnull String name, - @Nullable String returnType, - @Nullable String closureTypeParameter, - @Nonnull PsiElement place, - @Nonnull GroovyPsiManager psiManager) { - PsiClassType closureType; - PsiClass closureClass = - psiManager.findClassWithCache(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, place.getResolveScope()); - if (closureClass == null) return null; - - if (closureClass.getTypeParameters().length != 1) { - GradleLog.LOG.debug(String.format("Unexpected type parameters found for closureClass(%s) : (%s)", - closureClass, Arrays.toString(closureClass.getTypeParameters()))); - return null; + + public static void addImplicitVariable( + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement element, + @Nonnull String type + ) { + PsiVariable myPsi = new GrImplicitVariableImpl(element.getManager(), element.getText(), type, element); + processor.execute(myPsi, state); } - PsiElementFactory factory = JavaPsiFacade.getElementFactory(place.getManager().getProject()); + @Nullable + public static GrLightMethodBuilder createMethodWithClosure( + @Nonnull String name, + @Nullable String returnType, + @Nullable String closureTypeParameter, + @Nonnull PsiElement place, + @Nonnull GroovyPsiManager psiManager + ) { + PsiClassType closureType; + PsiClass closureClass = psiManager.findClassWithCache(GroovyCommonClassNames.GROOVY_LANG_CLOSURE, place.getResolveScope()); + if (closureClass == null) { + return null; + } - if (closureTypeParameter != null) { - PsiClassType closureClassTypeParameter = - factory.createTypeByFQClassName(closureTypeParameter, place.getResolveScope()); - closureType = factory.createType(closureClass, closureClassTypeParameter); - } - else { - PsiClassType closureClassTypeParameter = - factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_OBJECT, place.getResolveScope()); - closureType = factory.createType(closureClass, closureClassTypeParameter); - } + if (closureClass.getTypeParameters().length != 1) { + GradleLog.LOG.debug(String.format("Unexpected type parameters found for closureClass(%s) : (%s)", + closureClass, Arrays.toString(closureClass.getTypeParameters()) + )); + return null; + } - GrLightMethodBuilder methodWithClosure = new GrLightMethodBuilder(place.getManager(), name); - GrLightParameter closureParameter = new GrLightParameter("closure", closureType, methodWithClosure); - methodWithClosure.addParameter(closureParameter); - PsiClassType retType = factory.createTypeByFQClassName( - returnType != null ? returnType : JavaClassNames.JAVA_LANG_OBJECT, place.getResolveScope()); - methodWithClosure.setReturnType(retType); - methodWithClosure.setContainingClass(retType.resolve()); - return methodWithClosure; - } - - public static void processMethod(@Nonnull String methodName, - @Nonnull PsiClass handlerClass, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - processMethod(methodName, handlerClass, processor, state, place, null); - } - - public static void processMethod(@Nonnull String methodName, - @Nonnull PsiClass handlerClass, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place, - @Nullable String defaultMethodName) { - GrLightMethodBuilder builder = new GrLightMethodBuilder(place.getManager(), methodName); - PsiElementFactory factory = JavaPsiFacade.getElementFactory(place.getManager().getProject()); - PsiType type = new PsiArrayType(factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_OBJECT, place.getResolveScope())); - builder.addParameter(new GrLightParameter("param", type, builder)); - PsiClassType retType = factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_OBJECT, place.getResolveScope()); - builder.setReturnType(retType); - processor.execute(builder, state); - - GrMethodCall call = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); - if (call == null) { - return; + PsiElementFactory factory = JavaPsiFacade.getElementFactory(place.getManager().getProject()); + + if (closureTypeParameter != null) { + PsiClassType closureClassTypeParameter = factory.createTypeByFQClassName(closureTypeParameter, place.getResolveScope()); + closureType = factory.createType(closureClass, closureClassTypeParameter); + } + else { + PsiClassType closureClassTypeParameter = + factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_OBJECT, place.getResolveScope()); + closureType = factory.createType(closureClass, closureClassTypeParameter); + } + + GrLightMethodBuilder methodWithClosure = new GrLightMethodBuilder(place.getManager(), name); + GrLightParameter closureParameter = new GrLightParameter("closure", closureType, methodWithClosure); + methodWithClosure.addParameter(closureParameter); + PsiClassType retType = factory.createTypeByFQClassName( + returnType != null ? returnType : JavaClassNames.JAVA_LANG_OBJECT, + place.getResolveScope() + ); + methodWithClosure.setReturnType(retType); + methodWithClosure.setContainingClass(retType.resolve()); + return methodWithClosure; } - GrArgumentList args = call.getArgumentList(); - if (args == null) { - return; + + public static void processMethod( + @Nonnull String methodName, + @Nonnull PsiClass handlerClass, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + processMethod(methodName, handlerClass, processor, state, place, null); } - int argsCount = getGrMethodArumentsCount(args); - argsCount++; // Configuration name is delivered as an argument. + public static void processMethod( + @Nonnull String methodName, + @Nonnull PsiClass handlerClass, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place, + @Nullable String defaultMethodName + ) { + GrLightMethodBuilder builder = new GrLightMethodBuilder(place.getManager(), methodName); + PsiElementFactory factory = JavaPsiFacade.getElementFactory(place.getManager().getProject()); + PsiType type = new PsiArrayType(factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_OBJECT, place.getResolveScope())); + builder.addParameter(new GrLightParameter("param", type, builder)); + PsiClassType retType = factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_OBJECT, place.getResolveScope()); + builder.setReturnType(retType); + processor.execute(builder, state); + + GrMethodCall call = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); + if (call == null) { + return; + } + GrArgumentList args = call.getArgumentList(); + if (args == null) { + return; + } + + int argsCount = getGrMethodArumentsCount(args); + argsCount++; // Configuration name is delivered as an argument. + + // handle setter's shortcut facilities + final String setter = GroovyPropertyUtils.getSetterName(methodName); + for (PsiMethod method : handlerClass.findMethodsByName(setter, false)) { + if (method.getParameterList().getParametersCount() == 1) { + builder.setNavigationElement(method); + return; + } + } + + for (PsiMethod method : handlerClass.findMethodsByName(methodName, false)) { + if (method.getParameterList().getParametersCount() == argsCount) { + builder.setNavigationElement(method); + return; + } + } - // handle setter's shortcut facilities - final String setter = GroovyPropertyUtils.getSetterName(methodName); - for (PsiMethod method : handlerClass.findMethodsByName(setter, false)) { - if (method.getParameterList().getParametersCount() == 1) { - builder.setNavigationElement(method); - return; - } + if (defaultMethodName != null) { + for (PsiMethod method : handlerClass.findMethodsByName(defaultMethodName, false)) { + if (method.getParameterList().getParametersCount() == argsCount) { + builder.setNavigationElement(method); + return; + } + } + } } - for (PsiMethod method : handlerClass.findMethodsByName(methodName, false)) { - if (method.getParameterList().getParametersCount() == argsCount) { - builder.setNavigationElement(method); - return; - } + public static void processDeclarations( + @Nonnull GroovyPsiManager psiManager, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place, + @Nonnull String... fqNames + ) { + processDeclarations(null, psiManager, processor, state, place, fqNames); } - if (defaultMethodName != null) { - for (PsiMethod method : handlerClass.findMethodsByName(defaultMethodName, false)) { - if (method.getParameterList().getParametersCount() == argsCount) { - builder.setNavigationElement(method); - return; + public static void processDeclarations( + @Nullable String methodName, + @Nonnull GroovyPsiManager psiManager, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place, + @Nonnull String... fqNames + ) { + for (String fqName : fqNames) { + PsiClass psiClass = psiManager.findClassWithCache(fqName, place.getResolveScope()); + if (psiClass != null) { + psiClass.processDeclarations(processor, state, null, place); + if (methodName != null) { + processMethod(methodName, psiClass, processor, state, place); + } + } } - } } - } - - public static void processDeclarations(@Nonnull GroovyPsiManager psiManager, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place, - @Nonnull String... fqNames) { - processDeclarations(null, psiManager, processor, state, place, fqNames); - } - - public static void processDeclarations(@Nullable String methodName, - @Nonnull GroovyPsiManager psiManager, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place, - @Nonnull String... fqNames) { - for (String fqName : fqNames) { - PsiClass psiClass = psiManager.findClassWithCache(fqName, place.getResolveScope()); - if (psiClass != null) { - psiClass.processDeclarations(processor, state, null, place); - if (methodName != null) { - processMethod(methodName, psiClass, processor, state, place); + + @Nullable + public static PsiElement findParent(@Nonnull PsiElement element, int level) { + PsiElement parent = element; + do { + parent = parent.getParent(); } - } + while (parent != null && --level > 0); + return parent; } - } - @Nullable - public static PsiElement findParent(@Nonnull PsiElement element, int level) { - PsiElement parent = element; - do { - parent = parent.getParent(); + @Nullable + public static T findParent(@Nonnull PsiElement element, Class clazz) { + PsiElement parent = element; + do { + parent = parent.getParent(); + if (clazz.isInstance(parent)) { + //noinspection unchecked + return (T)parent; + } + } + while (parent != null && !(parent instanceof GroovyFile)); + return null; + } + + public static boolean canBeMethodOf(@Nullable String methodName, @Nullable PsiClass aClass) { + return methodName != null && aClass != null && aClass.findMethodsByName(methodName, true).length != 0; } - while (parent != null && --level > 0); - return parent; - } - - @Nullable - public static T findParent(@Nonnull PsiElement element, Class clazz) { - PsiElement parent = element; - do { - parent = parent.getParent(); - if (clazz.isInstance(parent)) { - //noinspection unchecked - return (T)parent; - } + + @Nullable + public static PsiType getTypeOf(@Nullable final GrExpression expression) { + if (expression == null) { + return null; + } + return RecursionManager.doPreventingRecursion(expression, true, () -> expression.getNominalType()); + } + + public static boolean isLShiftElement(@Nullable PsiElement psiElement) { + return psiElement instanceof GrBinaryExpression + && GroovyElementTypes.COMPOSITE_LSHIFT_SIGN.equals(GrBinaryExpression.class.cast(psiElement).getOperationTokenType()); } - while (parent != null && !(parent instanceof GroovyFile)); - return null; - } - - public static boolean canBeMethodOf(@Nullable String methodName, @Nullable PsiClass aClass) { - return methodName != null && aClass != null && aClass.findMethodsByName(methodName, true).length != 0; - } - - @Nullable - public static PsiType getTypeOf(@Nullable final GrExpression expression) { - if (expression == null) return null; - return RecursionManager.doPreventingRecursion(expression, true, () -> expression.getNominalType()); - } - - public static boolean isLShiftElement(@Nullable PsiElement psiElement) { - return (psiElement instanceof GrBinaryExpression && - GroovyElementTypes.COMPOSITE_LSHIFT_SIGN.equals(GrBinaryExpression.class.cast(psiElement).getOperationTokenType())); - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java index 8251632..7008428 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java @@ -35,36 +35,44 @@ */ @ExtensionImpl public class GradleRootContributor implements GradleMethodContextContributor { - private final static Set BUILD_SCRIPT_BLOCKS = Set.of( - "subprojects", - "allprojects", - "beforeEvaluate", - "afterEvaluate", - SOURCE_SETS); + private final static Set BUILD_SCRIPT_BLOCKS = Set.of( + "subprojects", + "allprojects", + "beforeEvaluate", + "afterEvaluate", + SOURCE_SETS + ); - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.size() > 2) { - return; - } + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.size() > 2) { + return; + } - if (methodCallInfo.size() == 2 && !BUILD_SCRIPT_BLOCKS.contains(methodCallInfo.get(1))) { - return; - } - if (methodCallInfo.size() > 0) { - String method = ContainerUtil.getLastItem(methodCallInfo); - if (method != null && StringUtil.startsWith(method, SOURCE_SETS)) { - GradleSourceSetsContributor.getInstance().process(methodCallInfo, processor, state, place); - return; - } - } + if (methodCallInfo.size() == 2 && !BUILD_SCRIPT_BLOCKS.contains(methodCallInfo.get(1))) { + return; + } + if (methodCallInfo.size() > 0) { + String method = ContainerUtil.getLastItem(methodCallInfo); + if (method != null && StringUtil.startsWith(method, SOURCE_SETS)) { + GradleSourceSetsContributor.getInstance().process(methodCallInfo, processor, state, place); + return; + } + } - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations(methodCallInfo.size() > 0 ? methodCallInfo.get(0) : null, - psiManager, processor, state, place, - GradleCommonClassNames.GRADLE_API_PROJECT); - } + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations( + methodCallInfo.size() > 0 ? methodCallInfo.get(0) : null, + psiManager, + processor, + state, + place, + GradleCommonClassNames.GRADLE_API_PROJECT + ); + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java index 1c6f6e6..9a6040a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java @@ -42,55 +42,57 @@ */ @ExtensionImpl public class GradleScriptContributor extends NonCodeMembersContributor { + public final static Set BUILD_PROJECT_SCRIPT_BLOCKS = ContainerUtil.newHashSet( + "project", + "configure", + "subprojects", + "allprojects", + "buildscript" + ); - public final static Set BUILD_PROJECT_SCRIPT_BLOCKS = ContainerUtil.newHashSet( - "project", - "configure", - "subprojects", - "allprojects", - "buildscript" - ); + @Override + public void processDynamicElements( + @Nonnull PsiType qualifierType, + PsiClass aClass, + PsiScopeProcessor processor, + PsiElement place, + ResolveState state + ) { + if (place == null) { + return; + } + if (!(aClass instanceof GroovyScriptClass)) { + return; + } - @Override - public void processDynamicElements(@Nonnull PsiType qualifierType, - PsiClass aClass, - PsiScopeProcessor processor, - PsiElement place, - ResolveState state) { - if (place == null) { - return; - } - - if (!(aClass instanceof GroovyScriptClass)) { - return; - } + PsiFile file = aClass.getContainingFile(); + if (file == null || !FileUtil.extensionEquals(file.getName(), GradleConstants.EXTENSION) + || GradleConstants.SETTINGS_FILE_NAME.equals(file.getName())) { + return; + } - PsiFile file = aClass.getContainingFile(); - if (file == null || !FileUtil.extensionEquals(file.getName(), GradleConstants.EXTENSION) - || GradleConstants.SETTINGS_FILE_NAME.equals(file.getName())) return; + List methodInfo = new ArrayList<>(); + for (GrMethodCall current = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); + current != null; + current = PsiTreeUtil.getParentOfType(current, GrMethodCall.class)) { + GrExpression expression = current.getInvokedExpression(); + if (expression == null) { + continue; + } + String text = expression.getText(); + if (text != null) { + methodInfo.add(text); + } + } - List methodInfo = new ArrayList<>(); - for (GrMethodCall current = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); - current != null; - current = PsiTreeUtil.getParentOfType(current, GrMethodCall.class)) { - GrExpression expression = current.getInvokedExpression(); - if (expression == null) { - continue; - } - String text = expression.getText(); - if (text != null) { - methodInfo.add(text); - } - } - - final String methodCall = ContainerUtil.getLastItem(methodInfo); - if (methodInfo.size() > 1 && BUILD_PROJECT_SCRIPT_BLOCKS.contains(methodCall)) { - methodInfo.remove(methodInfo.size() - 1); - } + final String methodCall = ContainerUtil.getLastItem(methodInfo); + if (methodInfo.size() > 1 && BUILD_PROJECT_SCRIPT_BLOCKS.contains(methodCall)) { + methodInfo.remove(methodInfo.size() - 1); + } - for (GradleMethodContextContributor contributor : GradleMethodContextContributor.EP_NAME.getExtensions()) { - contributor.process(methodInfo, processor, state, place); + for (GradleMethodContextContributor contributor : GradleMethodContextContributor.EP_NAME.getExtensions()) { + contributor.process(methodInfo, processor, state, place); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java index 83c108d..c9a9229 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java @@ -35,27 +35,34 @@ */ @ExtensionImpl public class GradleSettingsScriptContributor extends NonCodeMembersContributor { + @Override + public void processDynamicElements( + @Nonnull PsiType qualifierType, + PsiClass aClass, + PsiScopeProcessor processor, + PsiElement place, + ResolveState state + ) { + if (place == null) { + return; + } - @Override - public void processDynamicElements(@Nonnull PsiType qualifierType, - PsiClass aClass, - PsiScopeProcessor processor, - PsiElement place, - ResolveState state) { - if (place == null) { - return; - } + if (!(aClass instanceof GroovyScriptClass)) { + return; + } - if (!(aClass instanceof GroovyScriptClass)) { - return; - } + PsiFile file = aClass.getContainingFile(); + if (file == null || !file.getName().equals(GradleConstants.SETTINGS_FILE_NAME)) { + return; + } - PsiFile file = aClass.getContainingFile(); - if (file == null || !file.getName().equals(GradleConstants.SETTINGS_FILE_NAME)) { - return; + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations( + psiManager, + processor, + state, + place, + GradleCommonClassNames.GRADLE_API_INITIALIZATION_SETTINGS + ); } - - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GradleCommonClassNames.GRADLE_API_INITIALIZATION_SETTINGS); - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSimpleContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSimpleContributor.java index af15fb3..7c034b2 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSimpleContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSimpleContributor.java @@ -29,32 +29,34 @@ * @since 8/30/13 */ public abstract class GradleSimpleContributor implements GradleMethodContextContributor { + private final String blockName; + private final String fqName; + private final List myMixIns; - private final String blockName; - private final String fqName; - private final List myMixIns; - - protected GradleSimpleContributor(@Nonnull String blockName, @Nonnull String fqName, String... mixIns) { - this.blockName = blockName; - this.fqName = fqName; - myMixIns = List.of(mixIns); - } - - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.isEmpty() || methodCallInfo.size() < 2 || !blockName.equals(methodCallInfo.get(1))) { - return; + protected GradleSimpleContributor(@Nonnull String blockName, @Nonnull String fqName, String... mixIns) { + this.blockName = blockName; + this.fqName = fqName; + myMixIns = List.of(mixIns); } - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations(psiManager, processor, state, place, fqName); - for(final String mixin : myMixIns) { - PsiClass contributorClass = - psiManager.findClassWithCache(mixin, place.getResolveScope()); - if (contributorClass == null) continue; - GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place); + + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.isEmpty() || methodCallInfo.size() < 2 || !blockName.equals(methodCallInfo.get(1))) { + return; + } + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, fqName); + for (final String mixin : myMixIns) { + PsiClass contributorClass = psiManager.findClassWithCache(mixin, place.getResolveScope()); + if (contributorClass == null) { + continue; + } + GradleResolverUtil.processMethod(methodCallInfo.get(0), contributorClass, processor, state, place); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSourceSetsContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSourceSetsContributor.java index cda71e2..bd953c0 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSourceSetsContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSourceSetsContributor.java @@ -35,93 +35,105 @@ */ @ExtensionImpl public class GradleSourceSetsContributor implements GradleMethodContextContributor { - @Nonnull - public static GradleSourceSetsContributor getInstance() { - return EP_NAME.findExtension(GradleSourceSetsContributor.class); - } + @Nonnull + public static GradleSourceSetsContributor getInstance() { + return EP_NAME.findExtension(GradleSourceSetsContributor.class); + } - static final String SOURCE_SETS = "sourceSets"; - private static final String CONFIGURE_CLOSURE_METHOD = "configure"; - private static final int SOURCE_SET_CONTAINER_LEVEL = 1; - private static final int SOURCE_SET_LEVEL = 2; - private static final int SOURCE_DIRECTORY_LEVEL = 3; - private static final int SOURCE_DIRECTORY_CLOSURE_LEVEL = 4; + static final String SOURCE_SETS = "sourceSets"; + private static final String CONFIGURE_CLOSURE_METHOD = "configure"; + private static final int SOURCE_SET_CONTAINER_LEVEL = 1; + private static final int SOURCE_SET_LEVEL = 2; + private static final int SOURCE_DIRECTORY_LEVEL = 3; + private static final int SOURCE_DIRECTORY_CLOSURE_LEVEL = 4; - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.isEmpty()) { - return; - } - String methodCall = ContainerUtil.getLastItem(methodCallInfo); - if (methodCall == null) { - return; - } + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.isEmpty()) { + return; + } + String methodCall = ContainerUtil.getLastItem(methodCallInfo); + if (methodCall == null) { + return; + } - if (methodCallInfo.size() > 1 && "sourceSets".equals(place.getText()) && place instanceof GrReferenceExpressionImpl) { - GradleResolverUtil - .addImplicitVariable(processor, state, (GrReferenceExpressionImpl)place, GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER); - } + if (methodCallInfo.size() > 1 && "sourceSets".equals(place.getText()) && place instanceof GrReferenceExpressionImpl placeRefExpr) { + GradleResolverUtil.addImplicitVariable( + processor, + state, + placeRefExpr, + GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER + ); + } - if (methodCallInfo.size() > 1 && methodCall.equals("project")) { - methodCallInfo.remove(methodCallInfo.size() - 1); - methodCall = ContainerUtil.getLastItem(methodCallInfo); - } + if (methodCallInfo.size() > 1 && methodCall.equals("project")) { + methodCallInfo.remove(methodCallInfo.size() - 1); + methodCall = ContainerUtil.getLastItem(methodCallInfo); + } - if (methodCall == null || methodCallInfo.size() > SOURCE_DIRECTORY_CLOSURE_LEVEL || !StringUtil.startsWith(methodCall, SOURCE_SETS)) { - return; - } + if (methodCall == null || methodCallInfo.size() > SOURCE_DIRECTORY_CLOSURE_LEVEL + || !StringUtil.startsWith(methodCall, SOURCE_SETS)) { + return; + } - String configureClosureClazz = null; - String contributorClass = null; + String configureClosureClazz = null; + String contributorClass = null; - boolean isRootRelated = StringUtil.startsWith(methodCall, SOURCE_SETS + '.'); + boolean isRootRelated = StringUtil.startsWith(methodCall, SOURCE_SETS + '.'); - if (methodCallInfo.size() == SOURCE_SET_CONTAINER_LEVEL) { - configureClosureClazz = GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER; - if (place instanceof GrReferenceExpressionImpl) { - String varClazz = StringUtil.startsWith(methodCall, SOURCE_SETS + '.') - ? GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER - : GradleCommonClassNames.GRADLE_API_SOURCE_SET; - GradleResolverUtil.addImplicitVariable(processor, state, (GrReferenceExpressionImpl)place, varClazz); - } - else { - contributorClass = GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER; - } - } - else if (methodCallInfo.size() == SOURCE_SET_LEVEL) { - configureClosureClazz = GradleCommonClassNames.GRADLE_API_SOURCE_SET; - contributorClass = GradleCommonClassNames.GRADLE_API_SOURCE_SET; - } - else if (methodCallInfo.size() == SOURCE_DIRECTORY_LEVEL) { - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - PsiClass psiClass = psiManager.findClassWithCache(GradleCommonClassNames.GRADLE_API_SOURCE_SET, place.getResolveScope()); - configureClosureClazz = - GradleResolverUtil.canBeMethodOf(place.getText(), psiClass) ? null : GradleCommonClassNames.GRADLE_API_SOURCE_DIRECTORY_SET; - contributorClass = GradleCommonClassNames.GRADLE_API_SOURCE_DIRECTORY_SET; - } - else if (methodCallInfo.size() == SOURCE_DIRECTORY_CLOSURE_LEVEL) { - contributorClass = GradleCommonClassNames.GRADLE_API_SOURCE_DIRECTORY_SET; - } + if (methodCallInfo.size() == SOURCE_SET_CONTAINER_LEVEL) { + configureClosureClazz = GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER; + if (place instanceof GrReferenceExpressionImpl) { + String varClazz = StringUtil.startsWith(methodCall, SOURCE_SETS + '.') + ? GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER + : GradleCommonClassNames.GRADLE_API_SOURCE_SET; + GradleResolverUtil.addImplicitVariable(processor, state, (GrReferenceExpressionImpl)place, varClazz); + } + else { + contributorClass = GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER; + } + } + else if (methodCallInfo.size() == SOURCE_SET_LEVEL) { + configureClosureClazz = GradleCommonClassNames.GRADLE_API_SOURCE_SET; + contributorClass = GradleCommonClassNames.GRADLE_API_SOURCE_SET; + } + else if (methodCallInfo.size() == SOURCE_DIRECTORY_LEVEL) { + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + PsiClass psiClass = psiManager.findClassWithCache(GradleCommonClassNames.GRADLE_API_SOURCE_SET, place.getResolveScope()); + configureClosureClazz = GradleResolverUtil.canBeMethodOf(place.getText(), psiClass) + ? null + : GradleCommonClassNames.GRADLE_API_SOURCE_DIRECTORY_SET; + contributorClass = GradleCommonClassNames.GRADLE_API_SOURCE_DIRECTORY_SET; + } + else if (methodCallInfo.size() == SOURCE_DIRECTORY_CLOSURE_LEVEL) { + contributorClass = GradleCommonClassNames.GRADLE_API_SOURCE_DIRECTORY_SET; + } - if (configureClosureClazz != null && !isRootRelated) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GrLightMethodBuilder methodWithClosure = - GradleResolverUtil - .createMethodWithClosure(CONFIGURE_CLOSURE_METHOD, configureClosureClazz, null, place, psiManager); - if (methodWithClosure != null) { - processor.execute(methodWithClosure, state); - } - } - //else { - // GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - // GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GradleCommonClassNames.GRADLE_API_PROJECT); - //} - if (contributorClass != null) { - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations(psiManager, processor, state, place, contributorClass); + if (configureClosureClazz != null && !isRootRelated) { + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GrLightMethodBuilder methodWithClosure = GradleResolverUtil.createMethodWithClosure( + CONFIGURE_CLOSURE_METHOD, + configureClosureClazz, + null, + place, + psiManager + ); + if (methodWithClosure != null) { + processor.execute(methodWithClosure, state); + } + } + //else { + // GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + // GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GradleCommonClassNames.GRADLE_API_PROJECT); + //} + if (contributorClass != null) { + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, contributorClass); + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleTaskContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleTaskContributor.java index b85d07a..0c23c50 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleTaskContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleTaskContributor.java @@ -44,112 +44,124 @@ */ @ExtensionImpl public class GradleTaskContributor implements GradleMethodContextContributor { + @Override + public void process( + @Nonnull List methodCallInfo, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + if (methodCallInfo.isEmpty()) { + return; + } - @Override - public void process(@Nonnull List methodCallInfo, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - if (methodCallInfo.isEmpty()) return; - - if (methodCallInfo.size() == 1) { - if(GradleResolverUtil.isLShiftElement(place.getParent())) { - GradleResolverUtil.addImplicitVariable(processor, state, place, GradleCommonClassNames.GRADLE_API_TASK); - } - } - else if (methodCallInfo.size() == 2) { - if (place.getParent().getParent() instanceof GrCommandArgumentList) { - // Assuming that the method call is addition of new task into the project. - processTaskAddition(methodCallInfo.get(0), GradleCommonClassNames.GRADLE_API_TASK_CONTAINER, processor, state, place); - } - else { - processTaskTypeParameter(methodCallInfo.get(0), processor, state, place); - } + if (methodCallInfo.size() == 1) { + if (GradleResolverUtil.isLShiftElement(place.getParent())) { + GradleResolverUtil.addImplicitVariable(processor, state, place, GradleCommonClassNames.GRADLE_API_TASK); + } + } + else if (methodCallInfo.size() == 2) { + if (place.getParent().getParent() instanceof GrCommandArgumentList) { + // Assuming that the method call is addition of new task into the project. + processTaskAddition(methodCallInfo.get(0), GradleCommonClassNames.GRADLE_API_TASK_CONTAINER, processor, state, place); + } + else { + processTaskTypeParameter(methodCallInfo.get(0), processor, state, place); + } - GradleImplicitContributor.processImplicitDeclarations(processor, state, place); - } - else if (methodCallInfo.size() >= 3) { - processTaskTypeParameter(methodCallInfo.get(0), processor, state, place); + GradleImplicitContributor.processImplicitDeclarations(processor, state, place); + } + else if (methodCallInfo.size() >= 3) { + processTaskTypeParameter(methodCallInfo.get(0), processor, state, place); - GradleImplicitContributor.processImplicitDeclarations(processor, state, place); + GradleImplicitContributor.processImplicitDeclarations(processor, state, place); - if (place.getText().equals(GradleSourceSetsContributor.SOURCE_SETS) && - StringUtil.startsWith(methodCallInfo.get(0), GradleSourceSetsContributor.SOURCE_SETS + '.')) { - GradleResolverUtil.addImplicitVariable(processor, state, place, GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER); - } + if (place.getText().equals(GradleSourceSetsContributor.SOURCE_SETS) && + StringUtil.startsWith(methodCallInfo.get(0), GradleSourceSetsContributor.SOURCE_SETS + '.')) { + GradleResolverUtil.addImplicitVariable(processor, state, place, GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER); + } + } } - } - private static void processTaskTypeParameter(@Nonnull String methodCall, @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - final int taskTypeParameterLevel = 3; - PsiElement psiElement = GradleResolverUtil.findParent(place, taskTypeParameterLevel); + private static void processTaskTypeParameter( + @Nonnull String methodCall, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + final int taskTypeParameterLevel = 3; + PsiElement psiElement = GradleResolverUtil.findParent(place, taskTypeParameterLevel); - if (psiElement instanceof GrMethodCallExpression) { - GrMethodCallExpression callExpression = (GrMethodCallExpression)psiElement; - GrArgumentList argumentList = callExpression.getArgumentList(); - if (argumentList != null && argumentList.getAllArguments().length > 0) { - for (GroovyPsiElement argument : argumentList.getAllArguments()) { - if (argument instanceof GrNamedArgument) { - GrNamedArgument namedArgument = (GrNamedArgument)argument; - GrExpression grExpression = namedArgument.getExpression(); - PsiType psiType = null; - if (grExpression != null) { - psiType = GradleResolverUtil.getTypeOf(grExpression); + if (psiElement instanceof GrMethodCallExpression callExpression) { + GrArgumentList argumentList = callExpression.getArgumentList(); + if (argumentList != null && argumentList.getAllArguments().length > 0) { + for (GroovyPsiElement argument : argumentList.getAllArguments()) { + if (argument instanceof GrNamedArgument namedArgument) { + GrExpression grExpression = namedArgument.getExpression(); + PsiType psiType = null; + if (grExpression != null) { + psiType = GradleResolverUtil.getTypeOf(grExpression); + } + if (psiType instanceof PsiImmediateClassType immediateClassType) { + for (PsiType type : immediateClassType.getParameters()) { + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + GradleResolverUtil.processDeclarations( + methodCall, + psiManager, + processor, + state, + place, + type.getCanonicalText() + ); + } + } + } + } } - if (psiType instanceof PsiImmediateClassType) { - PsiImmediateClassType immediateClassType = (PsiImmediateClassType)psiType; - for (PsiType type : immediateClassType.getParameters()) { + else { GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations(methodCall, psiManager, processor, state, place, type.getCanonicalText()); - } + GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GradleCommonClassNames.GRADLE_API_TASK); } - } } - } - else { - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - GradleResolverUtil.processDeclarations(psiManager, processor, state, place, GradleCommonClassNames.GRADLE_API_TASK); - } } - } - private static void processTaskAddition(@Nonnull String name, - @Nonnull String handlerClass, - @Nonnull PsiScopeProcessor processor, - @Nonnull ResolveState state, - @Nonnull PsiElement place) { - GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); - PsiClass psiClass = psiManager.findClassWithCache(handlerClass, place.getResolveScope()); - if (psiClass == null) { - return; - } + private static void processTaskAddition( + @Nonnull String name, + @Nonnull String handlerClass, + @Nonnull PsiScopeProcessor processor, + @Nonnull ResolveState state, + @Nonnull PsiElement place + ) { + GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject()); + PsiClass psiClass = psiManager.findClassWithCache(handlerClass, place.getResolveScope()); + if (psiClass == null) { + return; + } - GrLightMethodBuilder builder = new GrLightMethodBuilder(place.getManager(), name); - PsiElementFactory factory = JavaPsiFacade.getElementFactory(place.getManager().getProject()); - PsiType type = new PsiArrayType(factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_OBJECT, place.getResolveScope())); - builder.addParameter(new GrLightParameter("taskInfo", type, builder)); - PsiClassType retType = factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_STRING, place.getResolveScope()); - builder.setReturnType(retType); - processor.execute(builder, state); + GrLightMethodBuilder builder = new GrLightMethodBuilder(place.getManager(), name); + PsiElementFactory factory = JavaPsiFacade.getElementFactory(place.getManager().getProject()); + PsiType type = new PsiArrayType(factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_OBJECT, place.getResolveScope())); + builder.addParameter(new GrLightParameter("taskInfo", type, builder)); + PsiClassType retType = factory.createTypeByFQClassName(JavaClassNames.JAVA_LANG_STRING, place.getResolveScope()); + builder.setReturnType(retType); + processor.execute(builder, state); - GrMethodCall call = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); - if (call == null) { - return; - } - GrArgumentList args = call.getArgumentList(); - if (args == null) { - return; - } + GrMethodCall call = PsiTreeUtil.getParentOfType(place, GrMethodCall.class); + if (call == null) { + return; + } + GrArgumentList args = call.getArgumentList(); + if (args == null) { + return; + } - int argsCount = GradleResolverUtil.getGrMethodArumentsCount(args); - argsCount++; // Configuration name is delivered as an argument. + int argsCount = GradleResolverUtil.getGrMethodArumentsCount(args); + argsCount++; // Configuration name is delivered as an argument. - for (PsiMethod method : psiClass.findMethodsByName("create", false)) { - if (method.getParameterList().getParametersCount() == argsCount) { - builder.setNavigationElement(method); - } + for (PsiMethod method : psiClass.findMethodsByName("create", false)) { + if (method.getParameterList().getParametersCount() == argsCount) { + builder.setNavigationElement(method); + } + } } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleUnresolvedReferenceFilter.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleUnresolvedReferenceFilter.java index 58a6116..94c1b6c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleUnresolvedReferenceFilter.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleUnresolvedReferenceFilter.java @@ -29,15 +29,15 @@ */ @ExtensionImpl public class GradleUnresolvedReferenceFilter extends GroovyUnresolvedHighlightFilter { + private final static Set IGNORE_SET = Set.of( + GradleCommonClassNames.GRADLE_API_TASK, + GradleCommonClassNames.GRADLE_API_SOURCE_SET, + GradleCommonClassNames.GRADLE_API_CONFIGURATION + ); - private final static Set IGNORE_SET = Set.of( - GradleCommonClassNames.GRADLE_API_TASK, - GradleCommonClassNames.GRADLE_API_SOURCE_SET, - GradleCommonClassNames.GRADLE_API_CONFIGURATION); - - @Override - public boolean isReject(@Nonnull GrReferenceExpression expression) { - final PsiType psiType = GradleResolverUtil.getTypeOf(expression); - return psiType != null && IGNORE_SET.contains(psiType.getCanonicalText()); - } + @Override + public boolean isReject(@Nonnull GrReferenceExpression expression) { + final PsiType psiType = GradleResolverUtil.getTypeOf(expression); + return psiType != null && IGNORE_SET.contains(psiType.getCanonicalText()); + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java index 0df28bb..9fa8cda 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java @@ -34,58 +34,67 @@ */ @ExtensionImpl public class NamedDomainObjectCollectionTypeEnhancer extends GrReferenceTypeEnhancer { - @Override - public PsiType getReferenceType(GrReferenceExpression ref, @Nullable PsiElement resolved) { - if (resolved != null) return null; + @Override + public PsiType getReferenceType(GrReferenceExpression ref, @Nullable PsiElement resolved) { + if (resolved != null) { + return null; + } - GrExpression qualifierExpression = ref.getQualifierExpression(); - if (qualifierExpression == null) return null; + GrExpression qualifierExpression = ref.getQualifierExpression(); + if (qualifierExpression == null) { + return null; + } - PsiType namedDomainCollectionType = GradleResolverUtil.getTypeOf(qualifierExpression); + PsiType namedDomainCollectionType = GradleResolverUtil.getTypeOf(qualifierExpression); - if (!GroovyPsiManager.isInheritorCached(namedDomainCollectionType, GradleCommonClassNames.GRADLE_API_NAMED_DOMAIN_OBJECT_COLLECTION)) { - return null; - } + if (!GroovyPsiManager.isInheritorCached( + namedDomainCollectionType, + GradleCommonClassNames.GRADLE_API_NAMED_DOMAIN_OBJECT_COLLECTION + )) { + return null; + } - PsiElement qResolved; + PsiElement qResolved; - if (qualifierExpression instanceof GrReferenceExpression) { - qResolved = ((GrReferenceExpression)qualifierExpression).resolve(); - } - else if (qualifierExpression instanceof GrMethodCall) { - qResolved = ((GrMethodCall)qualifierExpression).resolveMethod(); - } - else { - return null; - } + if (qualifierExpression instanceof GrReferenceExpression referenceExpression) { + qResolved = referenceExpression.resolve(); + } + else if (qualifierExpression instanceof GrMethodCall methodCall) { + qResolved = methodCall.resolveMethod(); + } + else { + return null; + } - String key = ref.getReferenceName(); - if (key == null) return null; + String key = ref.getReferenceName(); + if (key == null) { + return null; + } - for (GroovyMapContentProvider provider : GroovyMapContentProvider.EP_NAME.getExtensions()) { - PsiType type = provider.getValueType(qualifierExpression, qResolved, key); - if (type != null) { - return type; - } - } + for (GroovyMapContentProvider provider : GroovyMapContentProvider.EP_NAME.getExtensions()) { + PsiType type = provider.getValueType(qualifierExpression, qResolved, key); + if (type != null) { + return type; + } + } - if (namedDomainCollectionType instanceof PsiClassReferenceType) { - final PsiClassReferenceType referenceType = (PsiClassReferenceType)namedDomainCollectionType; - final String fqName = referenceType.getCanonicalText(); - if (GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER.equals(fqName)) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); - return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_SOURCE_SET, ref.getResolveScope()); - } - else if (GradleCommonClassNames.GRADLE_API_CONFIGURATION_CONTAINER.equals(fqName)) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); - return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_CONFIGURATION, ref.getResolveScope()); - } - else if (GradleCommonClassNames.GRADLE_API_TASK_CONTAINER.equals(fqName)) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); - return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_TASK, ref.getResolveScope()); - } - } + if (namedDomainCollectionType instanceof PsiClassReferenceType) { + final PsiClassReferenceType referenceType = (PsiClassReferenceType)namedDomainCollectionType; + final String fqName = referenceType.getCanonicalText(); + if (GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER.equals(fqName)) { + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); + return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_SOURCE_SET, ref.getResolveScope()); + } + else if (GradleCommonClassNames.GRADLE_API_CONFIGURATION_CONTAINER.equals(fqName)) { + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); + return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_CONFIGURATION, ref.getResolveScope()); + } + else if (GradleCommonClassNames.GRADLE_API_TASK_CONTAINER.equals(fqName)) { + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); + return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_TASK, ref.getResolveScope()); + } + } - return null; - } + return null; + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java index 22ad9c3..cebff33 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java @@ -39,30 +39,39 @@ * @since 9/25/13 */ public class GradleDslAnnotator implements Annotator { - @Override - public void annotate(@Nonnull PsiElement element, @Nonnull AnnotationHolder holder) { - if (element instanceof GrReferenceExpression) { - GrReferenceExpression referenceExpression = (GrReferenceExpression)element; - final GrExpression qualifier = ResolveUtil.getSelfOrWithQualifier(referenceExpression); - if (qualifier == null) return; - if (qualifier instanceof GrReferenceExpression && ((GrReferenceExpression)qualifier).resolve() instanceof PsiClass) return; + @Override + public void annotate(@Nonnull PsiElement element, @Nonnull AnnotationHolder holder) { + if (element instanceof GrReferenceExpression referenceExpression) { + final GrExpression qualifier = ResolveUtil.getSelfOrWithQualifier(referenceExpression); + if (qualifier == null) { + return; + } + if (qualifier instanceof GrReferenceExpression qualifierRefExpr && qualifierRefExpr.resolve() instanceof PsiClass) { + return; + } - PsiType psiType = GradleResolverUtil.getTypeOf(qualifier); - if (psiType == null) return; - if (InheritanceUtil.isInheritor(psiType, GradleCommonClassNames.GRADLE_API_NAMED_DOMAIN_OBJECT_COLLECTION)) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(element.getProject()); - PsiClass defaultGroovyMethodsClass = - psiManager.findClassWithCache(GroovyCommonClassNames.DEFAULT_GROOVY_METHODS, element.getResolveScope()); - if (canBeMethodOf(referenceExpression.getReferenceName(), defaultGroovyMethodsClass)) return; + PsiType psiType = GradleResolverUtil.getTypeOf(qualifier); + if (psiType == null) { + return; + } + if (InheritanceUtil.isInheritor(psiType, GradleCommonClassNames.GRADLE_API_NAMED_DOMAIN_OBJECT_COLLECTION)) { + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(element.getProject()); + PsiClass defaultGroovyMethodsClass = + psiManager.findClassWithCache(GroovyCommonClassNames.DEFAULT_GROOVY_METHODS, element.getResolveScope()); + if (canBeMethodOf(referenceExpression.getReferenceName(), defaultGroovyMethodsClass)) { + return; + } - PsiClass containerClass = psiManager.findClassWithCache(psiType.getCanonicalText(), element.getResolveScope()); - if (canBeMethodOf(referenceExpression.getReferenceName(), containerClass)) return; + PsiClass containerClass = psiManager.findClassWithCache(psiType.getCanonicalText(), element.getResolveScope()); + if (canBeMethodOf(referenceExpression.getReferenceName(), containerClass)) { + return; + } - PsiElement nameElement = referenceExpression.getReferenceNameElement(); - if (nameElement != null) { - holder.createInfoAnnotation(nameElement, null).setTextAttributes(GroovySyntaxHighlighter.MAP_KEY); + PsiElement nameElement = referenceExpression.getReferenceNameElement(); + if (nameElement != null) { + holder.createInfoAnnotation(nameElement, null).setTextAttributes(GroovySyntaxHighlighter.MAP_KEY); + } + } } - } } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotatorFactory.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotatorFactory.java index a2b12cd..1d13f00 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotatorFactory.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotatorFactory.java @@ -15,15 +15,15 @@ */ @ExtensionImpl public class GradleDslAnnotatorFactory implements AnnotatorFactory { - @Nullable - @Override - public Annotator createAnnotator() { - return new GradleDslAnnotator(); - } + @Nullable + @Override + public Annotator createAnnotator() { + return new GradleDslAnnotator(); + } - @Nonnull - @Override - public Language getLanguage() { - return GroovyLanguage.INSTANCE; - } + @Nonnull + @Override + public Language getLanguage() { + return GroovyLanguage.INSTANCE; + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigLocator.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigLocator.java index a649b1c..e29425d 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigLocator.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigLocator.java @@ -26,52 +26,51 @@ */ @ExtensionImpl public class GradleConfigLocator implements ExternalSystemConfigLocator { - - @Nonnull - @Override - public ProjectSystemId getTargetExternalSystemId() { - return GradleConstants.SYSTEM_ID; - } - - @Nullable - @Override - public VirtualFile adjust(@Nonnull VirtualFile configPath) { - if (!configPath.isDirectory()) { - return configPath; + @Nonnull + @Override + public ProjectSystemId getTargetExternalSystemId() { + return GradleConstants.SYSTEM_ID; } - VirtualFile result = configPath.findChild(GradleConstants.DEFAULT_SCRIPT_NAME); - if (result != null) { - return result; - } + @Nullable + @Override + public VirtualFile adjust(@Nonnull VirtualFile configPath) { + if (!configPath.isDirectory()) { + return configPath; + } - for (VirtualFile child : configPath.getChildren()) { - String name = child.getName(); - if (!name.endsWith(GradleConstants.EXTENSION)) { - continue; - } - if (!GradleConstants.SETTINGS_FILE_NAME.equals(name) && !child.isDirectory()) { - return child; - } + VirtualFile result = configPath.findChild(GradleConstants.DEFAULT_SCRIPT_NAME); + if (result != null) { + return result; + } + + for (VirtualFile child : configPath.getChildren()) { + String name = child.getName(); + if (!name.endsWith(GradleConstants.EXTENSION)) { + continue; + } + if (!GradleConstants.SETTINGS_FILE_NAME.equals(name) && !child.isDirectory()) { + return child; + } + } + return null; } - return null; - } - @Nonnull - @Override - public List findAll(@Nonnull ExternalProjectSettings externalProjectSettings) { - List list = new ArrayList<>(); - for (String path : externalProjectSettings.getModules()) { - VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(path)); - if (vFile != null) { - for (VirtualFile child : vFile.getChildren()) { - String name = child.getName(); - if (!child.isDirectory() && name.endsWith(GradleConstants.EXTENSION)) { - list.add(child); - } + @Nonnull + @Override + public List findAll(@Nonnull ExternalProjectSettings externalProjectSettings) { + List list = new ArrayList<>(); + for (String path : externalProjectSettings.getModules()) { + VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(path)); + if (vFile != null) { + for (VirtualFile child : vFile.getChildren()) { + String name = child.getName(); + if (!child.isDirectory() && name.endsWith(GradleConstants.EXTENSION)) { + list.add(child); + } + } + } } - } + return list; } - return list; - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java index 845ce96..bf01b0c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java @@ -36,38 +36,38 @@ */ @ExtensionImpl public class GradleConfigurable extends AbstractExternalSystemConfigurable implements ProjectConfigurable { - @Inject - public GradleConfigurable(@Nonnull Project project) { - super(project, GradleConstants.SYSTEM_ID); - } + @Inject + public GradleConfigurable(@Nonnull Project project) { + super(project, GradleConstants.SYSTEM_ID); + } - @Nonnull - @Override - protected ExternalSystemSettingsControl createProjectSettingsControl(@Nonnull GradleProjectSettings settings) { - return new GradleProjectSettingsControl(settings); - } + @Nonnull + @Override + protected ExternalSystemSettingsControl createProjectSettingsControl(@Nonnull GradleProjectSettings settings) { + return new GradleProjectSettingsControl(settings); + } - @Nullable - @Override - protected ExternalSystemSettingsControl createSystemSettingsControl(@Nonnull GradleSettings settings) { - return new GradleSystemSettingsControl(settings); - } + @Nullable + @Override + protected ExternalSystemSettingsControl createSystemSettingsControl(@Nonnull GradleSettings settings) { + return new GradleSystemSettingsControl(settings); + } - @Nonnull - @Override - protected GradleProjectSettings newProjectSettings() { - return new GradleProjectSettings(); - } + @Nonnull + @Override + protected GradleProjectSettings newProjectSettings() { + return new GradleProjectSettings(); + } - @Nonnull - @Override - public String getId() { - return "execution.gradle"; - } + @Nonnull + @Override + public String getId() { + return "execution.gradle"; + } - @Nullable - @Override - public String getParentId() { - return StandardConfigurableIds.EXECUTION_GROUP; - } + @Nullable + @Override + public String getParentId() { + return StandardConfigurableIds.EXECUTION_GROUP; + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java index 8e52e57..324410b 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java @@ -51,10 +51,7 @@ import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; -import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; import java.io.File; import java.util.Objects; import java.util.concurrent.TimeUnit; @@ -63,441 +60,381 @@ * @author Denis Zhdanov * @since 4/24/13 1:45 PM */ -public class GradleProjectSettingsControl extends AbstractExternalProjectSettingsControl -{ - - private static final long BALLOON_DELAY_MILLIS = TimeUnit.SECONDS.toMillis(1); - - @Nonnull - private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); - - @Nonnull - private LocationSettingType myGradleHomeSettingType = LocationSettingType.UNKNOWN; - - @Nonnull - private final GradleInstallationManager myInstallationManager; - - @SuppressWarnings("FieldCanBeLocal") // Used implicitly by reflection at disposeUIResources() and showUi() - private JLabel myGradleHomeLabel; - private TextFieldWithBrowseButton myGradleHomePathField; - private JBRadioButton myUseWrapperButton; - private JBRadioButton myUseWrapperWithVerificationButton; - private JBLabel myUseWrapperVerificationLabel; - private JBRadioButton myUseLocalDistributionButton; - private JBRadioButton myUseBundledDistributionButton; - - private boolean myShowBalloonIfNecessary; - - private BundleBox myBundleBox; - - public GradleProjectSettingsControl(@Nonnull GradleProjectSettings initialSettings) - { - super(initialSettings); - myInstallationManager = ServiceManager.getService(GradleInstallationManager.class); - } - - @Override - protected void fillExtraControls(@Nonnull Disposable uiDisposable, @Nonnull PaintAwarePanel content, int indentLevel) - { - content.setPaintCallback(graphics -> showBalloonIfNecessary()); - - content.addPropertyChangeListener(new PropertyChangeListener() - { - @Override - public void propertyChange(PropertyChangeEvent evt) - { - if(!"ancestor".equals(evt.getPropertyName())) - { - return; - } - - // Configure the balloon to show on initial configurable drawing. - myShowBalloonIfNecessary = evt.getNewValue() != null && evt.getOldValue() == null; - - if(evt.getNewValue() == null && evt.getOldValue() != null) - { - // Cancel delayed balloons when the configurable is hidden. - myAlarm.cancelAllRequests(); - } - } - }); - - myGradleHomeLabel = new JBLabel(GradleBundle.message("gradle.settings.text.home.path")); - initGradleHome(); - - initControls(); - content.add(myUseWrapperButton, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); - content.add(myUseWrapperWithVerificationButton, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); - content.add(myUseWrapperVerificationLabel, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); - //content.add(Box.createGlue(), ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); - // Hide bundled distribution option for a while - // content.add(myUseBundledDistributionButton, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); - content.add(myUseLocalDistributionButton, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); - - content.add(myGradleHomeLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); - content.add(myGradleHomePathField, ExternalSystemUiUtil.getFillLineConstraints(0)); - - BundleBoxBuilder builder = BundleBoxBuilder.create(uiDisposable); - builder.withNoneItem("Auto Select", PlatformIconGroup.actionsFind()); - builder.withSdkTypeFilterByClass(JavaSdkType.class); - - myBundleBox = builder.build(); - - content.add(TargetAWT.to(LabeledBuilder.sided(LocalizeValue.localizeTODO("JRE"), myBundleBox)), ExternalSystemUiUtil.getFillLineConstraints(0)); - } - - private void initControls() - { - ActionListener listener = new ActionListener() - { - @Override - public void actionPerformed(ActionEvent e) - { - boolean localDistributionEnabled = myUseLocalDistributionButton.isSelected(); - myGradleHomePathField.setEnabled(localDistributionEnabled); - if(localDistributionEnabled) - { - if(myGradleHomePathField.getText().isEmpty()) - { - deduceGradleHomeIfPossible(); - } - else - { - if(myInstallationManager.isGradleSdkHome(myGradleHomePathField.getText())) - { - myGradleHomeSettingType = LocationSettingType.EXPLICIT_CORRECT; - } - else - { - myGradleHomeSettingType = LocationSettingType.EXPLICIT_INCORRECT; - myShowBalloonIfNecessary = true; - } - } - showBalloonIfNecessary(); - } - else - { - myAlarm.cancelAllRequests(); - } - } - }; - - myUseWrapperButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.default_wrapper.configured")); - myUseWrapperButton.addActionListener(listener); - myUseWrapperWithVerificationButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.customizable_wrapper")); - myUseWrapperWithVerificationButton.addActionListener(listener); - myUseWrapperVerificationLabel = new JBLabel(GradleBundle.message("gradle.settings.text.wrapper.customization.compatibility")); - myUseWrapperVerificationLabel.setFont(UIUtil.getLabelFont(UIUtil.FontSize.MINI)); - myUseWrapperVerificationLabel.setIcon((Image) AllIcons.General.BalloonInformation); - - myUseLocalDistributionButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.local.distribution")); - myUseLocalDistributionButton.addActionListener(listener); - - myUseBundledDistributionButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.bundled.distribution", GradleVersion.current().getVersion())); - myUseBundledDistributionButton.addActionListener(listener); - myUseBundledDistributionButton.setEnabled(false); - - ButtonGroup buttonGroup = new ButtonGroup(); - buttonGroup.add(myUseWrapperButton); - buttonGroup.add(myUseWrapperWithVerificationButton); - buttonGroup.add(myUseBundledDistributionButton); - buttonGroup.add(myUseLocalDistributionButton); - } - - private void initGradleHome() - { - myGradleHomePathField = new TextFieldWithBrowseButton(); - - FileChooserDescriptor fileChooserDescriptor = GradleUtil.getGradleHomeFileChooserDescriptor(); - - myGradleHomePathField.addBrowseFolderListener("", GradleBundle.message("gradle.settings.text.home.path"), null, fileChooserDescriptor, TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, false); - myGradleHomePathField.getTextField().getDocument().addDocumentListener(new DocumentListener() - { - @Override - public void insertUpdate(DocumentEvent e) - { - myGradleHomePathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); - } - - @Override - public void removeUpdate(DocumentEvent e) - { - myGradleHomePathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); - } - - @Override - public void changedUpdate(DocumentEvent e) - { - } - }); - } - - @Override - public boolean validate(@Nonnull GradleProjectSettings settings) throws ConfigurationException - { - String gradleHomePath = FileUtil.toCanonicalPath(myGradleHomePathField.getText()); - if(myUseLocalDistributionButton.isSelected()) - { - if(StringUtil.isEmpty(gradleHomePath)) - { - myGradleHomeSettingType = LocationSettingType.UNKNOWN; - throw new ConfigurationException(GradleBundle.message("gradle.home.setting.type.explicit.empty", gradleHomePath)); - } - else if(!myInstallationManager.isGradleSdkHome(new File(gradleHomePath))) - { - myGradleHomeSettingType = LocationSettingType.EXPLICIT_INCORRECT; - new DelayedBalloonInfo(NotificationType.ERROR, myGradleHomeSettingType, 0).run(); - throw new ConfigurationException(GradleBundle.message("gradle.home.setting.type.explicit.incorrect", gradleHomePath)); - } - } - return true; - } - - @Override - protected void applyExtraSettings(@Nonnull GradleProjectSettings settings) - { - String gradleHomePath = FileUtil.toCanonicalPath(myGradleHomePathField.getText()); - if(StringUtil.isEmpty(gradleHomePath)) - { - settings.setGradleHome(null); - } - else - { - settings.setGradleHome(gradleHomePath); - GradleUtil.storeLastUsedGradleHome(gradleHomePath); - } - - if(myUseLocalDistributionButton.isSelected()) - { - settings.setDistributionType(DistributionType.LOCAL); - } - else if(myUseWrapperButton.isSelected()) - { - settings.setDistributionType(DistributionType.DEFAULT_WRAPPED); - } - else if(myUseWrapperWithVerificationButton.isSelected() || myUseBundledDistributionButton.isSelected()) - { - settings.setDistributionType(DistributionType.WRAPPED); - } - - settings.setJreName(myBundleBox.getSelectedBundleName()); - } - - @Override - protected void updateInitialExtraSettings() - { - String gradleHomePath = FileUtil.toCanonicalPath(myGradleHomePathField.getText()); - getInitialSettings().setGradleHome(StringUtil.isEmpty(gradleHomePath) ? null : gradleHomePath); - if(myUseLocalDistributionButton.isSelected()) - { - getInitialSettings().setDistributionType(DistributionType.LOCAL); - } - else if(myUseWrapperButton.isSelected()) - { - getInitialSettings().setDistributionType(DistributionType.DEFAULT_WRAPPED); - } - else if(myUseWrapperWithVerificationButton.isSelected() || myUseBundledDistributionButton.isSelected()) - { - getInitialSettings().setDistributionType(DistributionType.WRAPPED); - } - } - - @Override - protected boolean isExtraSettingModified() - { - DistributionType distributionType = getInitialSettings().getDistributionType(); - if(myUseBundledDistributionButton.isSelected() && distributionType != DistributionType.BUNDLED) - { - return true; - } - - if(myUseWrapperButton.isSelected() && distributionType != DistributionType.DEFAULT_WRAPPED) - { - return true; - } - - if(myUseWrapperWithVerificationButton.isSelected() && distributionType != DistributionType.WRAPPED) - { - return true; - } - - if(myUseLocalDistributionButton.isSelected() && distributionType != DistributionType.LOCAL) - { - return true; - } - - if(!Objects.equals(myBundleBox.getSelectedBundleName(), getInitialSettings().getJreName())) - { - return true; - } - - String gradleHome = FileUtil.toCanonicalPath(myGradleHomePathField.getText()); - if(StringUtil.isEmpty(gradleHome)) - { - return !StringUtil.isEmpty(getInitialSettings().getGradleHome()); - } - else - { - return !gradleHome.equals(getInitialSettings().getGradleHome()); - } - } - - @Override - @RequiredUIAccess - protected void resetExtraSettings(boolean isDefaultModuleCreation) - { - String gradleHome = getInitialSettings().getGradleHome(); - myGradleHomePathField.setText(gradleHome == null ? "" : gradleHome); - myGradleHomePathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); - - myBundleBox.setSelectedBundle(getInitialSettings().getJreName()); - - updateWrapperControls(getInitialSettings().getExternalProjectPath(), isDefaultModuleCreation); - if(!myUseLocalDistributionButton.isSelected()) - { - myGradleHomePathField.setEnabled(false); - return; - } - - if(StringUtil.isEmpty(gradleHome)) - { - myGradleHomeSettingType = LocationSettingType.UNKNOWN; - deduceGradleHomeIfPossible(); - } - else - { - myGradleHomeSettingType = myInstallationManager.isGradleSdkHome(new File(gradleHome)) ? LocationSettingType.EXPLICIT_CORRECT : LocationSettingType.EXPLICIT_INCORRECT; - myAlarm.cancelAllRequests(); - if(myGradleHomeSettingType == LocationSettingType.EXPLICIT_INCORRECT && getInitialSettings().getDistributionType() == DistributionType.LOCAL) - { - new DelayedBalloonInfo(NotificationType.ERROR, myGradleHomeSettingType, 0).run(); - } - } - } - - public void updateWrapperControls(@Nullable String linkedProjectPath, boolean isDefaultModuleCreation) - { - if(StringUtil.isEmpty(linkedProjectPath) && !isDefaultModuleCreation) - { - myUseLocalDistributionButton.setSelected(true); - myGradleHomePathField.setEnabled(true); - return; - } - - final boolean isGradleDefaultWrapperFilesExist = GradleUtil.isGradleDefaultWrapperFilesExist(linkedProjectPath); - if(isGradleDefaultWrapperFilesExist || isDefaultModuleCreation) - { - myUseWrapperButton.setEnabled(true); - myUseWrapperButton.setSelected(true); - myGradleHomePathField.setEnabled(false); - myUseWrapperButton.setText(GradleBundle.message("gradle.settings.text.use.default_wrapper.configured")); - } - else - { - myUseWrapperButton.setEnabled(false); - myUseLocalDistributionButton.setSelected(true); - myGradleHomePathField.setEnabled(true); - myUseWrapperButton.setText(GradleBundle.message("gradle.settings.text.use.default_wrapper.not_configured")); - } - - if(getInitialSettings().getDistributionType() == null) - { - return; - } - - switch(getInitialSettings().getDistributionType()) - { - case LOCAL: - myGradleHomePathField.setEnabled(true); - myUseLocalDistributionButton.setSelected(true); - break; - case DEFAULT_WRAPPED: - myGradleHomePathField.setEnabled(false); - myUseWrapperButton.setSelected(true); - myUseWrapperButton.setEnabled(true); - break; - case WRAPPED: - myGradleHomePathField.setEnabled(false); - myUseWrapperWithVerificationButton.setSelected(true); - break; - case BUNDLED: - myGradleHomePathField.setEnabled(false); - myUseBundledDistributionButton.setSelected(true); - break; - } - } - - /** - * Updates GUI of the gradle configurable in order to show deduced path to gradle (if possible). - */ - private void deduceGradleHomeIfPossible() - { - File gradleHome = myInstallationManager.getAutodetectedGradleHome(); - if(gradleHome == null) - { - new DelayedBalloonInfo(NotificationType.WARNING, LocationSettingType.UNKNOWN, BALLOON_DELAY_MILLIS).run(); - return; - } - myGradleHomeSettingType = LocationSettingType.DEDUCED; - new DelayedBalloonInfo(NotificationType.INFO, LocationSettingType.DEDUCED, BALLOON_DELAY_MILLIS).run(); - myGradleHomePathField.setText(gradleHome.getPath()); - myGradleHomePathField.getTextField().setForeground(LocationSettingType.DEDUCED.getColor()); - } - - void showBalloonIfNecessary() - { - if(!myShowBalloonIfNecessary || !myGradleHomePathField.isEnabled()) - { - return; - } - myShowBalloonIfNecessary = false; - NotificationType messageType = null; - switch(myGradleHomeSettingType) - { - case DEDUCED: - messageType = NotificationType.INFO; - break; - case EXPLICIT_INCORRECT: - case UNKNOWN: - messageType = NotificationType.ERROR; - break; - default: - } - if(messageType != null) - { - new DelayedBalloonInfo(messageType, myGradleHomeSettingType, BALLOON_DELAY_MILLIS).run(); - } - } - - private class DelayedBalloonInfo implements Runnable - { - private final NotificationType myMessageType; - private final String myText; - private final long myTriggerTime; - - DelayedBalloonInfo(@Nonnull NotificationType messageType, @Nonnull LocationSettingType settingType, long delayMillis) - { - myMessageType = messageType; - myText = settingType.getDescription(GradleConstants.SYSTEM_ID); - myTriggerTime = System.currentTimeMillis() + delayMillis; - } - - @Override - public void run() - { - long diff = myTriggerTime - System.currentTimeMillis(); - if(diff > 0) - { - myAlarm.cancelAllRequests(); - myAlarm.addRequest(this, diff); - return; - } - if(myGradleHomePathField == null || !myGradleHomePathField.isShowing()) - { - // Don't schedule the balloon if the configurable is hidden. - return; - } - ExternalSystemUiUtil.showBalloon(myGradleHomePathField, myMessageType, myText); - } - } +public class GradleProjectSettingsControl extends AbstractExternalProjectSettingsControl { + private static final long BALLOON_DELAY_MILLIS = TimeUnit.SECONDS.toMillis(1); + + @Nonnull + private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); + + @Nonnull + private LocationSettingType myGradleHomeSettingType = LocationSettingType.UNKNOWN; + + @Nonnull + private final GradleInstallationManager myInstallationManager; + + @SuppressWarnings("FieldCanBeLocal") // Used implicitly by reflection at disposeUIResources() and showUi() + private JLabel myGradleHomeLabel; + private TextFieldWithBrowseButton myGradleHomePathField; + private JBRadioButton myUseWrapperButton; + private JBRadioButton myUseWrapperWithVerificationButton; + private JBLabel myUseWrapperVerificationLabel; + private JBRadioButton myUseLocalDistributionButton; + private JBRadioButton myUseBundledDistributionButton; + + private boolean myShowBalloonIfNecessary; + + private BundleBox myBundleBox; + + public GradleProjectSettingsControl(@Nonnull GradleProjectSettings initialSettings) { + super(initialSettings); + myInstallationManager = ServiceManager.getService(GradleInstallationManager.class); + } + + @Override + protected void fillExtraControls(@Nonnull Disposable uiDisposable, @Nonnull PaintAwarePanel content, int indentLevel) { + content.setPaintCallback(graphics -> showBalloonIfNecessary()); + + content.addPropertyChangeListener(evt -> { + if (!"ancestor".equals(evt.getPropertyName())) { + return; + } + + // Configure the balloon to show on initial configurable drawing. + myShowBalloonIfNecessary = evt.getNewValue() != null && evt.getOldValue() == null; + + if (evt.getNewValue() == null && evt.getOldValue() != null) { + // Cancel delayed balloons when the configurable is hidden. + myAlarm.cancelAllRequests(); + } + }); + + myGradleHomeLabel = new JBLabel(GradleBundle.message("gradle.settings.text.home.path")); + initGradleHome(); + + initControls(); + content.add(myUseWrapperButton, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); + content.add(myUseWrapperWithVerificationButton, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); + content.add(myUseWrapperVerificationLabel, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); + //content.add(Box.createGlue(), ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); + // Hide bundled distribution option for a while + // content.add(myUseBundledDistributionButton, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); + content.add(myUseLocalDistributionButton, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); + + content.add(myGradleHomeLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); + content.add(myGradleHomePathField, ExternalSystemUiUtil.getFillLineConstraints(0)); + + BundleBoxBuilder builder = BundleBoxBuilder.create(uiDisposable); + builder.withNoneItem("Auto Select", PlatformIconGroup.actionsFind()); + builder.withSdkTypeFilterByClass(JavaSdkType.class); + + myBundleBox = builder.build(); + + content.add( + TargetAWT.to(LabeledBuilder.sided(LocalizeValue.localizeTODO("JRE"), myBundleBox)), + ExternalSystemUiUtil.getFillLineConstraints(0) + ); + } + + private void initControls() { + ActionListener listener = e -> { + boolean localDistributionEnabled = myUseLocalDistributionButton.isSelected(); + myGradleHomePathField.setEnabled(localDistributionEnabled); + if (localDistributionEnabled) { + if (myGradleHomePathField.getText().isEmpty()) { + deduceGradleHomeIfPossible(); + } + else if (myInstallationManager.isGradleSdkHome(myGradleHomePathField.getText())) { + myGradleHomeSettingType = LocationSettingType.EXPLICIT_CORRECT; + } + else { + myGradleHomeSettingType = LocationSettingType.EXPLICIT_INCORRECT; + myShowBalloonIfNecessary = true; + } + showBalloonIfNecessary(); + } + else { + myAlarm.cancelAllRequests(); + } + }; + + myUseWrapperButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.default_wrapper.configured")); + myUseWrapperButton.addActionListener(listener); + myUseWrapperWithVerificationButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.customizable_wrapper")); + myUseWrapperWithVerificationButton.addActionListener(listener); + myUseWrapperVerificationLabel = new JBLabel(GradleBundle.message("gradle.settings.text.wrapper.customization.compatibility")); + myUseWrapperVerificationLabel.setFont(UIUtil.getLabelFont(UIUtil.FontSize.MINI)); + myUseWrapperVerificationLabel.setIcon((Image)AllIcons.General.BalloonInformation); + + myUseLocalDistributionButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.local.distribution")); + myUseLocalDistributionButton.addActionListener(listener); + + myUseBundledDistributionButton = + new JBRadioButton(GradleBundle.message("gradle.settings.text.use.bundled.distribution", GradleVersion.current().getVersion())); + myUseBundledDistributionButton.addActionListener(listener); + myUseBundledDistributionButton.setEnabled(false); + + ButtonGroup buttonGroup = new ButtonGroup(); + buttonGroup.add(myUseWrapperButton); + buttonGroup.add(myUseWrapperWithVerificationButton); + buttonGroup.add(myUseBundledDistributionButton); + buttonGroup.add(myUseLocalDistributionButton); + } + + private void initGradleHome() { + myGradleHomePathField = new TextFieldWithBrowseButton(); + + FileChooserDescriptor fileChooserDescriptor = GradleUtil.getGradleHomeFileChooserDescriptor(); + + myGradleHomePathField.addBrowseFolderListener( + "", + GradleBundle.message("gradle.settings.text.home.path"), + null, + fileChooserDescriptor, + TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, + false + ); + myGradleHomePathField.getTextField().getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + myGradleHomePathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); + } + + @Override + public void removeUpdate(DocumentEvent e) { + myGradleHomePathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); + } + + @Override + public void changedUpdate(DocumentEvent e) { + } + }); + } + + @Override + public boolean validate(@Nonnull GradleProjectSettings settings) throws ConfigurationException { + String gradleHomePath = FileUtil.toCanonicalPath(myGradleHomePathField.getText()); + if (myUseLocalDistributionButton.isSelected()) { + if (StringUtil.isEmpty(gradleHomePath)) { + myGradleHomeSettingType = LocationSettingType.UNKNOWN; + throw new ConfigurationException(GradleBundle.message("gradle.home.setting.type.explicit.empty", gradleHomePath)); + } + else if (!myInstallationManager.isGradleSdkHome(new File(gradleHomePath))) { + myGradleHomeSettingType = LocationSettingType.EXPLICIT_INCORRECT; + new DelayedBalloonInfo(NotificationType.ERROR, myGradleHomeSettingType, 0).run(); + throw new ConfigurationException(GradleBundle.message("gradle.home.setting.type.explicit.incorrect", gradleHomePath)); + } + } + return true; + } + + @Override + protected void applyExtraSettings(@Nonnull GradleProjectSettings settings) { + String gradleHomePath = FileUtil.toCanonicalPath(myGradleHomePathField.getText()); + if (StringUtil.isEmpty(gradleHomePath)) { + settings.setGradleHome(null); + } + else { + settings.setGradleHome(gradleHomePath); + GradleUtil.storeLastUsedGradleHome(gradleHomePath); + } + + if (myUseLocalDistributionButton.isSelected()) { + settings.setDistributionType(DistributionType.LOCAL); + } + else if (myUseWrapperButton.isSelected()) { + settings.setDistributionType(DistributionType.DEFAULT_WRAPPED); + } + else if (myUseWrapperWithVerificationButton.isSelected() || myUseBundledDistributionButton.isSelected()) { + settings.setDistributionType(DistributionType.WRAPPED); + } + + settings.setJreName(myBundleBox.getSelectedBundleName()); + } + + @Override + protected void updateInitialExtraSettings() { + String gradleHomePath = FileUtil.toCanonicalPath(myGradleHomePathField.getText()); + getInitialSettings().setGradleHome(StringUtil.isEmpty(gradleHomePath) ? null : gradleHomePath); + if (myUseLocalDistributionButton.isSelected()) { + getInitialSettings().setDistributionType(DistributionType.LOCAL); + } + else if (myUseWrapperButton.isSelected()) { + getInitialSettings().setDistributionType(DistributionType.DEFAULT_WRAPPED); + } + else if (myUseWrapperWithVerificationButton.isSelected() || myUseBundledDistributionButton.isSelected()) { + getInitialSettings().setDistributionType(DistributionType.WRAPPED); + } + } + + @Override + protected boolean isExtraSettingModified() { + DistributionType distributionType = getInitialSettings().getDistributionType(); + if (myUseBundledDistributionButton.isSelected() && distributionType != DistributionType.BUNDLED) { + return true; + } + + if (myUseWrapperButton.isSelected() && distributionType != DistributionType.DEFAULT_WRAPPED) { + return true; + } + + if (myUseWrapperWithVerificationButton.isSelected() && distributionType != DistributionType.WRAPPED) { + return true; + } + + if (myUseLocalDistributionButton.isSelected() && distributionType != DistributionType.LOCAL) { + return true; + } + + if (!Objects.equals(myBundleBox.getSelectedBundleName(), getInitialSettings().getJreName())) { + return true; + } + + String gradleHome = FileUtil.toCanonicalPath(myGradleHomePathField.getText()); + if (StringUtil.isEmpty(gradleHome)) { + return !StringUtil.isEmpty(getInitialSettings().getGradleHome()); + } + else { + return !gradleHome.equals(getInitialSettings().getGradleHome()); + } + } + + @Override + @RequiredUIAccess + protected void resetExtraSettings(boolean isDefaultModuleCreation) { + String gradleHome = getInitialSettings().getGradleHome(); + myGradleHomePathField.setText(gradleHome == null ? "" : gradleHome); + myGradleHomePathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); + + myBundleBox.setSelectedBundle(getInitialSettings().getJreName()); + + updateWrapperControls(getInitialSettings().getExternalProjectPath(), isDefaultModuleCreation); + if (!myUseLocalDistributionButton.isSelected()) { + myGradleHomePathField.setEnabled(false); + return; + } + + if (StringUtil.isEmpty(gradleHome)) { + myGradleHomeSettingType = LocationSettingType.UNKNOWN; + deduceGradleHomeIfPossible(); + } + else { + myGradleHomeSettingType = myInstallationManager.isGradleSdkHome(new File(gradleHome)) + ? LocationSettingType.EXPLICIT_CORRECT + : LocationSettingType.EXPLICIT_INCORRECT; + myAlarm.cancelAllRequests(); + if (myGradleHomeSettingType == LocationSettingType.EXPLICIT_INCORRECT + && getInitialSettings().getDistributionType() == DistributionType.LOCAL) { + new DelayedBalloonInfo(NotificationType.ERROR, myGradleHomeSettingType, 0).run(); + } + } + } + + public void updateWrapperControls(@Nullable String linkedProjectPath, boolean isDefaultModuleCreation) { + if (StringUtil.isEmpty(linkedProjectPath) && !isDefaultModuleCreation) { + myUseLocalDistributionButton.setSelected(true); + myGradleHomePathField.setEnabled(true); + return; + } + + final boolean isGradleDefaultWrapperFilesExist = GradleUtil.isGradleDefaultWrapperFilesExist(linkedProjectPath); + if (isGradleDefaultWrapperFilesExist || isDefaultModuleCreation) { + myUseWrapperButton.setEnabled(true); + myUseWrapperButton.setSelected(true); + myGradleHomePathField.setEnabled(false); + myUseWrapperButton.setText(GradleBundle.message("gradle.settings.text.use.default_wrapper.configured")); + } + else { + myUseWrapperButton.setEnabled(false); + myUseLocalDistributionButton.setSelected(true); + myGradleHomePathField.setEnabled(true); + myUseWrapperButton.setText(GradleBundle.message("gradle.settings.text.use.default_wrapper.not_configured")); + } + + if (getInitialSettings().getDistributionType() == null) { + return; + } + + switch (getInitialSettings().getDistributionType()) { + case LOCAL: + myGradleHomePathField.setEnabled(true); + myUseLocalDistributionButton.setSelected(true); + break; + case DEFAULT_WRAPPED: + myGradleHomePathField.setEnabled(false); + myUseWrapperButton.setSelected(true); + myUseWrapperButton.setEnabled(true); + break; + case WRAPPED: + myGradleHomePathField.setEnabled(false); + myUseWrapperWithVerificationButton.setSelected(true); + break; + case BUNDLED: + myGradleHomePathField.setEnabled(false); + myUseBundledDistributionButton.setSelected(true); + break; + } + } + + /** + * Updates GUI of the gradle configurable in order to show deduced path to gradle (if possible). + */ + private void deduceGradleHomeIfPossible() { + File gradleHome = myInstallationManager.getAutodetectedGradleHome(); + if (gradleHome == null) { + new DelayedBalloonInfo(NotificationType.WARNING, LocationSettingType.UNKNOWN, BALLOON_DELAY_MILLIS).run(); + return; + } + myGradleHomeSettingType = LocationSettingType.DEDUCED; + new DelayedBalloonInfo(NotificationType.INFO, LocationSettingType.DEDUCED, BALLOON_DELAY_MILLIS).run(); + myGradleHomePathField.setText(gradleHome.getPath()); + myGradleHomePathField.getTextField().setForeground(LocationSettingType.DEDUCED.getColor()); + } + + void showBalloonIfNecessary() { + if (!myShowBalloonIfNecessary || !myGradleHomePathField.isEnabled()) { + return; + } + myShowBalloonIfNecessary = false; + NotificationType messageType = null; + switch (myGradleHomeSettingType) { + case DEDUCED: + messageType = NotificationType.INFO; + break; + case EXPLICIT_INCORRECT: + case UNKNOWN: + messageType = NotificationType.ERROR; + break; + default: + } + if (messageType != null) { + new DelayedBalloonInfo(messageType, myGradleHomeSettingType, BALLOON_DELAY_MILLIS).run(); + } + } + + private class DelayedBalloonInfo implements Runnable { + private final NotificationType myMessageType; + private final String myText; + private final long myTriggerTime; + + DelayedBalloonInfo(@Nonnull NotificationType messageType, @Nonnull LocationSettingType settingType, long delayMillis) { + myMessageType = messageType; + myText = settingType.getDescription(GradleConstants.SYSTEM_ID); + myTriggerTime = System.currentTimeMillis() + delayMillis; + } + + @Override + public void run() { + long diff = myTriggerTime - System.currentTimeMillis(); + if (diff > 0) { + myAlarm.cancelAllRequests(); + myAlarm.addRequest(this, diff); + return; + } + if (myGradleHomePathField == null || !myGradleHomePathField.isShowing()) { + // Don't schedule the balloon if the configurable is hidden. + return; + } + ExternalSystemUiUtil.showBalloon(myGradleHomePathField, myMessageType, myText); + } + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java index 06219f6..acd9fc9 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java @@ -38,129 +38,132 @@ /** * Manages gradle settings not specific to particular project (e.g. 'use wrapper' is project-level setting but 'gradle user home' is * a global one). - * + * * @author Denis Zhdanov * @since 4/28/13 11:06 AM */ public class GradleSystemSettingsControl implements ExternalSystemSettingsControl { + @Nonnull + private final GradleSettings myInitialSettings; + + @SuppressWarnings("FieldCanBeLocal") // Used by reflection at showUi() and disposeUiResources() + private JBLabel myServiceDirectoryLabel; + private TextFieldWithBrowseButton myServiceDirectoryPathField; + @SuppressWarnings("FieldCanBeLocal") // Used by reflection at showUi() and disposeUiResources() + private JBLabel myGradleVmOptionsLabel; + private JBTextField myGradleVmOptionsField; + private boolean myServiceDirectoryPathModifiedByUser; + + public GradleSystemSettingsControl(@Nonnull GradleSettings settings) { + myInitialSettings = settings; + } - @Nonnull - private final GradleSettings myInitialSettings; - - @SuppressWarnings("FieldCanBeLocal") // Used by reflection at showUi() and disposeUiResources() - private JBLabel myServiceDirectoryLabel; - private TextFieldWithBrowseButton myServiceDirectoryPathField; - @SuppressWarnings("FieldCanBeLocal") // Used by reflection at showUi() and disposeUiResources() - private JBLabel myGradleVmOptionsLabel; - private JBTextField myGradleVmOptionsField; - private boolean myServiceDirectoryPathModifiedByUser; - - public GradleSystemSettingsControl(@Nonnull GradleSettings settings) { - myInitialSettings = settings; - } - - @Override - public void fillUi(@Nonnull PaintAwarePanel canvas, int indentLevel) { - myServiceDirectoryLabel = new JBLabel(GradleBundle.message("gradle.settings.text.service.dir.path")); - preparePathControl(); - canvas.add(myServiceDirectoryLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); - canvas.add(myServiceDirectoryPathField, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); - - myGradleVmOptionsLabel = new JBLabel(GradleBundle.message("gradle.settings.text.vm.options")); - canvas.add(myGradleVmOptionsLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); - myGradleVmOptionsField = new JBTextField(); - canvas.add(myGradleVmOptionsField, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); - } - - @Override - public void showUi(boolean show) { - ExternalSystemUiUtil.showUi(this, show); - } - - private void preparePathControl() { - myServiceDirectoryPathField = new TextFieldWithBrowseButton(); - myServiceDirectoryPathField.addBrowseFolderListener("", - GradleBundle.message("gradle.settings.title.service.dir.path"), - null, - new FileChooserDescriptor(false, true, false, false, false, false), - TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, - false); - myServiceDirectoryPathField.getTextField().getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent e) { - myServiceDirectoryPathModifiedByUser = true; - myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); - } + @Override + public void fillUi(@Nonnull PaintAwarePanel canvas, int indentLevel) { + myServiceDirectoryLabel = new JBLabel(GradleBundle.message("gradle.settings.text.service.dir.path")); + preparePathControl(); + canvas.add(myServiceDirectoryLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); + canvas.add(myServiceDirectoryPathField, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); + + myGradleVmOptionsLabel = new JBLabel(GradleBundle.message("gradle.settings.text.vm.options")); + canvas.add(myGradleVmOptionsLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); + myGradleVmOptionsField = new JBTextField(); + canvas.add(myGradleVmOptionsField, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); + } + + @Override + public void showUi(boolean show) { + ExternalSystemUiUtil.showUi(this, show); + } + + private void preparePathControl() { + myServiceDirectoryPathField = new TextFieldWithBrowseButton(); + myServiceDirectoryPathField.addBrowseFolderListener( + "", + GradleBundle.message("gradle.settings.title.service.dir.path"), + null, + new FileChooserDescriptor(false, true, false, false, false, false), + TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, + false + ); + myServiceDirectoryPathField.getTextField().getDocument().addDocumentListener(new DocumentListener() { + @Override + public void insertUpdate(DocumentEvent e) { + myServiceDirectoryPathModifiedByUser = true; + myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); + } + + @Override + public void removeUpdate(DocumentEvent e) { + myServiceDirectoryPathModifiedByUser = true; + myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); + } + + @Override + public void changedUpdate(DocumentEvent e) { + } + }); + } - @Override - public void removeUpdate(DocumentEvent e) { - myServiceDirectoryPathModifiedByUser = true; + @Override + public void reset() { myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); - } - - @Override - public void changedUpdate(DocumentEvent e) { - } - }); - } - - @Override - public void reset() { - myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor()); - myServiceDirectoryPathField.setText(""); - String path = myInitialSettings.getServiceDirectoryPath(); - if (StringUtil.isEmpty(path)) { - deduceServiceDirectoryIfPossible(); + myServiceDirectoryPathField.setText(""); + String path = myInitialSettings.getServiceDirectoryPath(); + if (StringUtil.isEmpty(path)) { + deduceServiceDirectoryIfPossible(); + } + else { + myServiceDirectoryPathField.setText(path); + } + + myGradleVmOptionsField.setText(trimIfPossible(myInitialSettings.getGradleVmOptions())); } - else { - myServiceDirectoryPathField.setText(path); + + private void deduceServiceDirectoryIfPossible() { + String path = System.getenv().get(GradleConstants.SYSTEM_DIRECTORY_PATH_KEY); + if (StringUtil.isEmpty(path)) { + path = new File(System.getProperty("user.home"), ".gradle").getAbsolutePath(); + } + myServiceDirectoryPathField.setText(path); + myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.DEDUCED.getColor()); + myServiceDirectoryPathModifiedByUser = false; + } + + @Override + public boolean isModified() { + return (myServiceDirectoryPathModifiedByUser + && !Comparing.equal( + ExternalSystemApiUtil.normalizePath(myServiceDirectoryPathField.getText()), + ExternalSystemApiUtil.normalizePath(myInitialSettings.getServiceDirectoryPath()) + )) + || !Comparing.equal(trimIfPossible(myGradleVmOptionsField.getText()), trimIfPossible(myInitialSettings.getGradleVmOptions())); + } + + @Nullable + private static String trimIfPossible(@Nullable String s) { + if (s == null) { + return null; + } + String result = s.trim(); + return result.isEmpty() ? null : result; } - - myGradleVmOptionsField.setText(trimIfPossible(myInitialSettings.getGradleVmOptions())); - } - - private void deduceServiceDirectoryIfPossible() { - String path = System.getenv().get(GradleConstants.SYSTEM_DIRECTORY_PATH_KEY); - if (StringUtil.isEmpty(path)) { - path = new File(System.getProperty("user.home"), ".gradle").getAbsolutePath(); + + @Override + public void apply(@Nonnull GradleSettings settings) { + if (myServiceDirectoryPathModifiedByUser) { + settings.setServiceDirectoryPath(ExternalSystemApiUtil.normalizePath(myServiceDirectoryPathField.getText())); + } + settings.setGradleVmOptions(trimIfPossible(myGradleVmOptionsField.getText())); } - myServiceDirectoryPathField.setText(path); - myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.DEDUCED.getColor()); - myServiceDirectoryPathModifiedByUser = false; - } - - @Override - public boolean isModified() { - return (myServiceDirectoryPathModifiedByUser - && !Comparing.equal(ExternalSystemApiUtil.normalizePath(myServiceDirectoryPathField.getText()), - ExternalSystemApiUtil.normalizePath(myInitialSettings.getServiceDirectoryPath()))) - || !Comparing.equal(trimIfPossible(myGradleVmOptionsField.getText()), trimIfPossible(myInitialSettings.getGradleVmOptions())); - } - - @Nullable - private static String trimIfPossible(@Nullable String s) { - if (s == null) { - return null; + + @Override + public boolean validate(@Nonnull GradleSettings settings) throws ConfigurationException { + return true; } - String result = s.trim(); - return result.isEmpty() ? null : result; - } - - @Override - public void apply(@Nonnull GradleSettings settings) { - if (myServiceDirectoryPathModifiedByUser) { - settings.setServiceDirectoryPath(ExternalSystemApiUtil.normalizePath(myServiceDirectoryPathField.getText())); + + @Override + public void disposeUIResources() { + ExternalSystemUiUtil.disposeUi(this); } - settings.setGradleVmOptions(trimIfPossible(myGradleVmOptionsField.getText())); - } - - @Override - public boolean validate(@Nonnull GradleSettings settings) throws ConfigurationException { - return true; - } - - @Override - public void disposeUIResources() { - ExternalSystemUiUtil.disposeUi(this); - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java index 94d8754..2a539c6 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java @@ -33,38 +33,37 @@ * @since 4/30/13 4:58 PM */ public class ImportFromGradleControl - extends AbstractImportFromExternalSystemControl -{ - public ImportFromGradleControl() { - super(GradleConstants.SYSTEM_ID, new GradleSettings(ProjectManager.getInstance().getDefaultProject()), getInitialProjectSettings()); - } + extends AbstractImportFromExternalSystemControl { + public ImportFromGradleControl() { + super(GradleConstants.SYSTEM_ID, new GradleSettings(ProjectManager.getInstance().getDefaultProject()), getInitialProjectSettings()); + } - @Nonnull - private static GradleProjectSettings getInitialProjectSettings() { - GradleProjectSettings result = new GradleProjectSettings(); - String gradleHome = GradleUtil.getLastUsedGradleHome(); - if (!StringUtil.isEmpty(gradleHome)) { - result.setGradleHome(gradleHome); + @Nonnull + private static GradleProjectSettings getInitialProjectSettings() { + GradleProjectSettings result = new GradleProjectSettings(); + String gradleHome = GradleUtil.getLastUsedGradleHome(); + if (!StringUtil.isEmpty(gradleHome)) { + result.setGradleHome(gradleHome); + } + return result; } - return result; - } - - @Nonnull - @Override - protected ExternalSystemSettingsControl createProjectSettingsControl(@Nonnull GradleProjectSettings settings) { - GradleProjectSettingsControl settingsControl = new GradleProjectSettingsControl(settings); - settingsControl.hideUseAutoImportBox(); - return settingsControl; - } - @Nullable - @Override - protected ExternalSystemSettingsControl createSystemSettingsControl(@Nonnull GradleSettings settings) { - return new GradleSystemSettingsControl(settings); - } + @Nonnull + @Override + protected ExternalSystemSettingsControl createProjectSettingsControl(@Nonnull GradleProjectSettings settings) { + GradleProjectSettingsControl settingsControl = new GradleProjectSettingsControl(settings); + settingsControl.hideUseAutoImportBox(); + return settingsControl; + } - @Override - public void onLinkedProjectPathChange(@Nonnull String path) { - ((GradleProjectSettingsControl)getProjectSettingsControl()).updateWrapperControls(path, false); - } + @Nullable + @Override + protected ExternalSystemSettingsControl createSystemSettingsControl(@Nonnull GradleSettings settings) { + return new GradleSystemSettingsControl(settings); + } + + @Override + public void onLinkedProjectPathChange(@Nonnull String path) { + ((GradleProjectSettingsControl)getProjectSettingsControl()).updateWrapperControls(path, false); + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java index dab9c40..e90b4c3 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java @@ -48,102 +48,96 @@ * @since 3/14/13 5:09 PM */ public class GradleTaskManager extends AbstractExternalSystemTaskManager implements - ExternalSystemTaskManager -{ + ExternalSystemTaskManager { - private final GradleExecutionHelper myHelper = new GradleExecutionHelper(); + private final GradleExecutionHelper myHelper = new GradleExecutionHelper(); - @Override - public void executeTasks(@Nonnull final ExternalSystemTaskId id, @Nonnull final List taskNames, @Nonnull String projectPath, - @Nullable final GradleExecutionSettings settings, @Nonnull final List vmOptions, @Nonnull final List scriptParameters, - @Nullable final String debuggerSetup, @Nonnull final ExternalSystemTaskNotificationListener listener) throws ExternalSystemException - { + @Override + public void executeTasks( + @Nonnull final ExternalSystemTaskId id, + @Nonnull final List taskNames, + @Nonnull String projectPath, + @Nullable final GradleExecutionSettings settings, + @Nonnull final List vmOptions, + @Nonnull final List scriptParameters, + @Nullable final String debuggerSetup, + @Nonnull final ExternalSystemTaskNotificationListener listener + ) throws ExternalSystemException { + // TODO add support for external process mode + if (ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) { + for (GradleTaskManagerExtension gradleTaskManagerExtension : GradleTaskManagerExtension.EP_NAME.getExtensions()) { + if (gradleTaskManagerExtension.executeTasks( + id, + taskNames, + projectPath, + settings, + vmOptions, + scriptParameters, + debuggerSetup, + listener + )) { + return; + } + } + } + if (!scriptParameters.contains("--tests") && taskNames.contains("test")) { + ContainerUtil.addAll(scriptParameters, "--tests", "*"); + } - // TODO add support for external process mode - if(ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) - { - for(GradleTaskManagerExtension gradleTaskManagerExtension : GradleTaskManagerExtension.EP_NAME.getExtensions()) - { - if(gradleTaskManagerExtension.executeTasks(id, taskNames, projectPath, settings, vmOptions, scriptParameters, debuggerSetup, - listener)) - { - return; - } - } - } - if(!scriptParameters.contains("--tests") && taskNames.contains("test")) - { - ContainerUtil.addAll(scriptParameters, "--tests", "*"); - } + Function f = connection -> { + final List initScripts = new ArrayList<>(); + final GradleProjectResolverExtension projectResolverChain = GradleProjectResolver.createProjectResolverChain(settings); + for (GradleProjectResolverExtension resolverExtension = projectResolverChain; resolverExtension != null; resolverExtension = + resolverExtension.getNext()) { + final String resolverClassName = resolverExtension.getClass().getName(); + resolverExtension.enhanceTaskProcessing( + taskNames, + debuggerSetup, + script -> { + if (StringUtil.isNotEmpty(script)) { + ContainerUtil.addAllNotNull(initScripts, "//-- Generated by " + resolverClassName, script, "//"); + } + } + ); + } - Function f = new Function() - { - @Override - public Void apply(ProjectConnection connection) - { + if (!initScripts.isEmpty()) { + try { + final File tempFile = FileUtil.createTempFile("init", ".gradle"); + tempFile.deleteOnExit(); + FileUtil.writeToFile(tempFile, StringUtil.join(initScripts, SystemProperties.getLineSeparator())); + ContainerUtil.addAll(scriptParameters, GradleConstants.INIT_SCRIPT_CMD_OPTION, tempFile.getAbsolutePath()); + } + catch (IOException e) { + throw new ExternalSystemException(e); + } + } - final List initScripts = new ArrayList<>(); - final GradleProjectResolverExtension projectResolverChain = GradleProjectResolver.createProjectResolverChain(settings); - for(GradleProjectResolverExtension resolverExtension = projectResolverChain; resolverExtension != null; resolverExtension = - resolverExtension.getNext()) - { - final String resolverClassName = resolverExtension.getClass().getName(); - resolverExtension.enhanceTaskProcessing(taskNames, debuggerSetup, script -> - { - if(StringUtil.isNotEmpty(script)) - { - ContainerUtil.addAllNotNull(initScripts, "//-- Generated by " + resolverClassName, script, "//"); - } - }); - } + BuildLauncher launcher = myHelper.getBuildLauncher(id, connection, settings, listener, vmOptions, scriptParameters); + launcher.forTasks(ArrayUtil.toStringArray(taskNames)); + launcher.run(); + return null; + }; + myHelper.execute(projectPath, settings, f); + } - if(!initScripts.isEmpty()) - { - try - { - final File tempFile = FileUtil.createTempFile("init", ".gradle"); - tempFile.deleteOnExit(); - FileUtil.writeToFile(tempFile, StringUtil.join(initScripts, SystemProperties.getLineSeparator())); - ContainerUtil.addAll(scriptParameters, GradleConstants.INIT_SCRIPT_CMD_OPTION, tempFile.getAbsolutePath()); - } - catch(IOException e) - { - throw new ExternalSystemException(e); - } - } + @Override + public boolean cancelTask(@Nonnull ExternalSystemTaskId id, @Nonnull ExternalSystemTaskNotificationListener listener) throws + ExternalSystemException { + // extension points are available only in IDE process + if (ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) { + for (GradleTaskManagerExtension gradleTaskManagerExtension : GradleTaskManagerExtension.EP_NAME.getExtensions()) { + if (gradleTaskManagerExtension.cancelTask(id, listener)) { + return true; + } + } + } - BuildLauncher launcher = myHelper.getBuildLauncher(id, connection, settings, listener, vmOptions, scriptParameters); - launcher.forTasks(ArrayUtil.toStringArray(taskNames)); - launcher.run(); - return null; - } - }; - myHelper.execute(projectPath, settings, f); - } - - @Override - public boolean cancelTask(@Nonnull ExternalSystemTaskId id, @Nonnull ExternalSystemTaskNotificationListener listener) throws - ExternalSystemException - { - // extension points are available only in IDE process - if(ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) - { - for(GradleTaskManagerExtension gradleTaskManagerExtension : GradleTaskManagerExtension.EP_NAME.getExtensions()) - { - if(gradleTaskManagerExtension.cancelTask(id, listener)) - { - return true; - } - } - } - - // TODO replace with cancellation gradle API invocation when it will be ready, see http://issues.gradle.org/browse/GRADLE-1539 - if(!ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) - { - listener.onStatusChange(new ExternalSystemTaskNotificationEvent(id, "Cancelling the task...\n")); - System.exit(0); - } - return false; - } + // TODO replace with cancellation gradle API invocation when it will be ready, see http://issues.gradle.org/browse/GRADLE-1539 + if (!ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) { + listener.onStatusChange(new ExternalSystemTaskNotificationEvent(id, "Cancelling the task...\n")); + System.exit(0); + } + return false; + } } - diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java index 6ee2b5e..90cb15c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java @@ -34,17 +34,19 @@ @ExtensionAPI(ComponentScope.APPLICATION) public interface GradleTaskManagerExtension { - ExtensionPointName EP_NAME = ExtensionPointName.create(GradleTaskManagerExtension.class); + ExtensionPointName EP_NAME = ExtensionPointName.create(GradleTaskManagerExtension.class); - boolean executeTasks(@Nonnull final ExternalSystemTaskId id, - @Nonnull final List taskNames, - @Nonnull String projectPath, - @Nullable final GradleExecutionSettings settings, - @Nonnull final List vmOptions, - @Nonnull final List scriptParameters, - @Nullable final String debuggerSetup, - @Nonnull final ExternalSystemTaskNotificationListener listener) throws ExternalSystemException; + boolean executeTasks( + @Nonnull final ExternalSystemTaskId id, + @Nonnull final List taskNames, + @Nonnull String projectPath, + @Nullable final GradleExecutionSettings settings, + @Nonnull final List vmOptions, + @Nonnull final List scriptParameters, + @Nullable final String debuggerSetup, + @Nonnull final ExternalSystemTaskNotificationListener listener + ) throws ExternalSystemException; - boolean cancelTask(@Nonnull ExternalSystemTaskId id, @Nonnull ExternalSystemTaskNotificationListener listener) - throws ExternalSystemException; + boolean cancelTask(@Nonnull ExternalSystemTaskId id, @Nonnull ExternalSystemTaskNotificationListener listener) + throws ExternalSystemException; } From 9fc5159591099a891f77f1331fb8c6ef586ba4a4 Mon Sep 17 00:00:00 2001 From: UNV Date: Fri, 9 Aug 2024 13:47:03 +0300 Subject: [PATCH 02/16] Refactoring to reduce number of inspection warnings. --- .../AbstractProjectResolverExtension.java | 272 +++++++++--------- .../GradleProjectResolverExtension.java | 4 +- .../service/GradleBuildClasspathManager.java | 7 +- .../service/GradleInstallationManager.java | 31 +- .../BaseGradleProjectResolverExtension.java | 75 +++-- .../project/DistributionFactoryExt.java | 14 +- .../project/GradleExecutionHelper.java | 29 +- .../service/project/GradleNotification.java | 3 +- .../project/GradleStartupActivity.java | 10 +- ...BuildClasspathModuleGradleDataService.java | 11 +- .../data/ExternalProjectDataService.java | 34 ++- ...nfigurationsNonCodeMembersContributor.java | 6 +- .../resolve/GradleImplicitContributor.java | 57 ++-- .../service/resolve/GradleResolverUtil.java | 4 +- .../resolve/GradleRootContributor.java | 2 +- .../resolve/GradleScriptContributor.java | 12 +- .../GradleSettingsScriptContributor.java | 8 +- ...medDomainObjectCollectionTypeEnhancer.java | 19 +- .../resolve/dsl/GradleDslAnnotator.java | 4 +- .../GradleProjectSettingsControl.java | 25 +- .../settings/GradleSystemSettingsControl.java | 20 +- .../service/task/GradleTaskManager.java | 11 +- .../task/GradleTaskManagerExtension.java | 1 - 23 files changed, 334 insertions(+), 325 deletions(-) diff --git a/gradle-api/src/main/java/consulo/gradle/service/project/AbstractProjectResolverExtension.java b/gradle-api/src/main/java/consulo/gradle/service/project/AbstractProjectResolverExtension.java index 8e9e306..e3674fb 100644 --- a/gradle-api/src/main/java/consulo/gradle/service/project/AbstractProjectResolverExtension.java +++ b/gradle-api/src/main/java/consulo/gradle/service/project/AbstractProjectResolverExtension.java @@ -23,7 +23,7 @@ import consulo.externalSystem.service.project.ProjectData; import consulo.process.ExecutionException; import consulo.process.cmd.SimpleJavaParameters; -import consulo.util.lang.Pair; +import consulo.util.lang.Couple; import org.gradle.tooling.model.idea.IdeaModule; import org.gradle.tooling.model.idea.IdeaProject; @@ -44,135 +44,143 @@ */ public abstract class AbstractProjectResolverExtension implements GradleProjectResolverExtension { - @Nonnull - protected ProjectResolverContext resolverCtx; - @Nonnull - protected GradleProjectResolverExtension nextResolver; - - @Override - public void setProjectResolverContext(@Nonnull ProjectResolverContext projectResolverContext) { - resolverCtx = projectResolverContext; - } - - @Override - public void setNext(@Nonnull GradleProjectResolverExtension next) { - // there always should be at least gradle basic resolver further in the chain - //noinspection ConstantConditions - assert next != null; - nextResolver = next; - } - - @Nullable - @Override - public GradleProjectResolverExtension getNext() { - return nextResolver; - } - - @Nonnull - @Override - public ProjectData createProject() { - return nextResolver.createProject(); - } - - @Nonnull - @Override - public JavaProjectData createJavaProjectData() { - return nextResolver.createJavaProjectData(); - } - - @Override - public void populateProjectExtraModels(@Nonnull IdeaProject gradleProject, @Nonnull DataNode ideProject) { - nextResolver.populateProjectExtraModels(gradleProject, ideProject); - } - - @Nonnull - @Override - public ModuleData createModule(@Nonnull IdeaModule gradleModule, @Nonnull ProjectData projectData) { - return nextResolver.createModule(gradleModule, projectData); - } - - @Override - public void populateModuleExtraModels(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) { - nextResolver.populateModuleExtraModels(gradleModule, ideModule); - } - - @Override - public void populateModuleContentRoots(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) { - nextResolver.populateModuleContentRoots(gradleModule, ideModule); - } - - - @Override - public void populateModuleCompileOutputSettings(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) { - nextResolver.populateModuleCompileOutputSettings(gradleModule, ideModule); - } - - @Override - public void populateModuleDependencies(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule, - @Nonnull DataNode ideProject) { - nextResolver.populateModuleDependencies(gradleModule, ideModule, ideProject); - } - - @Nonnull - @Override - public Collection populateModuleTasks(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule, - @Nonnull DataNode ideProject) throws IllegalArgumentException, IllegalStateException { - return nextResolver.populateModuleTasks(gradleModule, ideModule, ideProject); - } - - @Nonnull - @Override - public Collection filterRootProjectTasks(@Nonnull List allTasks) { - return nextResolver.filterRootProjectTasks(allTasks); - } - - @Nonnull - @Override - public Set getExtraProjectModelClasses() { - return Collections.emptySet(); - } - - @Nonnull - @Override - public Set getToolingExtensionsClasses() { - return Collections.emptySet(); - } - - @Nonnull - @Override - public List> getExtraJvmArgs() { - 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 nextResolver.getUserFriendlyError(error, projectPath, buildFilePath); - } - - @Override - public void enhanceRemoteProcessing(@Nonnull SimpleJavaParameters parameters) throws ExecutionException { - } - - @Override - public void enhanceLocalProcessing(@Nonnull List urls) { - } - - @Override - public void preImportCheck() { - } - - @Override - public void enhanceTaskProcessing(@Nonnull List taskNames, - @Nullable String debuggerSetup, - @Nonnull Consumer initScriptConsumer) { - } + @Nonnull + protected ProjectResolverContext resolverCtx; + @Nonnull + protected GradleProjectResolverExtension nextResolver; + + @Override + public void setProjectResolverContext(@Nonnull ProjectResolverContext projectResolverContext) { + resolverCtx = projectResolverContext; + } + + @Override + public void setNext(@Nonnull GradleProjectResolverExtension next) { + // there always should be at least gradle basic resolver further in the chain + //noinspection ConstantConditions + assert next != null; + nextResolver = next; + } + + @Nullable + @Override + public GradleProjectResolverExtension getNext() { + return nextResolver; + } + + @Nonnull + @Override + public ProjectData createProject() { + return nextResolver.createProject(); + } + + @Nonnull + @Override + public JavaProjectData createJavaProjectData() { + return nextResolver.createJavaProjectData(); + } + + @Override + public void populateProjectExtraModels(@Nonnull IdeaProject gradleProject, @Nonnull DataNode ideProject) { + nextResolver.populateProjectExtraModels(gradleProject, ideProject); + } + + @Nonnull + @Override + public ModuleData createModule(@Nonnull IdeaModule gradleModule, @Nonnull ProjectData projectData) { + return nextResolver.createModule(gradleModule, projectData); + } + + @Override + public void populateModuleExtraModels(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) { + nextResolver.populateModuleExtraModels(gradleModule, ideModule); + } + + @Override + public void populateModuleContentRoots(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) { + nextResolver.populateModuleContentRoots(gradleModule, ideModule); + } + + + @Override + public void populateModuleCompileOutputSettings(@Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule) { + nextResolver.populateModuleCompileOutputSettings(gradleModule, ideModule); + } + + @Override + public void populateModuleDependencies( + @Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule, + @Nonnull DataNode ideProject + ) { + nextResolver.populateModuleDependencies(gradleModule, ideModule, ideProject); + } + + @Nonnull + @Override + public Collection populateModuleTasks( + @Nonnull IdeaModule gradleModule, @Nonnull DataNode ideModule, + @Nonnull DataNode ideProject + ) throws IllegalArgumentException, IllegalStateException { + return nextResolver.populateModuleTasks(gradleModule, ideModule, ideProject); + } + + @Nonnull + @Override + public Collection filterRootProjectTasks(@Nonnull List allTasks) { + return nextResolver.filterRootProjectTasks(allTasks); + } + + @Nonnull + @Override + public Set getExtraProjectModelClasses() { + return Collections.emptySet(); + } + + @Nonnull + @Override + public Set getToolingExtensionsClasses() { + return Collections.emptySet(); + } + + @Nonnull + @Override + public List> getExtraJvmArgs() { + 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 nextResolver.getUserFriendlyError(error, projectPath, buildFilePath); + } + + @Override + public void enhanceRemoteProcessing(@Nonnull SimpleJavaParameters parameters) throws ExecutionException { + } + + @Override + public void enhanceLocalProcessing(@Nonnull List urls) { + } + + @Override + public void preImportCheck() { + } + + @Override + public void enhanceTaskProcessing( + @Nonnull List taskNames, + @Nullable String debuggerSetup, + @Nonnull Consumer initScriptConsumer + ) { + } } diff --git a/gradle-api/src/main/java/consulo/gradle/service/project/GradleProjectResolverExtension.java b/gradle-api/src/main/java/consulo/gradle/service/project/GradleProjectResolverExtension.java index 454f4a5..0663390 100644 --- a/gradle-api/src/main/java/consulo/gradle/service/project/GradleProjectResolverExtension.java +++ b/gradle-api/src/main/java/consulo/gradle/service/project/GradleProjectResolverExtension.java @@ -25,7 +25,7 @@ import consulo.externalSystem.rt.model.ExternalSystemException; import consulo.externalSystem.service.ParametersEnhancer; import consulo.externalSystem.service.project.ProjectData; -import consulo.util.lang.Pair; +import consulo.util.lang.Couple; import org.gradle.tooling.model.idea.IdeaModule; import org.gradle.tooling.model.idea.IdeaProject; @@ -111,7 +111,7 @@ Collection populateModuleTasks(@Nonnull IdeaModule gradleModule, @Nonn Set getToolingExtensionsClasses(); @Nonnull - List> getExtraJvmArgs(); + List> getExtraJvmArgs(); @Nonnull List getExtraCommandLineArgs(); 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 2d9a97e..5af7be5 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 @@ -10,16 +10,15 @@ import consulo.externalSystem.model.project.ExternalProjectBuildClasspathPojo; import consulo.externalSystem.setting.AbstractExternalSystemLocalSettings; import consulo.externalSystem.util.ExternalSystemApiUtil; -import consulo.ide.ServiceManager; +import consulo.gradle.GradleConstants; import consulo.ide.impl.idea.openapi.externalSystem.util.ExternalSystemUtil; -import consulo.ide.impl.idea.util.containers.ContainerUtil; import consulo.project.Project; +import consulo.util.collection.ContainerUtil; import consulo.virtualFileSystem.VirtualFile; import consulo.virtualFileSystem.archive.ArchiveVfsUtil; import jakarta.inject.Inject; import jakarta.inject.Singleton; import org.jetbrains.plugins.gradle.config.GradleClassFinder; -import consulo.gradle.GradleConstants; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -51,7 +50,7 @@ public GradleBuildClasspathManager(@Nonnull Project project) { @Nonnull public static GradleBuildClasspathManager getInstance(@Nonnull Project project) { - return ServiceManager.getService(project, GradleBuildClasspathManager.class); + return project.getInstance(GradleBuildClasspathManager.class); } public void reload() { 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 3e2c2dd..fe48dc9 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 @@ -1,13 +1,16 @@ package org.jetbrains.plugins.gradle.service; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ComponentScope; import consulo.annotation.component.ServiceAPI; import consulo.annotation.component.ServiceImpl; import consulo.externalSystem.util.ExternalSystemApiUtil; import consulo.externalSystem.util.ExternalSystemConstants; +import consulo.gradle.setting.DistributionType; import consulo.module.Module; import consulo.module.ModuleManager; import consulo.module.content.layer.OrderEnumerator; +import consulo.platform.Platform; import consulo.project.Project; import consulo.util.collection.ContainerUtil; import consulo.util.lang.StringUtil; @@ -23,7 +26,6 @@ import org.gradle.wrapper.PathAssembler; import org.gradle.wrapper.WrapperConfiguration; import org.jetbrains.annotations.NonNls; -import consulo.gradle.setting.DistributionType; import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; import org.jetbrains.plugins.gradle.settings.GradleSettings; import org.jetbrains.plugins.gradle.util.GradleEnvironment; @@ -34,11 +36,9 @@ import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; -import java.io.FileFilter; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import java.util.function.Function; import java.util.regex.Pattern; /** @@ -232,7 +232,7 @@ public File getGradleHomeFromPath() { if (ref != null) { return ref.get(); } - String path = System.getenv("PATH"); + String path = Platform.current().os().getEnvironmentVariable("PATH"); if (path == null) { return null; } @@ -246,7 +246,7 @@ public File getGradleHomeFromPath() { if (startFile.isFile()) { File candidate = dir.getParentFile(); if (isGradleSdkHome(candidate)) { - myCachedGradleHomeFromPath = new Ref(candidate); + myCachedGradleHomeFromPath = new Ref<>(candidate); return candidate; } } @@ -262,7 +262,7 @@ public File getGradleHomeFromPath() { */ @Nullable public File getGradleHomeFromEnvProperty() { - String path = System.getenv(GRADLE_ENV_PROPERTY_NAME); + String path = Platform.current().os().getEnvironmentVariable(GRADLE_ENV_PROPERTY_NAME); if (path == null) { return null; } @@ -388,16 +388,17 @@ public List getClassRoots(@Nullable Project project) { return null; } final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); - return ContainerUtil.mapNotNull(files, new Function() { - @Override - public VirtualFile apply(File file) { + return ContainerUtil.mapNotNull( + files, + file -> { final VirtualFile virtualFile = localFileSystem.refreshAndFindFileByIoFile(file); return virtualFile != null ? ArchiveVfsUtil.getArchiveRootForLocalFile(virtualFile) : null; } - }); + ); } @Nullable + @RequiredReadAction public List getClassRoots(@Nullable Project project, @Nullable String rootProjectPath) { if (project == null) { return null; @@ -420,7 +421,7 @@ public List getClassRoots(@Nullable Project project, @Nullable String root } private List findGradleSdkClasspath(Project project, String rootProjectPath) { - List result = new ArrayList(); + List result = new ArrayList<>(); if (StringUtil.isEmpty(rootProjectPath)) { return result; @@ -499,12 +500,8 @@ private File getWrappedGradleHome(String linkedProjectPath, @Nullable final Wrap 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(f -> f.isDirectory() && StringUtil.startsWith(f.getName(), "gradle-")); return distFiles == null || distFiles.length == 0 ? null : distFiles[0]; } 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 04154bb..fa3872b 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 @@ -26,24 +26,23 @@ import consulo.externalSystem.rt.model.*; import consulo.externalSystem.service.project.ProjectData; import consulo.externalSystem.util.ExternalSystemApiUtil; -import consulo.externalSystem.util.Order; +import consulo.gradle.GradleBundle; +import consulo.gradle.GradleConstants; +import consulo.gradle.localize.GradleLocalize; import consulo.gradle.service.project.GradleProjectResolverExtension; import consulo.gradle.service.project.ProjectResolverContext; import consulo.http.HttpProxyManager; import consulo.ide.impl.idea.openapi.application.PathManager; import consulo.ide.impl.idea.openapi.externalSystem.util.ExternalSystemDebugEnvironment; -import consulo.ide.impl.idea.openapi.util.text.StringUtil; import consulo.ide.impl.idea.util.PathUtil; -import consulo.ide.impl.idea.util.containers.ContainerUtil; -import consulo.ide.impl.idea.util.containers.ContainerUtilRt; import consulo.logging.Logger; import consulo.module.content.layer.orderEntry.DependencyScope; +import consulo.platform.Platform; import consulo.process.ExecutionException; import consulo.process.cmd.SimpleJavaParameters; +import consulo.util.collection.ContainerUtil; import consulo.util.io.FileUtil; -import consulo.util.lang.CharArrayUtil; -import consulo.util.lang.Pair; -import consulo.util.lang.SystemProperties; +import consulo.util.lang.*; import consulo.virtualFileSystem.util.PathsList; import groovy.lang.GroovyObject; import org.gradle.tooling.ProjectConnection; @@ -63,14 +62,11 @@ import org.jetbrains.plugins.gradle.tooling.model.ExtIdeaContentRoot; import org.jetbrains.plugins.gradle.tooling.model.ModuleExtendedModel; import org.jetbrains.plugins.gradle.tooling.model.ProjectImportAction; -import consulo.gradle.GradleBundle; -import consulo.gradle.GradleConstants; import org.jetbrains.plugins.gradle.util.GradleUtil; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.File; -import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.util.*; @@ -131,7 +127,11 @@ public JavaProjectData createJavaProjectData() { JavaProjectData javaProjectData = new JavaProjectData(GradleConstants.SYSTEM_ID, projectDirPath + "/build/classes"); javaProjectData.setJdkVersion(ideaProject.getJdkName()); - LanguageLevel languageLevel = StringUtil.parseEnum(ideaProject.getLanguageLevel().getLevel(), null, LanguageLevel.class); + LanguageLevel languageLevel = consulo.ide.impl.idea.openapi.util.text.StringUtil.parseEnum( + ideaProject.getLanguageLevel().getLevel(), + null, + LanguageLevel.class + ); if (languageLevel != null) { javaProjectData.setLanguageLevel(languageLevel); } @@ -196,7 +196,7 @@ public void populateModuleExtraModels(@Nonnull IdeaModule gradleModule, @Nonnull ); } else { - classpathEntries = ContainerUtil.emptyList(); + classpathEntries = List.of(); } BuildScriptClasspathData buildScriptClasspathData = new BuildScriptClasspathData(GradleConstants.SYSTEM_ID, classpathEntries); ideModule.createChild(BuildScriptClasspathData.KEY, buildScriptClasspathData); @@ -231,8 +231,7 @@ public void populateModuleContentRoots(@Nonnull IdeaModule gradleModule, @Nonnul populateContentRoot(ideContentRoot, ExternalSystemSourceType.SOURCE, gradleContentRoot.getSourceDirectories()); populateContentRoot(ideContentRoot, ExternalSystemSourceType.TEST, gradleContentRoot.getTestDirectories()); - if (gradleContentRoot instanceof ExtIdeaContentRoot) { - ExtIdeaContentRoot extIdeaContentRoot = (ExtIdeaContentRoot)gradleContentRoot; + if (gradleContentRoot instanceof ExtIdeaContentRoot extIdeaContentRoot) { populateContentRoot(ideContentRoot, ExternalSystemSourceType.RESOURCE, extIdeaContentRoot.getResourceDirectories()); populateContentRoot( ideContentRoot, @@ -387,8 +386,7 @@ public Collection populateModuleTasks( @Nonnull DataNode ideModule, @Nonnull DataNode ideProject ) throws IllegalArgumentException, IllegalStateException { - - final Collection tasks = ContainerUtil.newArrayList(); + final Collection tasks = new ArrayList<>(); final String moduleConfigPath = ideModule.getData().getLinkedExternalProjectPath(); for (GradleTask task : gradleModule.getGradleProject().getTasks()) { @@ -413,7 +411,7 @@ public Collection filterRootProjectTasks(@Nonnull List allTa @Nonnull @Override public Set getExtraProjectModelClasses() { - return ContainerUtil.set( + return Set.of( GradleBuild.class, ExternalProject.class, ModuleExtendedModel.class, @@ -424,31 +422,33 @@ public Set getExtraProjectModelClasses() { @Nonnull @Override public Set getToolingExtensionsClasses() { - return ContainerUtil.set(ExternalProject.class, + return Set.of( + ExternalProject.class, // gradle-tooling-extension-api jar ProjectImportAction.class, // gradle-tooling-extension-impl jar - ModelBuildScriptClasspathBuilderImpl.class, GsonBuilder.class + ModelBuildScriptClasspathBuilderImpl.class, + GsonBuilder.class ); } @Nonnull @Override - public List> getExtraJvmArgs() { + public List> getExtraJvmArgs() { if (ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) { - final List> extraJvmArgs = ContainerUtil.newArrayList(); + final List> extraJvmArgs = new ArrayList<>(); final HttpProxyManager httpConfigurable = HttpProxyManager.getInstance(); List proxyExceptions = httpConfigurable.getProxyExceptions(); if (!proxyExceptions.isEmpty()) { - extraJvmArgs.add(Pair.create( + extraJvmArgs.add(Couple.of( "http.nonProxyHosts", - consulo.util.lang.StringUtil.join(proxyExceptions, StringUtil.TRIMMER, "|") + StringUtil.join(proxyExceptions, consulo.ide.impl.idea.openapi.util.text.StringUtil.TRIMMER, "|") )); } for (Pair pair : httpConfigurable.getJvmProperties(false, null)) { - extraJvmArgs.add(Pair.create(pair.getFirst(), pair.getSecond())); + extraJvmArgs.add(Couple.of(pair.getFirst(), pair.getSecond())); } return extraJvmArgs; @@ -489,7 +489,7 @@ public void enhanceTaskProcessing( " task.jvmArgs '" + debuggerSetup.trim() + '\'', " }" + "}", }; - final String script = StringUtil.join(lines, SystemProperties.getLineSeparator()); + final String script = StringUtil.join(lines, Platform.current().os().lineSeparator().getSeparatorString()); initScriptConsumer.accept(script); } } @@ -504,30 +504,25 @@ public void enhanceRemoteProcessing(@Nonnull SimpleJavaParameters parameters) th // Gradle tool jars. String toolingApiPath = PathManager.getJarPathForClass(ProjectConnection.class); if (toolingApiPath == null) { - LOG.warn(GradleBundle.message("gradle.generic.text.error.jar.not.found")); + LOG.warn(GradleLocalize.gradleGenericTextErrorJarNotFound().get()); 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"); - } - }); + String[] gradleJars = gradleJarsDir.list((dir, name) -> name.endsWith(".jar")); if (gradleJars == null) { - LOG.warn(GradleBundle.message("gradle.generic.text.error.jar.not.found")); + LOG.warn(GradleLocalize.gradleGenericTextErrorJarNotFound().get()); throw new ExecutionException("Can't find gradle libraries at " + gradleJarsDir.getAbsolutePath()); } for (String jar : gradleJars) { classPath.add(new File(gradleJarsDir, jar).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)); + List additionalEntries = new ArrayList<>(); + ContainerUtil.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(GroovyObject.class)); + ContainerUtil.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(GsonBuilder.class)); + ContainerUtil.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(ExternalProject.class)); + ContainerUtil.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(ProjectImportAction.class)); + ContainerUtil.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(Init.class)); for (String entry : additionalEntries) { classPath.add(entry); } @@ -641,7 +636,7 @@ private static ModuleDependencyData buildDependency( )); } - Set registeredModuleNames = ContainerUtil.newHashSet(); + Set registeredModuleNames = new HashSet<>(); Collection> modulesDataNode = ExternalSystemApiUtil.getChildren(ideProject, ProjectKeys.MODULE); for (DataNode moduleDataNode : modulesDataNode) { String name = moduleDataNode.getData().getExternalName(); 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 6bba433..b542d20 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 @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.gradle.service.project; +import consulo.platform.Platform; import org.gradle.initialization.BuildCancellationToken; import org.gradle.initialization.layout.BuildLayoutFactory; import org.gradle.internal.classpath.ClassPath; @@ -143,7 +144,7 @@ private ClassPath getToolingImpl() { locationDisplayName )); } - Set files = new LinkedHashSet(); + Set files = new LinkedHashSet<>(); //noinspection ConstantConditions for (File file : libDir.listFiles()) { if (file.getName().endsWith(".jar")) { @@ -180,7 +181,7 @@ public ClassPath getToolingImplementationClasspath( final DistributionInstaller installer = new DistributionInstaller(progressLoggerFactory, progressListener, clock); File installDir; try { - cancellationToken.addCallback(() -> installer.cancel()); + cancellationToken.addCallback(installer::cancel); installDir = installer.install( determineRealUserHomeDir(connectionParameters), determineRootDir(connectionParameters), @@ -218,14 +219,7 @@ public ClassPath getToolingImplementationClasspath( private static Map determineSystemProperties(ConnectionParameters connectionParameters) { Map systemProperties = new HashMap<>(); - - for (Map.Entry objectEntry : System.getProperties().entrySet()) { - systemProperties.put( - objectEntry.getKey().toString(), - objectEntry.getValue() == null ? null : objectEntry.getValue().toString() - ); - } - + systemProperties.putAll(Platform.current().jvm().getRuntimeProperties()); systemProperties.putAll(SystemPropertiesHandler.getSystemProperties( new File(determineRootDir(connectionParameters), "gradle.properties") )); 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 ebf6545..fe0b1d1 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 @@ -20,24 +20,24 @@ import consulo.externalSystem.model.task.ExternalSystemTaskNotificationEvent; import consulo.externalSystem.model.task.ExternalSystemTaskNotificationListener; import consulo.externalSystem.rt.model.ExternalSystemException; -import consulo.ide.impl.idea.openapi.util.io.FileUtil; +import consulo.gradle.GradleConstants; +import consulo.gradle.setting.DistributionType; +import consulo.gradle.setting.GradleExecutionSettings; import consulo.ide.impl.idea.util.PathUtil; -import consulo.ide.impl.idea.util.containers.ContainerUtil; +import consulo.util.collection.ContainerUtil; import consulo.logging.Logger; +import consulo.platform.Platform; import consulo.util.collection.ArrayUtil; +import consulo.util.io.FileUtil; import consulo.util.io.StreamUtil; import consulo.util.lang.ExceptionUtil; import consulo.util.lang.StringUtil; -import consulo.util.lang.SystemProperties; import org.gradle.process.internal.JvmOptions; import org.gradle.tooling.*; import org.gradle.tooling.internal.consumer.DefaultGradleConnector; import org.gradle.tooling.internal.consumer.Distribution; import org.gradle.tooling.model.build.BuildEnvironment; -import consulo.gradle.setting.DistributionType; -import consulo.gradle.setting.GradleExecutionSettings; import org.jetbrains.plugins.gradle.tooling.impl.internal.init.Init; -import consulo.gradle.GradleConstants; import org.jetbrains.plugins.gradle.util.GradleEnvironment; import org.jetbrains.plugins.gradle.util.GradleUtil; @@ -71,7 +71,7 @@ public ModelBuilder getModelBuilder( @Nonnull List extraJvmArgs ) { ModelBuilder result = connection.model(modelType); - prepare(result, id, settings, listener, extraJvmArgs, ContainerUtil.newArrayList(), connection); + prepare(result, id, settings, listener, extraJvmArgs, new ArrayList<>(), connection); return result; } @@ -265,9 +265,14 @@ public void ensureInstalledWrapper( "').write wrapperPropertyFileLocation", "}}", }; - FileUtil.writeToFile(tempFile, StringUtil.join(lines, SystemProperties.getLineSeparator())); - - BuildLauncher launcher = getBuildLauncher(id, connection, settings, listener, ContainerUtil.newArrayList(), + FileUtil.writeToFile(tempFile, StringUtil.join(lines, Platform.current().os().lineSeparator().getSeparatorString())); + + BuildLauncher launcher = getBuildLauncher( + id, + connection, + settings, + listener, + new ArrayList<>(), ContainerUtil.newArrayList( GradleConstants.INIT_SCRIPT_CMD_OPTION, tempFile.getAbsolutePath() @@ -275,7 +280,7 @@ public void ensureInstalledWrapper( ); launcher.forTasks("wrapper"); launcher.run(); - String wrapperPropertyFile = FileUtil.loadFile(wrapperPropertyFileLocation); + String wrapperPropertyFile = consulo.ide.impl.idea.openapi.util.io.FileUtil.loadFile(wrapperPropertyFileLocation); settings.setWrapperPropertyFile(wrapperPropertyFile); } catch (IOException e) { @@ -460,7 +465,7 @@ private static BuildEnvironment getBuildEnvironment(@Nonnull ProjectConnection c } private static void replaceTestCommandOptionWithInitScript(@Nonnull List args) { - Set testIncludePatterns = ContainerUtil.newLinkedHashSet(); + Set testIncludePatterns = new LinkedHashSet<>(); Iterator it = args.iterator(); while (it.hasNext()) { final String next = it.next(); 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 3063ede..3b1989f 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 @@ -18,7 +18,6 @@ import consulo.annotation.component.ComponentScope; import consulo.annotation.component.ServiceAPI; import consulo.annotation.component.ServiceImpl; -import consulo.ide.ServiceManager; import consulo.project.Project; import consulo.project.ui.notification.NotificationGroup; import consulo.project.ui.notification.NotificationType; @@ -45,7 +44,7 @@ public class GradleNotification { @Nonnull public static GradleNotification getInstance(@Nonnull Project project) { - return ServiceManager.getService(project, GradleNotification.class); + return project.getInstance(GradleNotification.class); } @Inject 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 bdae184..0f88559 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 @@ -18,7 +18,10 @@ import consulo.annotation.component.ExtensionImpl; import consulo.application.WriteAction; import consulo.externalSystem.model.ExternalSystemDataKeys; +import consulo.gradle.GradleBundle; +import consulo.gradle.GradleConstants; import consulo.gradle.impl.importProvider.GradleModuleImportProvider; +import consulo.gradle.localize.GradleLocalize; import consulo.ide.impl.idea.ide.util.PropertiesComponent; import consulo.ide.impl.idea.openapi.vfs.VfsUtilCore; import consulo.ide.moduleImport.ModuleImportContext; @@ -40,13 +43,10 @@ import consulo.virtualFileSystem.VirtualFile; import org.jetbrains.plugins.gradle.service.GradleBuildClasspathManager; import org.jetbrains.plugins.gradle.settings.GradleSettings; -import consulo.gradle.GradleBundle; -import consulo.gradle.GradleConstants; import javax.annotation.Nonnull; import javax.swing.event.HyperlinkEvent; import java.io.File; -import java.io.FilenameFilter; import java.util.Collections; /** @@ -84,12 +84,12 @@ private static void showNotificationForUnlinkedGradleProject(@Nonnull final Proj if (files != null && files.length != 0) { String message = String.format( "%s
\n%s", - GradleBundle.message("gradle.notifications.unlinked.project.found.msg", IMPORT_EVENT_DESCRIPTION), + GradleLocalize.gradleNotificationsUnlinkedProjectFoundMsg(IMPORT_EVENT_DESCRIPTION).get(), GradleBundle.message("gradle.notifications.do.not.show", DO_NOT_SHOW_EVENT_DESCRIPTION) ); GradleNotification.getInstance(project).showBalloon( - GradleBundle.message("gradle.notifications.unlinked.project.found.title"), + GradleLocalize.gradleNotificationsUnlinkedProjectFoundTitle().get(), message, NotificationType.INFORMATION, new NotificationListener.Adapter() { 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 fac319d..194e014 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 @@ -29,7 +29,7 @@ import consulo.externalSystem.util.ExternalSystemApiUtil; import consulo.externalSystem.util.ExternalSystemConstants; import consulo.externalSystem.util.Order; -import consulo.ide.ServiceManager; +import consulo.gradle.GradleConstants; import consulo.ide.impl.idea.util.containers.ContainerUtil; import consulo.project.Project; import consulo.util.collection.FactoryMap; @@ -39,7 +39,6 @@ import org.jetbrains.plugins.gradle.service.GradleInstallationManager; import org.jetbrains.plugins.gradle.settings.GradleProjectSettings; import org.jetbrains.plugins.gradle.settings.GradleSettings; -import consulo.gradle.GradleConstants; import javax.annotation.Nonnull; import java.io.File; @@ -71,7 +70,7 @@ public void importData( return; } - final GradleInstallationManager gradleInstallationManager = ServiceManager.getService(GradleInstallationManager.class); + final GradleInstallationManager gradleInstallationManager = project.getInstance(GradleInstallationManager.class); ExternalSystemManager manager = ExternalSystemApiUtil.getManager(GradleConstants.SYSTEM_ID); assert manager != null; @@ -118,7 +117,7 @@ public void importData( continue; } - final Set buildClasspath = ContainerUtil.newLinkedHashSet(); + final Set buildClasspath = new LinkedHashSet<>(); BuildScriptClasspathData buildScriptClasspathData = node.getData(); for (BuildScriptClasspathData.ClasspathEntry classpathEntry : buildScriptClasspathData.getClasspathEntries()) { for (String path : classpathEntry.getSourcesFile()) { @@ -135,8 +134,8 @@ public void importData( if (projectBuildClasspathPojo == null) { projectBuildClasspathPojo = new ExternalProjectBuildClasspathPojo( moduleDataNode.getData().getExternalName(), - ContainerUtil.newArrayList(), - ContainerUtil.newHashMap() + new ArrayList<>(), + new HashMap<>() ); localSettings.getProjectBuildClasspath().put(linkedExternalProjectPath, projectBuildClasspathPojo); } 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 416a1c0..42c304f 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 @@ -15,12 +15,10 @@ */ package org.jetbrains.plugins.gradle.service.project.data; -import consulo.application.CommonBundle; import consulo.application.progress.ProgressIndicator; import consulo.application.progress.Task; import consulo.application.util.ConcurrentFactoryMap; -import consulo.application.util.function.Computable; -import consulo.externalSystem.ExternalSystemBundle; +import consulo.externalSystem.localize.ExternalSystemLocalize; import consulo.externalSystem.model.DataNode; import consulo.externalSystem.model.Key; import consulo.externalSystem.model.ProjectKeys; @@ -38,9 +36,11 @@ import consulo.ide.impl.idea.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask; import consulo.ide.impl.idea.openapi.externalSystem.service.notification.ExternalSystemNotificationManager; import consulo.ide.impl.idea.openapi.externalSystem.service.project.manage.ProjectDataManager; +import consulo.localize.LocalizeValue; import consulo.logging.Logger; import consulo.module.Module; import consulo.module.content.ProjectRootManager; +import consulo.platform.base.localize.CommonLocalize; import consulo.project.Project; import consulo.ui.ex.awt.Messages; import consulo.ui.ex.awt.UIUtil; @@ -54,7 +54,6 @@ import java.io.File; import java.util.Collection; import java.util.Map; -import java.util.function.Function; /** * @author Vladislav.Soroka @@ -85,6 +84,7 @@ public Key getTargetDataKey() { return KEY; } + @Override public void importData( @Nonnull final Collection> toImport, @Nonnull final Project project, @@ -134,7 +134,7 @@ private ExternalProject importExternalProject( if (LOG.isDebugEnabled()) { LOG.debug("Available projects paths: " + ContainerUtil.map( ExternalSystemApiUtil.getSettings(project, projectSystemId).getLinkedProjectsSettings(), - (Function)settings -> settings.getExternalProjectPath() + ExternalProjectSettings::getExternalProjectPath )); } return false; @@ -152,35 +152,33 @@ private ExternalProject importExternalProject( // 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() + "Project '%s' require synchronization with %s configuration. \nImport the project?", + projectName, + projectSystemId.getDisplayName() ); int returnValue = Messages.showOkCancelDialog( message, "Import Project", - CommonBundle.getOkButtonText(), - CommonBundle.getCancelButtonText(), - Messages.getQuestionIcon() + CommonLocalize.buttonOk().get(), + CommonLocalize.buttonCancel().get(), + UIUtil.getQuestionIcon() ); if (returnValue != Messages.OK) { return false; } } - final String title = - ExternalSystemBundle.message("progress.import.text", linkedProjectPath, projectSystemId.getReadableName()); - new Task.Modal(project, title, false) { + final LocalizeValue title = + ExternalSystemLocalize.progressImportText(linkedProjectPath, projectSystemId.getDisplayName()); + new Task.Modal(project, title.get(), false) { @Override public void run(@Nonnull ProgressIndicator indicator) { if (project.isDisposed()) { return; } - ExternalSystemNotificationManager.getInstance(project).clearNotifications( - null, - NotificationSource.PROJECT_SYNC, - projectSystemId - ); + ExternalSystemNotificationManager.getInstance(project) + .clearNotifications(null, NotificationSource.PROJECT_SYNC, projectSystemId); ExternalSystemResolveProjectTask task = new ExternalSystemResolveProjectTask(projectSystemId, project, linkedProjectPath, false); task.execute(indicator, ExternalSystemTaskNotificationListener.EP_NAME.getExtensions()); diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java index f4d889f..ae31148 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java @@ -51,9 +51,9 @@ public class GradleConfigurationsNonCodeMembersContributor extends NonCodeMember public void processDynamicElements( @Nonnull PsiType qualifierType, PsiClass aClass, - PsiScopeProcessor processor, - PsiElement place, - ResolveState state + @Nonnull PsiScopeProcessor processor, + @Nonnull PsiElement place, + @Nonnull ResolveState state ) { if (place == null || aClass == null) { return; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleImplicitContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleImplicitContributor.java index 373aca6..02336e8 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleImplicitContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleImplicitContributor.java @@ -17,6 +17,7 @@ import com.intellij.java.language.psi.PsiClass; import com.intellij.java.language.psi.PsiType; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.externalSystem.model.execution.ExternalTaskPojo; import consulo.externalSystem.util.ExternalSystemApiUtil; @@ -27,7 +28,7 @@ import consulo.language.psi.resolve.ResolveState; import consulo.language.util.ModuleUtilCore; import consulo.module.Module; -import consulo.util.lang.Pair; +import consulo.util.lang.Couple; import org.jetbrains.plugins.gradle.settings.GradleLocalSettings; import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; @@ -53,33 +54,34 @@ @ExtensionImpl public class GradleImplicitContributor implements GradleMethodContextContributor { private final static Map BUILT_IN_TASKS = ContainerUtil.newHashMap( - new Pair("assemble", GRADLE_API_DEFAULT_TASK), - new Pair("build", GRADLE_API_DEFAULT_TASK), - new Pair("buildDependents", GRADLE_API_DEFAULT_TASK), - new Pair("buildNeeded", GRADLE_API_DEFAULT_TASK), - new Pair("clean", GRADLE_API_TASKS_DELETE), - new Pair("jar", GRADLE_API_TASKS_BUNDLING_JAR), - new Pair("war", GRADLE_API_TASKS_BUNDLING_WAR), - new Pair("classes", GRADLE_API_DEFAULT_TASK), - new Pair("compileJava", GRADLE_API_TASKS_COMPILE_JAVA_COMPILE), - new Pair("compileTestJava", GRADLE_API_DEFAULT_TASK), - new Pair("processTestResources", GRADLE_API_DEFAULT_TASK), - new Pair("testClasses", GRADLE_API_DEFAULT_TASK), - new Pair("processResources", GRADLE_LANGUAGE_JVM_TASKS_PROCESS_RESOURCES), - new Pair("setupBuild", GRADLE_BUILDSETUP_TASKS_SETUP_BUILD), - new Pair("wrapper", GRADLE_API_TASKS_WRAPPER_WRAPPER), - new Pair("javadoc", GRADLE_API_TASKS_JAVADOC_JAVADOC), - new Pair("dependencies", GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_REPORT_TASK), - new Pair("dependencyInsight", GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_INSIGHT_REPORT_TASK), - new Pair("projects", GRADLE_API_TASKS_DIAGNOSTICS_PROJECT_REPORT_TASK), - new Pair("properties", GRADLE_API_TASKS_DIAGNOSTICS_PROPERTY_REPORT_TASK), - new Pair("tasks", GRADLE_API_TASKS_DIAGNOSTICS_TASK_REPORT_TASK), - new Pair("check", GRADLE_API_DEFAULT_TASK), - new Pair("test", GRADLE_API_TASKS_TESTING_TEST), - new Pair("uploadArchives", GRADLE_API_TASKS_UPLOAD) + Couple.of("assemble", GRADLE_API_DEFAULT_TASK), + Couple.of("build", GRADLE_API_DEFAULT_TASK), + Couple.of("buildDependents", GRADLE_API_DEFAULT_TASK), + Couple.of("buildNeeded", GRADLE_API_DEFAULT_TASK), + Couple.of("clean", GRADLE_API_TASKS_DELETE), + Couple.of("jar", GRADLE_API_TASKS_BUNDLING_JAR), + Couple.of("war", GRADLE_API_TASKS_BUNDLING_WAR), + Couple.of("classes", GRADLE_API_DEFAULT_TASK), + Couple.of("compileJava", GRADLE_API_TASKS_COMPILE_JAVA_COMPILE), + Couple.of("compileTestJava", GRADLE_API_DEFAULT_TASK), + Couple.of("processTestResources", GRADLE_API_DEFAULT_TASK), + Couple.of("testClasses", GRADLE_API_DEFAULT_TASK), + Couple.of("processResources", GRADLE_LANGUAGE_JVM_TASKS_PROCESS_RESOURCES), + Couple.of("setupBuild", GRADLE_BUILDSETUP_TASKS_SETUP_BUILD), + Couple.of("wrapper", GRADLE_API_TASKS_WRAPPER_WRAPPER), + Couple.of("javadoc", GRADLE_API_TASKS_JAVADOC_JAVADOC), + Couple.of("dependencies", GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_REPORT_TASK), + Couple.of("dependencyInsight", GRADLE_API_TASKS_DIAGNOSTICS_DEPENDENCY_INSIGHT_REPORT_TASK), + Couple.of("projects", GRADLE_API_TASKS_DIAGNOSTICS_PROJECT_REPORT_TASK), + Couple.of("properties", GRADLE_API_TASKS_DIAGNOSTICS_PROPERTY_REPORT_TASK), + Couple.of("tasks", GRADLE_API_TASKS_DIAGNOSTICS_TASK_REPORT_TASK), + Couple.of("check", GRADLE_API_DEFAULT_TASK), + Couple.of("test", GRADLE_API_TASKS_TESTING_TEST), + Couple.of("uploadArchives", GRADLE_API_TASKS_UPLOAD) ); @Override + @RequiredReadAction public void process( @Nonnull List methodCallInfo, @Nonnull PsiScopeProcessor processor, @@ -126,7 +128,7 @@ public void process( } } - if (place instanceof GrExpression && GradleResolverUtil.getTypeOf((GrExpression)place) == null) { + if (place instanceof GrExpression placeExpression && GradleResolverUtil.getTypeOf(placeExpression) == null) { GrClosableBlock closableBlock = GradleResolverUtil.findParent(place, GrClosableBlock.class); if (closableBlock != null && closableBlock.getParent() instanceof GrMethodCallExpression methodCallExpression) { PsiType psiType = GradleResolverUtil.getTypeOf(methodCallExpression); @@ -138,6 +140,7 @@ public void process( } } + @RequiredReadAction public static void processImplicitDeclarations( @Nonnull PsiScopeProcessor processor, @Nonnull ResolveState state, @@ -149,6 +152,7 @@ public static void processImplicitDeclarations( } } + @RequiredReadAction private static void checkForAvailableTasks( int level, @Nullable String taskName, @@ -196,6 +200,7 @@ private static void checkForAvailableTasks( } } + @RequiredReadAction private static void processTask( @Nonnull String taskName, @Nonnull String fqName, diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java index 12d1950..982b05b 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java @@ -16,6 +16,7 @@ package org.jetbrains.plugins.gradle.service.resolve; import com.intellij.java.language.psi.*; +import consulo.annotation.access.RequiredReadAction; import consulo.application.util.RecursionManager; import consulo.java.language.module.util.JavaClassNames; import consulo.language.psi.PsiElement; @@ -77,6 +78,7 @@ public static void addImplicitVariable( } } + @RequiredReadAction public static void addImplicitVariable( @Nonnull PsiScopeProcessor processor, @Nonnull ResolveState state, @@ -258,7 +260,7 @@ public static PsiType getTypeOf(@Nullable final GrExpression expression) { if (expression == null) { return null; } - return RecursionManager.doPreventingRecursion(expression, true, () -> expression.getNominalType()); + return RecursionManager.doPreventingRecursion(expression, true, expression::getNominalType); } public static boolean isLShiftElement(@Nullable PsiElement psiElement) { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java index 7008428..a071184 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java @@ -16,7 +16,7 @@ package org.jetbrains.plugins.gradle.service.resolve; import consulo.annotation.component.ExtensionImpl; -import consulo.ide.impl.idea.util.containers.ContainerUtil; +import consulo.util.collection.ContainerUtil; import consulo.language.psi.PsiElement; import consulo.language.psi.resolve.PsiScopeProcessor; import consulo.language.psi.resolve.ResolveState; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java index 9a6040a..3a12b6f 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java @@ -17,8 +17,9 @@ import com.intellij.java.language.psi.PsiClass; import com.intellij.java.language.psi.PsiType; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; -import consulo.ide.impl.idea.util.containers.ContainerUtil; +import consulo.util.collection.ContainerUtil; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; import consulo.language.psi.resolve.PsiScopeProcessor; @@ -42,7 +43,7 @@ */ @ExtensionImpl public class GradleScriptContributor extends NonCodeMembersContributor { - public final static Set BUILD_PROJECT_SCRIPT_BLOCKS = ContainerUtil.newHashSet( + public final static Set BUILD_PROJECT_SCRIPT_BLOCKS = Set.of( "project", "configure", "subprojects", @@ -51,12 +52,13 @@ public class GradleScriptContributor extends NonCodeMembersContributor { ); @Override + @RequiredReadAction public void processDynamicElements( @Nonnull PsiType qualifierType, PsiClass aClass, - PsiScopeProcessor processor, - PsiElement place, - ResolveState state + @Nonnull PsiScopeProcessor processor, + @Nonnull PsiElement place, + @Nonnull ResolveState state ) { if (place == null) { return; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java index c9a9229..4dd2f17 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java @@ -17,6 +17,7 @@ import com.intellij.java.language.psi.PsiClass; import com.intellij.java.language.psi.PsiType; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.psi.PsiElement; import consulo.language.psi.PsiFile; @@ -36,12 +37,13 @@ @ExtensionImpl public class GradleSettingsScriptContributor extends NonCodeMembersContributor { @Override + @RequiredReadAction public void processDynamicElements( @Nonnull PsiType qualifierType, PsiClass aClass, - PsiScopeProcessor processor, - PsiElement place, - ResolveState state + @Nonnull PsiScopeProcessor processor, + @Nonnull PsiElement place, + @Nonnull ResolveState state ) { if (place == null) { return; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java index 9fa8cda..580bb51 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java @@ -81,17 +81,14 @@ else if (qualifierExpression instanceof GrMethodCall methodCall) { if (namedDomainCollectionType instanceof PsiClassReferenceType) { final PsiClassReferenceType referenceType = (PsiClassReferenceType)namedDomainCollectionType; final String fqName = referenceType.getCanonicalText(); - if (GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER.equals(fqName)) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); - return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_SOURCE_SET, ref.getResolveScope()); - } - else if (GradleCommonClassNames.GRADLE_API_CONFIGURATION_CONTAINER.equals(fqName)) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); - return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_CONFIGURATION, ref.getResolveScope()); - } - else if (GradleCommonClassNames.GRADLE_API_TASK_CONTAINER.equals(fqName)) { - final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); - return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_TASK, ref.getResolveScope()); + final GroovyPsiManager psiManager = GroovyPsiManager.getInstance(ref.getProject()); + switch (fqName) { + case GradleCommonClassNames.GRADLE_API_SOURCE_SET_CONTAINER: + return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_SOURCE_SET, ref.getResolveScope()); + case GradleCommonClassNames.GRADLE_API_CONFIGURATION_CONTAINER: + return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_CONFIGURATION, ref.getResolveScope()); + case GradleCommonClassNames.GRADLE_API_TASK_CONTAINER: + return psiManager.createTypeByFQClassName(GradleCommonClassNames.GRADLE_API_TASK, ref.getResolveScope()); } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java index cebff33..e5b134a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java @@ -20,6 +20,7 @@ import com.intellij.java.language.psi.util.InheritanceUtil; import consulo.language.editor.annotation.AnnotationHolder; import consulo.language.editor.annotation.Annotator; +import consulo.language.editor.annotation.HighlightSeverity; import consulo.language.psi.PsiElement; import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames; import org.jetbrains.plugins.gradle.service.resolve.GradleResolverUtil; @@ -69,7 +70,8 @@ public void annotate(@Nonnull PsiElement element, @Nonnull AnnotationHolder hold PsiElement nameElement = referenceExpression.getReferenceNameElement(); if (nameElement != null) { - holder.createInfoAnnotation(nameElement, null).setTextAttributes(GroovySyntaxHighlighter.MAP_KEY); + holder.newSilentAnnotation(HighlightSeverity.INFORMATION) + .textAttributes(GroovySyntaxHighlighter.MAP_KEY); } } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java index 324410b..0ebf6f8 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java @@ -24,6 +24,7 @@ import consulo.fileChooser.FileChooserDescriptor; import consulo.gradle.GradleBundle; import consulo.gradle.GradleConstants; +import consulo.gradle.localize.GradleLocalize; import consulo.gradle.setting.DistributionType; import consulo.ide.ServiceManager; import consulo.ide.impl.idea.openapi.externalSystem.model.settings.LocationSettingType; @@ -37,7 +38,6 @@ import consulo.ui.ex.awt.*; import consulo.ui.ex.awt.util.Alarm; import consulo.ui.ex.awtUnsafe.TargetAWT; -import consulo.ui.image.Image; import consulo.ui.util.LabeledBuilder; import consulo.util.io.FileUtil; import consulo.util.lang.StringUtil; @@ -91,6 +91,7 @@ public GradleProjectSettingsControl(@Nonnull GradleProjectSettings initialSettin } @Override + @RequiredUIAccess protected void fillExtraControls(@Nonnull Disposable uiDisposable, @Nonnull PaintAwarePanel content, int indentLevel) { content.setPaintCallback(graphics -> showBalloonIfNecessary()); @@ -108,7 +109,7 @@ protected void fillExtraControls(@Nonnull Disposable uiDisposable, @Nonnull Pain } }); - myGradleHomeLabel = new JBLabel(GradleBundle.message("gradle.settings.text.home.path")); + myGradleHomeLabel = new JBLabel(GradleLocalize.gradleSettingsTextHomePath().get()); initGradleHome(); initControls(); @@ -157,19 +158,19 @@ else if (myInstallationManager.isGradleSdkHome(myGradleHomePathField.getText())) } }; - myUseWrapperButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.default_wrapper.configured")); + myUseWrapperButton = new JBRadioButton(GradleLocalize.gradleSettingsTextUseDefault_wrapperConfigured().get()); myUseWrapperButton.addActionListener(listener); - myUseWrapperWithVerificationButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.customizable_wrapper")); + myUseWrapperWithVerificationButton = new JBRadioButton(GradleLocalize.gradleSettingsTextUseCustomizable_wrapper().get()); myUseWrapperWithVerificationButton.addActionListener(listener); - myUseWrapperVerificationLabel = new JBLabel(GradleBundle.message("gradle.settings.text.wrapper.customization.compatibility")); + myUseWrapperVerificationLabel = new JBLabel(GradleLocalize.gradleSettingsTextWrapperCustomizationCompatibility().get()); myUseWrapperVerificationLabel.setFont(UIUtil.getLabelFont(UIUtil.FontSize.MINI)); - myUseWrapperVerificationLabel.setIcon((Image)AllIcons.General.BalloonInformation); + myUseWrapperVerificationLabel.setIcon(AllIcons.General.BalloonInformation); - myUseLocalDistributionButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.local.distribution")); + myUseLocalDistributionButton = new JBRadioButton(GradleLocalize.gradleSettingsTextUseLocalDistribution().get()); myUseLocalDistributionButton.addActionListener(listener); myUseBundledDistributionButton = - new JBRadioButton(GradleBundle.message("gradle.settings.text.use.bundled.distribution", GradleVersion.current().getVersion())); + new JBRadioButton(GradleLocalize.gradleSettingsTextUseBundledDistribution(GradleVersion.current().getVersion()).get()); myUseBundledDistributionButton.addActionListener(listener); myUseBundledDistributionButton.setEnabled(false); @@ -187,7 +188,7 @@ private void initGradleHome() { myGradleHomePathField.addBrowseFolderListener( "", - GradleBundle.message("gradle.settings.text.home.path"), + GradleLocalize.gradleSettingsTextHomePath().get(), null, fileChooserDescriptor, TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, @@ -221,7 +222,7 @@ public boolean validate(@Nonnull GradleProjectSettings settings) throws Configur else if (!myInstallationManager.isGradleSdkHome(new File(gradleHomePath))) { myGradleHomeSettingType = LocationSettingType.EXPLICIT_INCORRECT; new DelayedBalloonInfo(NotificationType.ERROR, myGradleHomeSettingType, 0).run(); - throw new ConfigurationException(GradleBundle.message("gradle.home.setting.type.explicit.incorrect", gradleHomePath)); + throw new ConfigurationException(GradleLocalize.gradleHomeSettingTypeExplicitIncorrect(gradleHomePath).get()); } } return true; @@ -341,13 +342,13 @@ public void updateWrapperControls(@Nullable String linkedProjectPath, boolean is myUseWrapperButton.setEnabled(true); myUseWrapperButton.setSelected(true); myGradleHomePathField.setEnabled(false); - myUseWrapperButton.setText(GradleBundle.message("gradle.settings.text.use.default_wrapper.configured")); + myUseWrapperButton.setText(GradleLocalize.gradleSettingsTextUseDefault_wrapperConfigured().get()); } else { myUseWrapperButton.setEnabled(false); myUseLocalDistributionButton.setSelected(true); myGradleHomePathField.setEnabled(true); - myUseWrapperButton.setText(GradleBundle.message("gradle.settings.text.use.default_wrapper.not_configured")); + myUseWrapperButton.setText(GradleLocalize.gradleSettingsTextUseDefault_wrapperNot_configured().get()); } if (getInitialSettings().getDistributionType() == null) { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java index acd9fc9..e4927b5 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java @@ -21,13 +21,17 @@ import consulo.externalSystem.ui.awt.PaintAwarePanel; import consulo.externalSystem.util.ExternalSystemApiUtil; import consulo.fileChooser.FileChooserDescriptor; +import consulo.gradle.GradleConstants; +import consulo.gradle.localize.GradleLocalize; import consulo.ide.impl.idea.openapi.externalSystem.model.settings.LocationSettingType; -import consulo.ui.ex.awt.*; +import consulo.platform.Platform; +import consulo.ui.ex.awt.JBLabel; +import consulo.ui.ex.awt.JBTextField; +import consulo.ui.ex.awt.TextComponentAccessor; +import consulo.ui.ex.awt.TextFieldWithBrowseButton; import consulo.util.lang.Comparing; import consulo.util.lang.StringUtil; import org.jetbrains.plugins.gradle.settings.GradleSettings; -import consulo.gradle.GradleBundle; -import consulo.gradle.GradleConstants; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -60,12 +64,12 @@ public GradleSystemSettingsControl(@Nonnull GradleSettings settings) { @Override public void fillUi(@Nonnull PaintAwarePanel canvas, int indentLevel) { - myServiceDirectoryLabel = new JBLabel(GradleBundle.message("gradle.settings.text.service.dir.path")); + myServiceDirectoryLabel = new JBLabel(GradleLocalize.gradleSettingsTextServiceDirPath().get()); preparePathControl(); canvas.add(myServiceDirectoryLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); canvas.add(myServiceDirectoryPathField, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); - myGradleVmOptionsLabel = new JBLabel(GradleBundle.message("gradle.settings.text.vm.options")); + myGradleVmOptionsLabel = new JBLabel(GradleLocalize.gradleSettingsTextVmOptions().get()); canvas.add(myGradleVmOptionsLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel)); myGradleVmOptionsField = new JBTextField(); canvas.add(myGradleVmOptionsField, ExternalSystemUiUtil.getFillLineConstraints(indentLevel)); @@ -80,7 +84,7 @@ private void preparePathControl() { myServiceDirectoryPathField = new TextFieldWithBrowseButton(); myServiceDirectoryPathField.addBrowseFolderListener( "", - GradleBundle.message("gradle.settings.title.service.dir.path"), + GradleLocalize.gradleSettingsTitleServiceDirPath().get(), null, new FileChooserDescriptor(false, true, false, false, false, false), TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT, @@ -121,9 +125,9 @@ public void reset() { } private void deduceServiceDirectoryIfPossible() { - String path = System.getenv().get(GradleConstants.SYSTEM_DIRECTORY_PATH_KEY); + String path = Platform.current().os().getEnvironmentVariable(GradleConstants.SYSTEM_DIRECTORY_PATH_KEY); if (StringUtil.isEmpty(path)) { - path = new File(System.getProperty("user.home"), ".gradle").getAbsolutePath(); + path = new File(Platform.current().jvm().getRuntimeProperty("user.home"), ".gradle").getAbsolutePath(); } myServiceDirectoryPathField.setText(path); myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.DEDUCED.getColor()); diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java index e90b4c3..8f947ad 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java @@ -21,19 +21,19 @@ import consulo.externalSystem.rt.model.ExternalSystemException; import consulo.externalSystem.task.ExternalSystemTaskManager; import consulo.externalSystem.util.ExternalSystemApiUtil; +import consulo.gradle.GradleConstants; +import consulo.gradle.service.project.GradleProjectResolverExtension; +import consulo.gradle.setting.GradleExecutionSettings; import consulo.ide.impl.idea.openapi.externalSystem.task.AbstractExternalSystemTaskManager; +import consulo.platform.Platform; import consulo.util.collection.ArrayUtil; import consulo.util.collection.ContainerUtil; import consulo.util.io.FileUtil; import consulo.util.lang.StringUtil; -import consulo.util.lang.SystemProperties; import org.gradle.tooling.BuildLauncher; import org.gradle.tooling.ProjectConnection; import org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper; import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver; -import consulo.gradle.service.project.GradleProjectResolverExtension; -import consulo.gradle.setting.GradleExecutionSettings; -import consulo.gradle.GradleConstants; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -105,7 +105,8 @@ public void executeTasks( try { final File tempFile = FileUtil.createTempFile("init", ".gradle"); tempFile.deleteOnExit(); - FileUtil.writeToFile(tempFile, StringUtil.join(initScripts, SystemProperties.getLineSeparator())); + String path = StringUtil.join(initScripts, Platform.current().os().lineSeparator().getSeparatorString()); + FileUtil.writeToFile(tempFile, path); ContainerUtil.addAll(scriptParameters, GradleConstants.INIT_SCRIPT_CMD_OPTION, tempFile.getAbsolutePath()); } catch (IOException e) { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java index 90cb15c..4a301df 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java @@ -33,7 +33,6 @@ */ @ExtensionAPI(ComponentScope.APPLICATION) public interface GradleTaskManagerExtension { - ExtensionPointName EP_NAME = ExtensionPointName.create(GradleTaskManagerExtension.class); boolean executeTasks( From b3f7331adeb5192b40a1b1995543ac15322206f3 Mon Sep 17 00:00:00 2001 From: Valery Semenchuk Date: Fri, 9 Aug 2024 14:56:09 +0400 Subject: [PATCH 03/16] Create maven.yml --- .github/workflows/maven.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .github/workflows/maven.yml diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 0000000..a666fa4 --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,25 @@ +name: jdk21 + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +env: + BUILD_NUMBER: 999999 + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 21 + uses: actions/setup-java@v1 + with: + distribution: 'temurin' + java-version: 21 + - name: Build with Maven + run: mvn -U -T 1C -Dmaven.javadoc.skip=true -B -V clean package From c087475d786b0d4ea8cd2d8258eaa94bd074f985 Mon Sep 17 00:00:00 2001 From: UNV Date: Fri, 9 Aug 2024 15:54:33 +0300 Subject: [PATCH 04/16] Code reformat using IJ4 code style (part 2). --- ...avenProjectImportNotificationListener.java | 19 +- .../maven/GradleMavenRepositoryProvider.java | 11 +- .../maven/GradleProjectStartupActivity.java | 9 +- .../maven/ImportMavenRepositoriesTask.java | 402 ++++++++------- .../maven/MavenRepositoriesHolder.java | 38 +- .../action/AddGradleDslDependencyAction.java | 35 +- .../AddGradleDslDependencyActionHandler.java | 125 ++--- ...pendenciesGradleCompletionContributor.java | 259 +++++----- .../GradleModuleImportProvider.java | 154 +++--- .../AbstractGradleLinkedProjectAction.java | 76 +-- .../gradle/action/GradleOpenScriptAction.java | 35 +- .../action/GradleToolWindowHelpAction.java | 31 +- ...butionWithSourcesNotificationProvider.java | 289 +++++------ .../actions/AddGradleDslPluginAction.java | 59 +-- .../AddGradleDslPluginActionHandler.java | 120 ++--- .../codeInspection/GradleBaseInspection.java | 10 +- .../GradleInspectionBundle.java | 28 +- .../MultipleRepositoryUrlsFix.java | 67 +-- .../MultipleRepositoryUrlsInspection.java | 146 +++--- ...legatingGradleSettingsListenerAdapter.java | 33 +- ...dleBuildClasspathResolveScopeEnlarger.java | 25 +- .../gradle/config/GradleClassFinder.java | 93 ++-- .../GradleDefaultImportContributor.java | 227 +++++---- .../GradleLibraryPresentationProvider.java | 143 +++--- .../plugins/gradle/config/GradlePatcher.java | 29 +- .../gradle/config/GradlePositionManager.java | 226 +++++---- .../gradle/config/GradleScriptType.java | 465 +++++++++--------- .../config/GradleScriptTypeDetector.java | 14 +- .../config/GradleSettingsListenerAdapter.java | 27 +- .../gradle/config/GradleToolWindowPanel.java | 169 ++++--- 30 files changed, 1714 insertions(+), 1650 deletions(-) diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenProjectImportNotificationListener.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenProjectImportNotificationListener.java index 6eeebd6..03a80a1 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenProjectImportNotificationListener.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenProjectImportNotificationListener.java @@ -33,14 +33,15 @@ */ @ExtensionImpl public class GradleMavenProjectImportNotificationListener extends ExternalSystemTaskNotificationListenerAdapter { - - @Override - public void onSuccess(@Nonnull ExternalSystemTaskId id) { - if (GradleConstants.SYSTEM_ID.getId().equals(id.getProjectSystemId().getId()) - && id.getType() == ExternalSystemTaskType.RESOLVE_PROJECT) { - final Project project = id.findProject(); - if (project == null) return; - Application.get().invokeLater(new ImportMavenRepositoriesTask(project)); + @Override + public void onSuccess(@Nonnull ExternalSystemTaskId id) { + if (GradleConstants.SYSTEM_ID.getId().equals(id.getProjectSystemId().getId()) + && id.getType() == ExternalSystemTaskType.RESOLVE_PROJECT) { + final Project project = id.findProject(); + if (project == null) { + return; + } + Application.get().invokeLater(new ImportMavenRepositoriesTask(project)); + } } - } } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenRepositoryProvider.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenRepositoryProvider.java index 130494a..ed734b2 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenRepositoryProvider.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenRepositoryProvider.java @@ -29,10 +29,9 @@ */ @ExtensionImpl public class GradleMavenRepositoryProvider implements MavenRepositoryProvider { - - @Nonnull - @Override - public Set getRemoteRepositories(@Nonnull Project project) { - return MavenRepositoriesHolder.getInstance(project).getRemoteRepositories(); - } + @Nonnull + @Override + public Set getRemoteRepositories(@Nonnull Project project) { + return MavenRepositoriesHolder.getInstance(project).getRemoteRepositories(); + } } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleProjectStartupActivity.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleProjectStartupActivity.java index bc86929..9461306 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleProjectStartupActivity.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleProjectStartupActivity.java @@ -29,9 +29,8 @@ */ @ExtensionImpl public class GradleProjectStartupActivity implements PostStartupActivity { - - @Override - public void runActivity(@Nonnull final Project project, @Nonnull UIAccess uiAccess) { - DumbService.getInstance(project).smartInvokeLater(new ImportMavenRepositoriesTask(project)); - } + @Override + public void runActivity(@Nonnull final Project project, @Nonnull UIAccess uiAccess) { + DumbService.getInstance(project).smartInvokeLater(new ImportMavenRepositoriesTask(project)); + } } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java index 978ccd8..a28bab6 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java @@ -59,233 +59,227 @@ * @since 10/29/13 */ public class ImportMavenRepositoriesTask implements Runnable { - @Nonnull - private final static MavenRemoteRepository mavenCentralRemoteRepository; + @Nonnull + private final static MavenRemoteRepository mavenCentralRemoteRepository; - static { - mavenCentralRemoteRepository = new MavenRemoteRepository("central", null, "https://repo1.maven.org/maven2/", null, null, null); - } - - private final Project myProject; + static { + mavenCentralRemoteRepository = + new MavenRemoteRepository("central", null, "https://repo1.maven.org/maven2/", null, null, null); + } - public ImportMavenRepositoriesTask(Project project) { - myProject = project; - } + private final Project myProject; - @Override - public void run() { - if (myProject.isDisposed()) { - return; + public ImportMavenRepositoriesTask(Project project) { + myProject = project; } - final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); - final List psiFileList = new ArrayList<>(); - - final ModuleManager moduleManager = ModuleManager.getInstance(myProject); - for (Module module : moduleManager.getModules()) { - final String externalSystemId = - ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY); - final String modulePath = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.LINKED_PROJECT_PATH_KEY); - if (!GradleConstants.SYSTEM_ID.getId().equals(externalSystemId) || modulePath == null) { - continue; - } - - String buildScript = FileUtil.findFileInProvidedPath(modulePath, GradleConstants.DEFAULT_SCRIPT_NAME); - if (StringUtil.isEmpty(buildScript)) { - continue; - } - - VirtualFile virtualFile = - localFileSystem.refreshAndFindFileByPath(buildScript); - if (virtualFile == null) { - continue; - } - - final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(virtualFile); - if (psiFile == null) { - continue; - } - psiFileList.add(psiFile); - } + @Override + public void run() { + if (myProject.isDisposed()) { + return; + } - final PsiFile[] psiFiles = ArrayUtil.toObjectArray(psiFileList, PsiFile.class); - - final Set mavenRemoteRepositories = ReadAction.compute(() -> - { - Set remoteRepositories = - new HashSet<>(); - for (PsiFile psiFile : psiFiles) { - List repositoriesBlocks = - new ArrayList<>(); - repositoriesBlocks.addAll(findClosableBlocks(psiFile, - "repositories")); - - for (GrClosableBlock closableBlock : findClosableBlocks( - psiFile, - "buildscript", - "subprojects", - "allprojects", - "project", - "configure")) { - repositoriesBlocks.addAll(findClosableBlocks( - closableBlock, - "repositories")); - } - - for (GrClosableBlock repositoriesBlock : repositoriesBlocks) { - remoteRepositories.addAll( - findMavenRemoteRepositories(repositoriesBlock)); - } - } - - return remoteRepositories; - }); - - if (mavenRemoteRepositories == null || mavenRemoteRepositories.isEmpty()) { - return; - } + final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); + final List psiFileList = new ArrayList<>(); + + final ModuleManager moduleManager = ModuleManager.getInstance(myProject); + for (Module module : moduleManager.getModules()) { + final String externalSystemId = + ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY); + final String modulePath = + ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.LINKED_PROJECT_PATH_KEY); + if (!GradleConstants.SYSTEM_ID.getId().equals(externalSystemId) || modulePath == null) { + continue; + } - MavenRepositoriesHolder.getInstance(myProject).update(mavenRemoteRepositories); + String buildScript = FileUtil.findFileInProvidedPath(modulePath, GradleConstants.DEFAULT_SCRIPT_NAME); + if (StringUtil.isEmpty(buildScript)) { + continue; + } - MavenProjectIndicesManager.getInstance(myProject).scheduleUpdateIndicesList(new Consumer>() { - @Override - public void accept(List indexes) { - for (MavenIndex mavenIndex : indexes) { - if (mavenIndex.getUpdateTimestamp() == -1 && - MavenRepositoriesHolder.getInstance(myProject).contains(mavenIndex.getRepositoryId())) { - MavenProjectIndicesManager.getInstance(myProject).scheduleUpdate(Collections.singletonList(mavenIndex)); - } - } - } - }); - } - - @Nonnull - private static Collection findClosableBlocks(@Nonnull final PsiElement element, - @Nonnull final String... blockNames) { - List methodCalls = PsiTreeUtil.getChildrenOfTypeAsList(element, GrMethodCall.class); - return ContainerUtil.mapNotNull(methodCalls, new Function() { - @Override - public GrClosableBlock apply(GrMethodCall call) { - if (call == null || call.getClosureArguments().length != 1) { - return null; - } + VirtualFile virtualFile = localFileSystem.refreshAndFindFileByPath(buildScript); + if (virtualFile == null) { + continue; + } - GrExpression expression = call.getInvokedExpression(); - return expression != null && ArrayUtil.contains(expression.getText(), blockNames) ? call.getClosureArguments()[0] : null; - } - }); - } - - @Nonnull - private static Collection findMavenRemoteRepositories(@Nullable GrClosableBlock repositoriesBlock) { - Set myRemoteRepositories = new HashSet<>(); - for (GrMethodCall repo : PsiTreeUtil - .getChildrenOfTypeAsList(repositoriesBlock, GrMethodCall.class)) { - if (repo.getInvokedExpression() == null) { - continue; - } - - final String expressionText = repo.getInvokedExpression().getText(); - if ("mavenCentral".equals(expressionText)) { - myRemoteRepositories.add(mavenCentralRemoteRepository); - } - else if ("mavenRepo".equals(expressionText)) { - for (GrNamedArgument namedArgument : repo.getNamedArguments()) { - if ("url".equals(namedArgument.getLabelName())) { - URI urlArgumentValue = resolveUriFromSimpleExpression(namedArgument.getExpression()); - if (urlArgumentValue != null) { - String textUri = urlArgumentValue.toString(); - myRemoteRepositories.add(new MavenRemoteRepository(textUri, null, textUri, null, null, null)); + final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(virtualFile); + if (psiFile == null) { + continue; } - break; - } + psiFileList.add(psiFile); } - } - else if ("maven".equals(expressionText) && repo.getClosureArguments().length > 0) { - List applicationStatementList = - PsiTreeUtil.getChildrenOfTypeAsList(repo.getClosureArguments()[0], GrApplicationStatement.class); - if (!applicationStatementList.isEmpty()) { - GrApplicationStatement statement = applicationStatementList.get(0); - if (statement == null) { - continue; - } - GrExpression expression = statement.getInvokedExpression(); - if (expression == null) { - continue; - } - - if ("url".equals(expression.getText())) { - URI urlArgumentValue = resolveUriFromSimpleExpression(statement.getExpressionArguments()[0]); - if (urlArgumentValue != null) { - String textUri = urlArgumentValue.toString(); - myRemoteRepositories.add(new MavenRemoteRepository(textUri, null, textUri, null, null, null)); + + final PsiFile[] psiFiles = ArrayUtil.toObjectArray(psiFileList, PsiFile.class); + + final Set mavenRemoteRepositories = ReadAction.compute(() -> { + Set remoteRepositories = new HashSet<>(); + for (PsiFile psiFile : psiFiles) { + List repositoriesBlocks = new ArrayList<>(); + repositoriesBlocks.addAll(findClosableBlocks(psiFile, "repositories")); + + for (GrClosableBlock closableBlock : + findClosableBlocks(psiFile, "buildscript", "subprojects", "allprojects", "project", "configure")) { + repositoriesBlocks.addAll(findClosableBlocks(closableBlock, "repositories")); + } + + for (GrClosableBlock repositoriesBlock : repositoriesBlocks) { + remoteRepositories.addAll(findMavenRemoteRepositories(repositoriesBlock)); + } } - } + + return remoteRepositories; + }); + + if (mavenRemoteRepositories == null || mavenRemoteRepositories.isEmpty()) { + return; } - List assignmentExpressionList = - PsiTreeUtil.getChildrenOfTypeAsList(repo.getClosureArguments()[0], GrAssignmentExpression.class); - if (!assignmentExpressionList.isEmpty()) { - GrAssignmentExpression statement = assignmentExpressionList.get(0); - if (statement == null) { - continue; - } - GrExpression expression = statement.getLValue(); - - if ("url".equals(expression.getText())) { - URI urlArgumentValue = resolveUriFromSimpleExpression(statement.getRValue()); - if (urlArgumentValue != null) { - String textUri = urlArgumentValue.toString(); - myRemoteRepositories.add(new MavenRemoteRepository(textUri, null, textUri, null, null, null)); + MavenRepositoriesHolder.getInstance(myProject).update(mavenRemoteRepositories); + + MavenProjectIndicesManager.getInstance(myProject).scheduleUpdateIndicesList(indexes -> { + for (MavenIndex mavenIndex : indexes) { + if (mavenIndex.getUpdateTimestamp() == -1 + && MavenRepositoriesHolder.getInstance(myProject).contains(mavenIndex.getRepositoryId())) { + MavenProjectIndicesManager.getInstance(myProject).scheduleUpdate(Collections.singletonList(mavenIndex)); + } } - } - } - } + }); } - return myRemoteRepositories; - } - - @Nullable - private static URI resolveUriFromSimpleExpression(@Nullable GrExpression expression) { - if (expression == null) { - return null; + @Nonnull + private static Collection findClosableBlocks( + @Nonnull final PsiElement element, + @Nonnull final String... blockNames + ) { + List methodCalls = PsiTreeUtil.getChildrenOfTypeAsList(element, GrMethodCall.class); + return ContainerUtil.mapNotNull( + methodCalls, + call -> { + if (call == null || call.getClosureArguments().length != 1) { + return null; + } + + GrExpression expression = call.getInvokedExpression(); + return expression != null && ArrayUtil.contains(expression.getText(), blockNames) ? call.getClosureArguments()[0] : null; + } + ); } - try { - if (expression instanceof PsiLiteral) { - URI uri = new URI(String.valueOf(PsiLiteral.class.cast(expression).getValue())); - if (uri.getScheme() != null && StringUtil.startsWith(uri.getScheme(), "http")) { - return uri; + @Nonnull + private static Collection findMavenRemoteRepositories(@Nullable GrClosableBlock repositoriesBlock) { + Set myRemoteRepositories = new HashSet<>(); + for (GrMethodCall repo : PsiTreeUtil + .getChildrenOfTypeAsList(repositoriesBlock, GrMethodCall.class)) { + if (repo.getInvokedExpression() == null) { + continue; + } + + final String expressionText = repo.getInvokedExpression().getText(); + if ("mavenCentral".equals(expressionText)) { + myRemoteRepositories.add(mavenCentralRemoteRepository); + } + else if ("mavenRepo".equals(expressionText)) { + for (GrNamedArgument namedArgument : repo.getNamedArguments()) { + if ("url".equals(namedArgument.getLabelName())) { + URI urlArgumentValue = resolveUriFromSimpleExpression(namedArgument.getExpression()); + if (urlArgumentValue != null) { + String textUri = urlArgumentValue.toString(); + myRemoteRepositories.add( + new MavenRemoteRepository(textUri, null, textUri, null, null, null) + ); + } + break; + } + } + } + else if ("maven".equals(expressionText) && repo.getClosureArguments().length > 0) { + List applicationStatementList = + PsiTreeUtil.getChildrenOfTypeAsList(repo.getClosureArguments()[0], GrApplicationStatement.class); + if (!applicationStatementList.isEmpty()) { + GrApplicationStatement statement = applicationStatementList.get(0); + if (statement == null) { + continue; + } + GrExpression expression = statement.getInvokedExpression(); + if (expression == null) { + continue; + } + + if ("url".equals(expression.getText())) { + URI urlArgumentValue = resolveUriFromSimpleExpression(statement.getExpressionArguments()[0]); + if (urlArgumentValue != null) { + String textUri = urlArgumentValue.toString(); + myRemoteRepositories.add( + new MavenRemoteRepository(textUri, null, textUri, null, null, null) + ); + } + } + } + + List assignmentExpressionList = + PsiTreeUtil.getChildrenOfTypeAsList(repo.getClosureArguments()[0], GrAssignmentExpression.class); + if (!assignmentExpressionList.isEmpty()) { + GrAssignmentExpression statement = assignmentExpressionList.get(0); + if (statement == null) { + continue; + } + GrExpression expression = statement.getLValue(); + + if ("url".equals(expression.getText())) { + URI urlArgumentValue = resolveUriFromSimpleExpression(statement.getRValue()); + if (urlArgumentValue != null) { + String textUri = urlArgumentValue.toString(); + myRemoteRepositories.add( + new MavenRemoteRepository(textUri, null, textUri, null, null, null) + ); + } + } + } + } } - } - } - catch (URISyntaxException ignored) { - // ignore it + + return myRemoteRepositories; } - try { - PsiReference reference = expression.getReference(); - if (reference == null) { - return null; - } - PsiElement element = reference.resolve(); - if (element instanceof GrVariable) { - List grLiterals = PsiTreeUtil.getChildrenOfTypeAsList(element, GrLiteral.class); - if (grLiterals.isEmpty()) { - return null; + @Nullable + private static URI resolveUriFromSimpleExpression(@Nullable GrExpression expression) { + if (expression == null) { + return null; + } + + try { + if (expression instanceof PsiLiteral) { + URI uri = new URI(String.valueOf(PsiLiteral.class.cast(expression).getValue())); + if (uri.getScheme() != null && StringUtil.startsWith(uri.getScheme(), "http")) { + return uri; + } + } } - URI uri = new URI(String.valueOf(grLiterals.get(0).getValue())); - if (uri.getScheme() != null && StringUtil.startsWith("http", uri.getScheme())) { - return uri; + catch (URISyntaxException ignored) { + // ignore it + } + + try { + PsiReference reference = expression.getReference(); + if (reference == null) { + return null; + } + PsiElement element = reference.resolve(); + if (element instanceof GrVariable) { + List grLiterals = PsiTreeUtil.getChildrenOfTypeAsList(element, GrLiteral.class); + if (grLiterals.isEmpty()) { + return null; + } + URI uri = new URI(String.valueOf(grLiterals.get(0).getValue())); + if (uri.getScheme() != null && StringUtil.startsWith("http", uri.getScheme())) { + return uri; + } + } + } + catch (URISyntaxException ignored) { + // ignore it } - } - } - catch (URISyntaxException ignored) { - // ignore it - } - return null; - } + return null; + } } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/MavenRepositoriesHolder.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/MavenRepositoriesHolder.java index 304cc84..69d5781 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/MavenRepositoriesHolder.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/MavenRepositoriesHolder.java @@ -33,28 +33,30 @@ @ServiceAPI(ComponentScope.PROJECT) @ServiceImpl public class MavenRepositoriesHolder { - private volatile Set myRemoteRepositories; + private volatile Set myRemoteRepositories; - public MavenRepositoriesHolder() { - myRemoteRepositories = new HashSet<>(); - } + public MavenRepositoriesHolder() { + myRemoteRepositories = new HashSet<>(); + } - public static MavenRepositoriesHolder getInstance(Project project) { - return project.getInstance(MavenRepositoriesHolder.class); - } + public static MavenRepositoriesHolder getInstance(Project project) { + return project.getInstance(MavenRepositoriesHolder.class); + } - public void update(Set remoteRepositories) { - myRemoteRepositories = new HashSet<>(remoteRepositories); - } + public void update(Set remoteRepositories) { + myRemoteRepositories = new HashSet<>(remoteRepositories); + } - public Set getRemoteRepositories() { - return myRemoteRepositories; - } + public Set getRemoteRepositories() { + return myRemoteRepositories; + } - public boolean contains(String repositoryId) { - for (MavenRemoteRepository repository : myRemoteRepositories) { - if (repository.getId().equals(repositoryId)) return true; + public boolean contains(String repositoryId) { + for (MavenRemoteRepository repository : myRemoteRepositories) { + if (repository.getId().equals(repositoryId)) { + return true; + } + } + return false; } - return false; - } } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java index a7eb873..26ed075 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java @@ -39,24 +39,25 @@ */ @ActionImpl(id = "Gradle.AddGradleDslDependencyAction", parents = @ActionParentRef(value = @ActionRef(id = "GenerateGroup"))) public class AddGradleDslDependencyAction extends CodeInsightAction { - static final ThreadLocal> TEST_THREAD_LOCAL = new ThreadLocal>(); + static final ThreadLocal> TEST_THREAD_LOCAL = new ThreadLocal<>(); - public AddGradleDslDependencyAction() { - getTemplatePresentation().setDescription(GradleBundle.message("gradle.codeInsight.action.add_maven_dependency.description")); - getTemplatePresentation().setText(GradleBundle.message("gradle.codeInsight.action.add_maven_dependency.text")); - getTemplatePresentation().setIcon(AllIcons.Nodes.PpLib); - } + public AddGradleDslDependencyAction() { + getTemplatePresentation().setDescription(GradleBundle.message("gradle.codeInsight.action.add_maven_dependency.description")); + getTemplatePresentation().setText(GradleBundle.message("gradle.codeInsight.action.add_maven_dependency.text")); + getTemplatePresentation().setIcon(AllIcons.Nodes.PpLib); + } - @Nonnull - @Override - protected CodeInsightActionHandler getHandler() { - return new AddGradleDslDependencyActionHandler(); - } + @Nonnull + @Override + protected CodeInsightActionHandler getHandler() { + return new AddGradleDslDependencyActionHandler(); + } - @Override - protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file) { - if (file instanceof PsiCompiledElement) return false; - if (!GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType())) return false; - return !GradleConstants.SETTINGS_FILE_NAME.equals(file.getName()) && file.getName().endsWith(GradleConstants.EXTENSION); - } + @Override + protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file) { + if (file instanceof PsiCompiledElement || !GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType())) { + return false; + } + return !GradleConstants.SETTINGS_FILE_NAME.equals(file.getName()) && file.getName().endsWith(GradleConstants.EXTENSION); + } } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java index bdc66a5..ecccabe 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java @@ -45,73 +45,80 @@ * @since 10/23/13 */ class AddGradleDslDependencyActionHandler implements CodeInsightActionHandler { + @Override + public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) { + if (!LanguageEditorUtil.checkModificationAllowed(editor)) { + return; + } - @Override - public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) { - if (!LanguageEditorUtil.checkModificationAllowed(editor)) return; - - final List ids; - if (ApplicationManager.getApplication().isUnitTestMode()) { - ids = AddGradleDslDependencyAction.TEST_THREAD_LOCAL.get(); - } - else { - ids = MavenArtifactSearchDialog.searchForArtifact(project, Collections.emptyList()); - } + final List ids; + if (ApplicationManager.getApplication().isUnitTestMode()) { + ids = AddGradleDslDependencyAction.TEST_THREAD_LOCAL.get(); + } + else { + ids = MavenArtifactSearchDialog.searchForArtifact(project, Collections.emptyList()); + } - if (ids.isEmpty()) return; + if (ids.isEmpty()) { + return; + } - new WriteCommandAction.Simple(project, GradleBundle.message("gradle.codeInsight.action.add_maven_dependency.text"), file) { - @Override - protected void run() { - GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); - List closableBlocks = PsiTreeUtil.getChildrenOfTypeAsList(file, GrMethodCall.class); - GrCall dependenciesBlock = ContainerUtil.find(closableBlocks, new Predicate() { - @Override - public boolean test(GrMethodCall call) { - GrExpression expression = call.getInvokedExpression(); - return expression != null && "dependencies".equals(expression.getText()); - } - }); + new WriteCommandAction.Simple(project, GradleBundle.message("gradle.codeInsight.action.add_maven_dependency.text"), file) { + @Override + protected void run() { + GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); + List closableBlocks = PsiTreeUtil.getChildrenOfTypeAsList(file, GrMethodCall.class); + GrCall dependenciesBlock = ContainerUtil.find(closableBlocks, new Predicate() { + @Override + public boolean test(GrMethodCall call) { + GrExpression expression = call.getInvokedExpression(); + return expression != null && "dependencies".equals(expression.getText()); + } + }); - if (dependenciesBlock == null) { - StringBuilder buf = new StringBuilder(); - for (MavenId mavenId : ids) { - buf.append(String.format("compile '%s'\n", getMavenArtifactKey(mavenId))); - } - dependenciesBlock = (GrCall)factory.createStatementFromText("dependencies{\n" + buf + "}"); - file.add(dependenciesBlock); - } - else { - GrClosableBlock closableBlock = ArrayUtil.getFirstElement(dependenciesBlock.getClosureArguments()); - if (closableBlock != null) { - for (MavenId mavenId : ids) { - closableBlock.addStatementBefore( - factory.createStatementFromText(String.format("compile '%s'\n", getMavenArtifactKey(mavenId))), null); + if (dependenciesBlock == null) { + StringBuilder buf = new StringBuilder(); + for (MavenId mavenId : ids) { + buf.append(String.format("compile '%s'\n", getMavenArtifactKey(mavenId))); + } + dependenciesBlock = (GrCall)factory.createStatementFromText("dependencies{\n" + buf + "}"); + file.add(dependenciesBlock); + } + else { + GrClosableBlock closableBlock = ArrayUtil.getFirstElement(dependenciesBlock.getClosureArguments()); + if (closableBlock != null) { + for (MavenId mavenId : ids) { + closableBlock.addStatementBefore( + factory.createStatementFromText(String.format("compile '%s'\n", getMavenArtifactKey(mavenId))), + null + ); + } + } + } } - } - } - } - }.execute(); - } + }.execute(); + } - @Override - public boolean startInWriteAction() { - return false; - } + @Override + public boolean startInWriteAction() { + return false; + } - @Nonnull - private static String getMavenArtifactKey(MavenId mavenId) { - StringBuilder builder = new StringBuilder(); - append(builder, mavenId.getGroupId()); - append(builder, mavenId.getArtifactId()); - append(builder, mavenId.getVersion()); + @Nonnull + private static String getMavenArtifactKey(MavenId mavenId) { + StringBuilder builder = new StringBuilder(); + append(builder, mavenId.getGroupId()); + append(builder, mavenId.getArtifactId()); + append(builder, mavenId.getVersion()); - return builder.toString(); - } + return builder.toString(); + } - private static void append(StringBuilder builder, String part) { - if (builder.length() != 0) builder.append(':'); - builder.append(part == null ? "" : part); - } + private static void append(StringBuilder builder, String part) { + if (builder.length() != 0) { + builder.append(':'); + } + builder.append(part == null ? "" : part); + } } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java index 7a20483..2658a4c 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java @@ -52,125 +52,142 @@ */ @ExtensionImpl public class MavenDependenciesGradleCompletionContributor extends AbstractGradleCompletionContributor { - private static final String GROUP_LABEL = "group"; - private static final String NAME_LABEL = "name"; - private static final String VERSION_LABEL = "version"; - private static final String DEPENDENCIES_SCRIPT_BLOCK = "dependencies"; - - private static final ElementPattern DEPENDENCIES_CALL_PATTERN = psiElement() - .inside(true, psiElement(GrMethodCallExpression.class).with(new PatternCondition("withInvokedExpressionText") { - @Override - public boolean accepts(@Nonnull GrMethodCallExpression expression, ProcessingContext context) { - if (checkExpression(expression)) return true; - return checkExpression(PsiTreeUtil.getParentOfType(expression, GrMethodCallExpression.class)); - } - - private boolean checkExpression(@Nullable GrMethodCallExpression expression) { - if (expression == null) return false; - GrExpression grExpression = expression.getInvokedExpression(); - return grExpression != null && DEPENDENCIES_SCRIPT_BLOCK.equals(grExpression.getText()); - } - })); - - private static final ElementPattern IN_MAP_DEPENDENCY_NOTATION = psiElement() - .and(AbstractGradleCompletionContributor.GRADLE_FILE_PATTERN) - .withParent(GrLiteral.class) - .withSuperParent(2, psiElement(GrNamedArgument.class)) - .and(DEPENDENCIES_CALL_PATTERN); - - private static final ElementPattern IN_METHOD_DEPENDENCY_NOTATION = psiElement() - .and(AbstractGradleCompletionContributor.GRADLE_FILE_PATTERN) - .and(DEPENDENCIES_CALL_PATTERN); - - public MavenDependenciesGradleCompletionContributor() { - // map-style notation: - // e.g.: - // compile group: 'com.google.code.guice', name: 'guice', version: '1.0' - // runtime([group:'junit', name:'junit-dep', version:'4.7']) - // compile(group:'junit', name:'junit-dep', version:'4.7') - extend(CompletionType.BASIC, IN_MAP_DEPENDENCY_NOTATION, new CompletionProvider() { - @Override - public void addCompletions(@Nonnull CompletionParameters params, - ProcessingContext context, - @Nonnull final CompletionResultSet result) { - result.stopHere(); - - final PsiElement parent = params.getPosition().getParent().getParent(); - if (!(parent instanceof GrNamedArgument) || !(parent.getParent() instanceof GrNamedArgumentsOwner)) { - return; - } - - final GrNamedArgument namedArgument = (GrNamedArgument)parent; - if (GROUP_LABEL.equals(namedArgument.getLabelName())) { - MavenProjectIndicesManager m = MavenProjectIndicesManager.getInstance(namedArgument.getProject()); - for (String groupId : m.getGroupIds()) { - LookupElement builder = LookupElementBuilder.create(groupId).withIcon(AllIcons.Nodes.PpLib); - result.addElement(builder); - } - } - else if (NAME_LABEL.equals(namedArgument.getLabelName())) { - String groupId = findNamedArgumentValue((GrNamedArgumentsOwner)namedArgument.getParent(), GROUP_LABEL); - if (groupId == null) return; - - MavenProjectIndicesManager m = MavenProjectIndicesManager.getInstance(namedArgument.getProject()); - for (String artifactId : m.getArtifactIds(groupId)) { - LookupElement builder = LookupElementBuilder.create(artifactId).withIcon(AllIcons.Nodes.PpLib); - result.addElement(builder); - } - } - else if (VERSION_LABEL.equals(namedArgument.getLabelName())) { - GrNamedArgumentsOwner namedArgumentsOwner = (GrNamedArgumentsOwner)namedArgument.getParent(); - - String groupId = findNamedArgumentValue(namedArgumentsOwner, GROUP_LABEL); - if (groupId == null) return; - - String artifactId = findNamedArgumentValue(namedArgumentsOwner, NAME_LABEL); - if (artifactId == null) return; - - MavenProjectIndicesManager m = MavenProjectIndicesManager.getInstance(namedArgument.getProject()); - for (String version : m.getVersions(groupId, artifactId)) { - LookupElement builder = LookupElementBuilder.create(version).withIcon(AllIcons.Nodes.PpLib); - result.addElement(builder); - } - } - } - }); - - // group:name:version notation - // e.g.: - // compile 'junit:junit:4.11' - // compile('junit:junit:4.11') - extend(CompletionType.BASIC, IN_METHOD_DEPENDENCY_NOTATION, new CompletionProvider() { - @Override - public void addCompletions(@Nonnull CompletionParameters params, - ProcessingContext context, - @Nonnull final CompletionResultSet result) { - result.stopHere(); - - final PsiElement parent = params.getPosition().getParent(); - if (!(parent instanceof GrLiteral) || !(parent.getParent() instanceof GrArgumentList)) return; - - String searchText = CompletionUtilCore.findReferenceOrAlphanumericPrefix(params); - MavenArtifactSearcher searcher = new MavenArtifactSearcher(); - List searchResults = searcher.search(params.getPosition().getProject(), searchText, 100); - for (MavenArtifactSearchResult searchResult : searchResults) { - for (MavenArtifactInfo artifactInfo : searchResult.versions) { - final StringBuilder buf = new StringBuilder(); - MavenId.append(buf, artifactInfo.getGroupId()); - MavenId.append(buf, artifactInfo.getArtifactId()); - MavenId.append(buf, artifactInfo.getVersion()); - - LookupElement builder = LookupElementBuilder.create(buf.toString()).withIcon(AllIcons.Nodes.PpLib); - result.addElement(builder); - } - } - } - }); - } - - @Nonnull - @Override - public Language getLanguage() { - return GroovyLanguage.INSTANCE; - } + private static final String GROUP_LABEL = "group"; + private static final String NAME_LABEL = "name"; + private static final String VERSION_LABEL = "version"; + private static final String DEPENDENCIES_SCRIPT_BLOCK = "dependencies"; + + private static final ElementPattern DEPENDENCIES_CALL_PATTERN = psiElement() + .inside( + true, + psiElement(GrMethodCallExpression.class).with(new PatternCondition<>("withInvokedExpressionText") { + @Override + public boolean accepts(@Nonnull GrMethodCallExpression expression, ProcessingContext context) { + if (checkExpression(expression)) { + return true; + } + return checkExpression(PsiTreeUtil.getParentOfType(expression, GrMethodCallExpression.class)); + } + + private boolean checkExpression(@Nullable GrMethodCallExpression expression) { + if (expression == null) { + return false; + } + GrExpression grExpression = expression.getInvokedExpression(); + return grExpression != null && DEPENDENCIES_SCRIPT_BLOCK.equals(grExpression.getText()); + } + }) + ); + + private static final ElementPattern IN_MAP_DEPENDENCY_NOTATION = psiElement() + .and(AbstractGradleCompletionContributor.GRADLE_FILE_PATTERN) + .withParent(GrLiteral.class) + .withSuperParent(2, psiElement(GrNamedArgument.class)) + .and(DEPENDENCIES_CALL_PATTERN); + + private static final ElementPattern IN_METHOD_DEPENDENCY_NOTATION = psiElement() + .and(AbstractGradleCompletionContributor.GRADLE_FILE_PATTERN) + .and(DEPENDENCIES_CALL_PATTERN); + + public MavenDependenciesGradleCompletionContributor() { + // map-style notation: + // e.g.: + // compile group: 'com.google.code.guice', name: 'guice', version: '1.0' + // runtime([group:'junit', name:'junit-dep', version:'4.7']) + // compile(group:'junit', name:'junit-dep', version:'4.7') + extend(CompletionType.BASIC, IN_MAP_DEPENDENCY_NOTATION, new CompletionProvider() { + @Override + public void addCompletions( + @Nonnull CompletionParameters params, + ProcessingContext context, + @Nonnull final CompletionResultSet result + ) { + result.stopHere(); + + final PsiElement parent = params.getPosition().getParent().getParent(); + if (!(parent instanceof GrNamedArgument) || !(parent.getParent() instanceof GrNamedArgumentsOwner)) { + return; + } + + final GrNamedArgument namedArgument = (GrNamedArgument)parent; + if (GROUP_LABEL.equals(namedArgument.getLabelName())) { + MavenProjectIndicesManager m = MavenProjectIndicesManager.getInstance(namedArgument.getProject()); + for (String groupId : m.getGroupIds()) { + LookupElement builder = LookupElementBuilder.create(groupId).withIcon(AllIcons.Nodes.PpLib); + result.addElement(builder); + } + } + else if (NAME_LABEL.equals(namedArgument.getLabelName())) { + String groupId = findNamedArgumentValue((GrNamedArgumentsOwner)namedArgument.getParent(), GROUP_LABEL); + if (groupId == null) { + return; + } + + MavenProjectIndicesManager m = MavenProjectIndicesManager.getInstance(namedArgument.getProject()); + for (String artifactId : m.getArtifactIds(groupId)) { + LookupElement builder = LookupElementBuilder.create(artifactId).withIcon(AllIcons.Nodes.PpLib); + result.addElement(builder); + } + } + else if (VERSION_LABEL.equals(namedArgument.getLabelName())) { + GrNamedArgumentsOwner namedArgumentsOwner = (GrNamedArgumentsOwner)namedArgument.getParent(); + + String groupId = findNamedArgumentValue(namedArgumentsOwner, GROUP_LABEL); + if (groupId == null) { + return; + } + + String artifactId = findNamedArgumentValue(namedArgumentsOwner, NAME_LABEL); + if (artifactId == null) { + return; + } + + MavenProjectIndicesManager m = MavenProjectIndicesManager.getInstance(namedArgument.getProject()); + for (String version : m.getVersions(groupId, artifactId)) { + LookupElement builder = LookupElementBuilder.create(version).withIcon(AllIcons.Nodes.PpLib); + result.addElement(builder); + } + } + } + }); + + // group:name:version notation + // e.g.: + // compile 'junit:junit:4.11' + // compile('junit:junit:4.11') + extend( + CompletionType.BASIC, + IN_METHOD_DEPENDENCY_NOTATION, + (params, context, result) -> { + result.stopHere(); + + final PsiElement parent = params.getPosition().getParent(); + if (!(parent instanceof GrLiteral) || !(parent.getParent() instanceof GrArgumentList)) { + return; + } + + String searchText = CompletionUtilCore.findReferenceOrAlphanumericPrefix(params); + MavenArtifactSearcher searcher = new MavenArtifactSearcher(); + List searchResults = + searcher.search(params.getPosition().getProject(), searchText, 100); + for (MavenArtifactSearchResult searchResult : searchResults) { + for (MavenArtifactInfo artifactInfo : searchResult.versions) { + final StringBuilder buf = new StringBuilder(); + MavenId.append(buf, artifactInfo.getGroupId()); + MavenId.append(buf, artifactInfo.getArtifactId()); + MavenId.append(buf, artifactInfo.getVersion()); + + LookupElement builder = LookupElementBuilder.create(buf.toString()).withIcon(AllIcons.Nodes.PpLib); + result.addElement(builder); + } + } + } + ); + } + + @Nonnull + @Override + public Language getLanguage() { + return GroovyLanguage.INSTANCE; + } } diff --git a/plugin/src/main/java/consulo/gradle/impl/importProvider/GradleModuleImportProvider.java b/plugin/src/main/java/consulo/gradle/impl/importProvider/GradleModuleImportProvider.java index a18b227..74fdee5 100644 --- a/plugin/src/main/java/consulo/gradle/impl/importProvider/GradleModuleImportProvider.java +++ b/plugin/src/main/java/consulo/gradle/impl/importProvider/GradleModuleImportProvider.java @@ -33,97 +33,97 @@ */ @ExtensionImpl public class GradleModuleImportProvider extends AbstractExternalModuleImportProvider { - @Nonnull - public static GradleModuleImportProvider getInstance() { - return EP_NAME.findExtensionOrFail(GradleModuleImportProvider.class); - } - - @Inject - public GradleModuleImportProvider(@Nonnull ProjectDataManager dataManager) { - super(dataManager, new ImportFromGradleControl(), GradleConstants.SYSTEM_ID); - } - - @Nonnull - @Override - public String getName() { - return GradleBundle.message("gradle.name"); - } + @Nonnull + public static GradleModuleImportProvider getInstance() { + return EP_NAME.findExtensionOrFail(GradleModuleImportProvider.class); + } - @Nullable - @Override - public Image getIcon() { - return GradleIconGroup.gradle(); - } + @Inject + public GradleModuleImportProvider(@Nonnull ProjectDataManager dataManager) { + super(dataManager, new ImportFromGradleControl(), GradleConstants.SYSTEM_ID); + } - @Override - public boolean canImport(@Nonnull File fileOrDirectory) { - if (fileOrDirectory.isDirectory()) { - return new File(fileOrDirectory, GradleConstants.DEFAULT_SCRIPT_NAME).exists(); + @Nonnull + @Override + public String getName() { + return GradleBundle.message("gradle.name"); } - else { - String extension = FileUtil.getExtension(fileOrDirectory.getName()); - return GradleConstants.EXTENSION.equalsIgnoreCase(extension); + + @Nullable + @Override + public Image getIcon() { + return GradleIconGroup.gradle(); } - } - @Nonnull - @Override - public String getFileSample() { - return "Gradle build script (*.gradle)"; - } + @Override + public boolean canImport(@Nonnull File fileOrDirectory) { + if (fileOrDirectory.isDirectory()) { + return new File(fileOrDirectory, GradleConstants.DEFAULT_SCRIPT_NAME).exists(); + } + else { + String extension = FileUtil.getExtension(fileOrDirectory.getName()); + return GradleConstants.EXTENSION.equalsIgnoreCase(extension); + } + } - @Override - protected void doPrepare(@Nonnull ExternalModuleImportContext context) { - String importFile = context.getFileToImport(); - VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(importFile); - if (file != null && !file.isDirectory()) { - //getControl().setLinkedProjectPath(file.getParent().getPath()); + @Nonnull + @Override + public String getFileSample() { + return "Gradle build script (*.gradle)"; } - } - @Override - protected void beforeCommit(@Nonnull DataNode dataNode, @Nonnull Project project) { + @Override + protected void doPrepare(@Nonnull ExternalModuleImportContext context) { + String importFile = context.getFileToImport(); + VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(importFile); + if (file != null && !file.isDirectory()) { + //getControl().setLinkedProjectPath(file.getParent().getPath()); + } + } - } + @Override + protected void beforeCommit(@Nonnull DataNode dataNode, @Nonnull Project project) { - @Nonnull - @Override - protected File getExternalProjectConfigToUse(@Nonnull File file) { - return file.isDirectory() ? file : file.getParentFile(); - } + } - @Override - protected void applyExtraSettings(@Nonnull ExternalModuleImportContext context) { - DataNode node = getExternalProjectNode(); - if (node == null) { - return; + @Nonnull + @Override + protected File getExternalProjectConfigToUse(@Nonnull File file) { + return file.isDirectory() ? file : file.getParentFile(); } - DataNode javaProjectNode = ExternalSystemApiUtil.find(node, JavaProjectData.KEY); - if (javaProjectNode != null) { - JavaProjectData data = javaProjectNode.getData(); - // todo context.setCompilerOutputDirectory(data.getCompileOutputPath()); - JavaSdkVersion version = data.getJdkVersion(); - Sdk jdk = findJdk(version); - if (jdk != null) { - //context.setProjectJdk(jdk); - } + @Override + protected void applyExtraSettings(@Nonnull ExternalModuleImportContext context) { + DataNode node = getExternalProjectNode(); + if (node == null) { + return; + } + + DataNode javaProjectNode = ExternalSystemApiUtil.find(node, JavaProjectData.KEY); + if (javaProjectNode != null) { + JavaProjectData data = javaProjectNode.getData(); + // todo context.setCompilerOutputDirectory(data.getCompileOutputPath()); + JavaSdkVersion version = data.getJdkVersion(); + Sdk jdk = findJdk(version); + if (jdk != null) { + //context.setProjectJdk(jdk); + } + } } - } - @Nullable - private static Sdk findJdk(@Nonnull JavaSdkVersion version) { - List javaSdks = JavaSdkTypeUtil.getAllJavaSdks(); - Sdk candidate = null; - for (Sdk sdk : javaSdks) { - JavaSdkVersion v = JavaSdkTypeUtil.getVersion(sdk); - if (v == version) { - return sdk; - } - else if (candidate == null && v != null && version.getMaxLanguageLevel().isAtLeast(version.getMaxLanguageLevel())) { - candidate = sdk; - } + @Nullable + private static Sdk findJdk(@Nonnull JavaSdkVersion version) { + List javaSdks = JavaSdkTypeUtil.getAllJavaSdks(); + Sdk candidate = null; + for (Sdk sdk : javaSdks) { + JavaSdkVersion v = JavaSdkTypeUtil.getVersion(sdk); + if (v == version) { + return sdk; + } + else if (candidate == null && v != null && version.getMaxLanguageLevel().isAtLeast(version.getMaxLanguageLevel())) { + candidate = sdk; + } + } + return candidate; } - return candidate; - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java index 6b2643e..6b7399f 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java @@ -15,53 +15,53 @@ * Common super class for gradle actions that require {@link GradleSettings#getLinkedExternalProjectPath()} linked project}. *

* Not thread-safe. - * + * * @author Denis Zhdanov * @since 1/31/12 5:36 PM */ public abstract class AbstractGradleLinkedProjectAction extends AnAction { - - @Override - public void update(AnActionEvent e) { - final Pair pair = deriveProjects(e.getDataContext()); - final boolean visible = pair != null; - e.getPresentation().setVisible(visible); - if (!visible) { - return; + @Override + public void update(AnActionEvent e) { + final Pair pair = deriveProjects(e.getDataContext()); + final boolean visible = pair != null; + e.getPresentation().setVisible(visible); + if (!visible) { + return; + } + doUpdate(e, pair.first, pair.second); } - doUpdate(e, pair.first, pair.second); - } - @Override - public void actionPerformed(AnActionEvent e) { - final Project project = e.getData(Project.KEY); - if (project == null) { - return; - } - final Pair pair = deriveProjects(e.getDataContext()); - if (pair == null) { - e.getPresentation().setVisible(false); - return; + @Override + public void actionPerformed(AnActionEvent e) { + final Project project = e.getData(Project.KEY); + if (project == null) { + return; + } + final Pair pair = deriveProjects(e.getDataContext()); + if (pair == null) { + e.getPresentation().setVisible(false); + return; + } + doActionPerformed(e, project, pair.second); } - doActionPerformed(e, project, pair.second); - } - @Nullable - private static Pair deriveProjects(@Nullable DataContext context) { - if (context == null) { - return null; - } - - final Project project = context.getData(CommonDataKeys.PROJECT); - if (project == null) { - return null; - } - // TODO den implement - return null; + @Nullable + private static Pair deriveProjects(@Nullable DataContext context) { + if (context == null) { + return null; + } + + final Project project = context.getData(CommonDataKeys.PROJECT); + if (project == null) { + return null; + } + // TODO den implement + return null; // final String path = GradleSettings.getInstance(project).getLinkedExternalProjectPath(); // return path == null ? null : new Pair(project, path); - } + } + + protected abstract void doUpdate(@Nonnull AnActionEvent event, @Nonnull Project project, @Nonnull String linkedProjectPath); - protected abstract void doUpdate(@Nonnull AnActionEvent event, @Nonnull Project project, @Nonnull String linkedProjectPath); - protected abstract void doActionPerformed(@Nonnull AnActionEvent event, @Nonnull Project project, @Nonnull String linkedProjectPath); + protected abstract void doActionPerformed(@Nonnull AnActionEvent event, @Nonnull Project project, @Nonnull String linkedProjectPath); } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java index 318dd26..2808646 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java @@ -23,26 +23,25 @@ * @since 1/31/12 5:16 PM */ public class GradleOpenScriptAction extends AbstractGradleLinkedProjectAction implements DumbAware { + private static final Logger LOG = Logger.getInstance(GradleOpenScriptAction.class); - private static final Logger LOG = Logger.getInstance(GradleOpenScriptAction.class); - - public GradleOpenScriptAction() { - getTemplatePresentation().setText(GradleBundle.message("gradle.action.open.script.text")); - getTemplatePresentation().setDescription(GradleBundle.message("gradle.action.open.script.description")); - } + public GradleOpenScriptAction() { + getTemplatePresentation().setText(GradleBundle.message("gradle.action.open.script.text")); + getTemplatePresentation().setDescription(GradleBundle.message("gradle.action.open.script.description")); + } - @Override - protected void doUpdate(@Nonnull AnActionEvent event, @Nonnull Project project, @Nonnull String linkedProjectPath) { - } + @Override + protected void doUpdate(@Nonnull AnActionEvent event, @Nonnull Project project, @Nonnull String linkedProjectPath) { + } - @Override - protected void doActionPerformed(@Nonnull AnActionEvent event, @Nonnull Project project, @Nonnull String linkedProjectPath) { - final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(linkedProjectPath); - if (virtualFile == null) { - LOG.warn(String.format("Can't obtain virtual file for the target file path: '%s'", linkedProjectPath)); - return; + @Override + protected void doActionPerformed(@Nonnull AnActionEvent event, @Nonnull Project project, @Nonnull String linkedProjectPath) { + final VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(linkedProjectPath); + if (virtualFile == null) { + LOG.warn(String.format("Can't obtain virtual file for the target file path: '%s'", linkedProjectPath)); + return; + } + OpenFileDescriptor descriptor = OpenFileDescriptorFactory.getInstance(project).builder(virtualFile).build(); + FileEditorManager.getInstance(project).openTextEditor(descriptor, true); } - OpenFileDescriptor descriptor = OpenFileDescriptorFactory.getInstance(project).builder(virtualFile).build(); - FileEditorManager.getInstance(project).openTextEditor(descriptor, true); - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java index 9d7685f..1375f0e 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java @@ -11,26 +11,25 @@ * @since 3/17/12 2:34 PM */ public class GradleToolWindowHelpAction extends ContextHelpAction { + @Override + public void update(AnActionEvent event) { + final Project project = event.getData(Project.KEY); + if (project == null) { + event.getPresentation().setVisible(false); + return; + } - @Override - public void update(AnActionEvent event) { - final Project project = event.getData(Project.KEY); - if (project == null) { - event.getPresentation().setVisible(false); - return; - } - - // TODO den implement + // TODO den implement // if (StringUtil.isEmpty(GradleSettings.getInstance(project).getLinkedExternalProjectPath())) { // event.getPresentation().setVisible(false); // return; // } - event.getPresentation().setVisible(true); - super.update(event); - } + event.getPresentation().setVisible(true); + super.update(event); + } - @Override - protected String getHelpId(DataContext dataContext) { - return GradleConstants.HELP_TOPIC_TOOL_WINDOW; - } + @Override + protected String getHelpId(DataContext dataContext) { + return GradleConstants.HELP_TOPIC_TOOL_WINDOW; + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java index 825c4b9..c1ef086 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java @@ -69,154 +69,163 @@ */ @ExtensionImpl public class UseDistributionWithSourcesNotificationProvider implements EditorNotificationProvider { - public static final Pattern GRADLE_SRC_DISTRIBUTION_PATTERN; - private static final Logger LOG = Logger.getInstance(UseDistributionWithSourcesNotificationProvider.class); - private static final String ALL_ZIP_DISTRIBUTION_URI_SUFFIX = "-all.zip"; - private final Project myProject; - - static { - GRADLE_SRC_DISTRIBUTION_PATTERN = Pattern.compile("https?\\\\?://services\\.gradle\\.org.*" + ALL_ZIP_DISTRIBUTION_URI_SUFFIX); - } - - @Inject - public UseDistributionWithSourcesNotificationProvider(Project project) { - myProject = project; - } - - @Nonnull - @Override - public String getId() { - return "gradle-use-distribution-with-source"; - } - - @RequiredReadAction - @Nullable - @Override - public EditorNotificationBuilder buildNotification(@Nonnull VirtualFile file, - @Nonnull FileEditor fileEditor, - @Nonnull Supplier supplier) { - try { - if (GradleConstants.DEFAULT_SCRIPT_NAME.equals(file.getName()) || GradleConstants.SETTINGS_FILE_NAME.equals(file.getName())) { - - final Module module = ModuleUtilCore.findModuleForFile(file, myProject); - if (module == null) { - return null; - } - final String rootProjectPath = getRootProjectPath(module); - if (rootProjectPath == null) { - return null; - } - final GradleProjectSettings settings = GradleSettings.getInstance(module.getProject()).getLinkedProjectSettings(rootProjectPath); - if (settings == null || settings.getDistributionType() != DistributionType.DEFAULT_WRAPPED) { - return null; - } - if (settings.isDisableWrapperSourceDistributionNotification()) { - return null; - } - if (!showUseDistributionWithSourcesTip(rootProjectPath)) { - return null; - } + public static final Pattern GRADLE_SRC_DISTRIBUTION_PATTERN; + private static final Logger LOG = Logger.getInstance(UseDistributionWithSourcesNotificationProvider.class); + private static final String ALL_ZIP_DISTRIBUTION_URI_SUFFIX = "-all.zip"; + private final Project myProject; - final EditorNotificationBuilder panel = supplier.get(); - panel.withText(GradleLocalize.gradleNotificationsUseDistributionWithSources()); - panel.withAction(GradleLocalize.gradleNotificationsHideTip(), (e) -> - { - settings.setDisableWrapperSourceDistributionNotification(true); - EditorNotifications.getInstance(module.getProject()).updateAllNotifications(); - }); - panel.withAction(GradleLocalize.gradleNotificationsApplySuggestion(), (e) -> - { - updateDefaultWrapperConfiguration(rootProjectPath); - EditorNotifications.getInstance(module.getProject()).updateAllNotifications(); - final ProjectDataManager projectDataManager = ServiceManager.getService(ProjectDataManager.class); - ExternalSystemUtil.refreshProject(module.getProject(), GradleConstants.SYSTEM_ID, settings.getExternalProjectPath(), new - ExternalProjectRefreshCallback() { - @Override - public void onSuccess(@Nullable final DataNode externalProject) { - if (externalProject == null) { - return; - } - ExternalSystemApiUtil.executeProjectChangeAction(true, new DisposeAwareProjectChange(module.getProject()) { - @RequiredUIAccess - @Override - public void execute() { - ProjectRootManager.getInstance(module.getProject()).mergeRootsChangesDuring(() -> projectDataManager - .importData(externalProject.getKey(), Collections.singleton(externalProject), module.getProject(), true)); - } - }); - } - - @Override - public void onFailure(@Nonnull String errorMessage, @Nullable String errorDetails) { - } - }, true, ProgressExecutionMode.START_IN_FOREGROUND_ASYNC); - }); - return panel; - } - } - catch (ProcessCanceledException | IndexNotReadyException ignored) { + static { + GRADLE_SRC_DISTRIBUTION_PATTERN = Pattern.compile("https?\\\\?://services\\.gradle\\.org.*" + ALL_ZIP_DISTRIBUTION_URI_SUFFIX); } - return null; - } - - private static void updateDefaultWrapperConfiguration(@Nonnull String linkedProjectPath) { - try { - final File wrapperPropertiesFile = GradleUtil.findDefaultWrapperPropertiesFile(linkedProjectPath); - if (wrapperPropertiesFile == null) { - return; - } - final WrapperConfiguration wrapperConfiguration = GradleUtil.getWrapperConfiguration(linkedProjectPath); - if (wrapperConfiguration == null) { - return; - } - String currentDistributionUri = wrapperConfiguration.getDistribution().toString(); - if (StringUtil.endsWith(currentDistributionUri, ALL_ZIP_DISTRIBUTION_URI_SUFFIX)) { - return; - } - - final String distributionUri = currentDistributionUri.substring(0, currentDistributionUri.lastIndexOf('-')) + - ALL_ZIP_DISTRIBUTION_URI_SUFFIX; - - wrapperConfiguration.setDistribution(new URI(distributionUri)); - Properties wrapperProperties = new Properties(); - wrapperProperties.setProperty(WrapperExecutor.DISTRIBUTION_URL_PROPERTY, wrapperConfiguration.getDistribution().toString()); - wrapperProperties.setProperty(WrapperExecutor.DISTRIBUTION_BASE_PROPERTY, wrapperConfiguration.getDistributionBase()); - wrapperProperties.setProperty(WrapperExecutor.DISTRIBUTION_PATH_PROPERTY, wrapperConfiguration.getDistributionPath()); - wrapperProperties.setProperty(WrapperExecutor.ZIP_STORE_BASE_PROPERTY, wrapperConfiguration.getZipBase()); - wrapperProperties.setProperty(WrapperExecutor.ZIP_STORE_PATH_PROPERTY, wrapperConfiguration.getZipPath()); - GUtil.saveProperties(wrapperProperties, new File(wrapperPropertiesFile.getPath())); - LocalFileSystem.getInstance().refreshIoFiles(Collections.singletonList(wrapperPropertiesFile)); + @Inject + public UseDistributionWithSourcesNotificationProvider(Project project) { + myProject = project; } - catch (Exception e) { - LOG.error(e); - } - } - private static boolean showUseDistributionWithSourcesTip(String linkedProjectPath) { - WrapperConfiguration wrapperConfiguration = GradleUtil.getWrapperConfiguration(linkedProjectPath); - // currently only wrapped distribution takes into account - if (wrapperConfiguration == null) { - return true; + @Nonnull + @Override + public String getId() { + return "gradle-use-distribution-with-source"; } - String distributionUri = wrapperConfiguration.getDistribution().toString(); - try { - String host = new URI(distributionUri).getHost(); - return host != null && host.endsWith("gradle.org") && !GRADLE_SRC_DISTRIBUTION_PATTERN.matcher(distributionUri).matches(); + + @RequiredReadAction + @Nullable + @Override + public EditorNotificationBuilder buildNotification( + @Nonnull VirtualFile file, + @Nonnull FileEditor fileEditor, + @Nonnull Supplier supplier + ) { + try { + if (GradleConstants.DEFAULT_SCRIPT_NAME.equals(file.getName()) || GradleConstants.SETTINGS_FILE_NAME.equals(file.getName())) { + + final Module module = ModuleUtilCore.findModuleForFile(file, myProject); + if (module == null) { + return null; + } + final String rootProjectPath = getRootProjectPath(module); + if (rootProjectPath == null) { + return null; + } + final GradleProjectSettings settings = + GradleSettings.getInstance(module.getProject()).getLinkedProjectSettings(rootProjectPath); + if (settings == null || settings.getDistributionType() != DistributionType.DEFAULT_WRAPPED) { + return null; + } + if (settings.isDisableWrapperSourceDistributionNotification()) { + return null; + } + if (!showUseDistributionWithSourcesTip(rootProjectPath)) { + return null; + } + + final EditorNotificationBuilder panel = supplier.get(); + panel.withText(GradleLocalize.gradleNotificationsUseDistributionWithSources()); + panel.withAction(GradleLocalize.gradleNotificationsHideTip(), (e) -> + { + settings.setDisableWrapperSourceDistributionNotification(true); + EditorNotifications.getInstance(module.getProject()).updateAllNotifications(); + }); + panel.withAction(GradleLocalize.gradleNotificationsApplySuggestion(), (e) -> + { + updateDefaultWrapperConfiguration(rootProjectPath); + EditorNotifications.getInstance(module.getProject()).updateAllNotifications(); + final ProjectDataManager projectDataManager = ServiceManager.getService(ProjectDataManager.class); + ExternalSystemUtil.refreshProject(module.getProject(), GradleConstants.SYSTEM_ID, settings.getExternalProjectPath(), new + ExternalProjectRefreshCallback() { + @Override + public void onSuccess(@Nullable final DataNode externalProject) { + if (externalProject == null) { + return; + } + ExternalSystemApiUtil.executeProjectChangeAction(true, new DisposeAwareProjectChange(module.getProject()) { + @RequiredUIAccess + @Override + public void execute() { + ProjectRootManager.getInstance(module.getProject()).mergeRootsChangesDuring( + () -> projectDataManager.importData( + externalProject.getKey(), + Collections.singleton(externalProject), + module.getProject(), + true + ) + ); + } + }); + } + + @Override + public void onFailure(@Nonnull String errorMessage, @Nullable String errorDetails) { + } + }, true, ProgressExecutionMode.START_IN_FOREGROUND_ASYNC); + }); + return panel; + } + } + catch (ProcessCanceledException | IndexNotReadyException ignored) { + } + + return null; } - catch (URISyntaxException ignore) { + + private static void updateDefaultWrapperConfiguration(@Nonnull String linkedProjectPath) { + try { + final File wrapperPropertiesFile = GradleUtil.findDefaultWrapperPropertiesFile(linkedProjectPath); + if (wrapperPropertiesFile == null) { + return; + } + final WrapperConfiguration wrapperConfiguration = GradleUtil.getWrapperConfiguration(linkedProjectPath); + if (wrapperConfiguration == null) { + return; + } + String currentDistributionUri = wrapperConfiguration.getDistribution().toString(); + if (StringUtil.endsWith(currentDistributionUri, ALL_ZIP_DISTRIBUTION_URI_SUFFIX)) { + return; + } + + final String distributionUri = currentDistributionUri.substring(0, currentDistributionUri.lastIndexOf('-')) + + ALL_ZIP_DISTRIBUTION_URI_SUFFIX; + + wrapperConfiguration.setDistribution(new URI(distributionUri)); + Properties wrapperProperties = new Properties(); + wrapperProperties.setProperty(WrapperExecutor.DISTRIBUTION_URL_PROPERTY, wrapperConfiguration.getDistribution().toString()); + wrapperProperties.setProperty(WrapperExecutor.DISTRIBUTION_BASE_PROPERTY, wrapperConfiguration.getDistributionBase()); + wrapperProperties.setProperty(WrapperExecutor.DISTRIBUTION_PATH_PROPERTY, wrapperConfiguration.getDistributionPath()); + wrapperProperties.setProperty(WrapperExecutor.ZIP_STORE_BASE_PROPERTY, wrapperConfiguration.getZipBase()); + wrapperProperties.setProperty(WrapperExecutor.ZIP_STORE_PATH_PROPERTY, wrapperConfiguration.getZipPath()); + GUtil.saveProperties(wrapperProperties, new File(wrapperPropertiesFile.getPath())); + LocalFileSystem.getInstance().refreshIoFiles(Collections.singletonList(wrapperPropertiesFile)); + } + catch (Exception e) { + LOG.error(e); + } } - return false; - } - - @Nullable - private static String getRootProjectPath(@Nonnull Module module) { - String externalSystemId = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY); - if (externalSystemId == null || !GradleConstants.SYSTEM_ID.toString().equals(externalSystemId)) { - return null; + + private static boolean showUseDistributionWithSourcesTip(String linkedProjectPath) { + WrapperConfiguration wrapperConfiguration = GradleUtil.getWrapperConfiguration(linkedProjectPath); + // currently only wrapped distribution takes into account + if (wrapperConfiguration == null) { + return true; + } + String distributionUri = wrapperConfiguration.getDistribution().toString(); + try { + String host = new URI(distributionUri).getHost(); + return host != null && host.endsWith("gradle.org") && !GRADLE_SRC_DISTRIBUTION_PATTERN.matcher(distributionUri).matches(); + } + catch (URISyntaxException ignore) { + } + return false; } - String path = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY); - return StringUtil.isEmpty(path) ? null : path; - } + @Nullable + private static String getRootProjectPath(@Nonnull Module module) { + String externalSystemId = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY); + if (externalSystemId == null || !GradleConstants.SYSTEM_ID.toString().equals(externalSystemId)) { + return null; + } + + String path = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY); + return StringUtil.isEmpty(path) ? null : path; + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java index 9557459..c8216cd 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java @@ -44,39 +44,40 @@ */ @ActionImpl(id = "AddGradleDslPluginAction", parents = @ActionParentRef(value = @ActionRef(id = "GenerateGroup"), anchor = ActionRefAnchor.FIRST)) public class AddGradleDslPluginAction extends CodeInsightAction { - private final Pair[] myPlugins; + private final Pair[] myPlugins; - public AddGradleDslPluginAction() { - getTemplatePresentation().setDescription(GradleBundle.message("gradle.codeInsight.action.apply_plugin.description")); - getTemplatePresentation().setText(GradleBundle.message("gradle.codeInsight.action.apply_plugin.text")); - getTemplatePresentation().setIcon(AllIcons.Nodes.Plugin); + public AddGradleDslPluginAction() { + getTemplatePresentation().setDescription(GradleBundle.message("gradle.codeInsight.action.apply_plugin.description")); + getTemplatePresentation().setText(GradleBundle.message("gradle.codeInsight.action.apply_plugin.text")); + getTemplatePresentation().setIcon(AllIcons.Nodes.Plugin); - final List plugins = StringUtil.split( - "java,groovy,idea,eclipse,scala,antlr,application,ear,jetty,maven,osgi,war,announce," + - "build-announcements,checkstyle,codenarc,eclipse-wtp,findbugs,jdepend,pmd,project-report,signing,sonar", ","); + final List plugins = StringUtil.split( + "java,groovy,idea,eclipse,scala,antlr,application,ear,jetty,maven,osgi,war,announce," + + "build-announcements,checkstyle,codenarc,eclipse-wtp,findbugs,jdepend,pmd,project-report,signing,sonar", ","); - myPlugins = new Pair[plugins.size()]; - ContainerUtil.map2Array(plugins, myPlugins, o -> createPluginKey(o)); - Arrays.sort(myPlugins, (o1, o2) -> String.valueOf(o1.getFirst()).compareTo(String.valueOf(o2.getFirst()))); - } + myPlugins = new Pair[plugins.size()]; + ContainerUtil.map2Array(plugins, myPlugins, o -> createPluginKey(o)); + Arrays.sort(myPlugins, (o1, o2) -> String.valueOf(o1.getFirst()).compareTo(String.valueOf(o2.getFirst()))); + } - @Nonnull - @Override - protected CodeInsightActionHandler getHandler() { - return new AddGradleDslPluginActionHandler(myPlugins); - } + @Nonnull + @Override + protected CodeInsightActionHandler getHandler() { + return new AddGradleDslPluginActionHandler(myPlugins); + } - @Override - protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file) { - if (file instanceof PsiCompiledElement) return false; - if (!GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType())) return false; - return !GradleConstants.SETTINGS_FILE_NAME.equals(file.getName()) && file.getName().endsWith(GradleConstants.EXTENSION); - } + @Override + protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file) { + if (file instanceof PsiCompiledElement || !GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType())) { + return false; + } + return !GradleConstants.SETTINGS_FILE_NAME.equals(file.getName()) && file.getName().endsWith(GradleConstants.EXTENSION); + } - @Nonnull - private static Pair createPluginKey(@Nonnull String pluginName) { - String description = GradleDocumentationBundle.messageOrDefault( - String.format("gradle.documentation.org.gradle.api.Project.apply.plugin.%s.non-html", pluginName), ""); - return Pair.create(pluginName, description); - } + @Nonnull + private static Pair createPluginKey(@Nonnull String pluginName) { + String description = GradleDocumentationBundle.messageOrDefault( + String.format("gradle.documentation.org.gradle.api.Project.apply.plugin.%s.non-html", pluginName), ""); + return Pair.create(pluginName, description); + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java index 153f995..1c386cc 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java @@ -51,70 +51,78 @@ * @since 10/24/13 */ class AddGradleDslPluginActionHandler implements CodeInsightActionHandler { - private final Pair[] myPlugins; + private final Pair[] myPlugins; - public AddGradleDslPluginActionHandler(Pair[] plugins) { - myPlugins = plugins; - } + public AddGradleDslPluginActionHandler(Pair[] plugins) { + myPlugins = plugins; + } - @Override - public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) { - if (!LanguageEditorUtil.checkModificationAllowed(editor)) return; + @Override + public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) { + if (!LanguageEditorUtil.checkModificationAllowed(editor)) { + return; + } - Consumer runnable = - selected -> new WriteCommandAction.Simple(project, GradleBundle.message("gradle.codeInsight.action.apply_plugin.text"), file) { - @Override - protected void run() { - if (selected == null) return; - GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); - GrStatement grStatement = factory.createStatementFromText( - String.format("apply plugin: '%s'", selected.getFirst()), null); + Consumer runnable = + selected -> new WriteCommandAction.Simple(project, GradleBundle.message("gradle.codeInsight.action.apply_plugin.text"), file) { + @Override + protected void run() { + if (selected == null) { + return; + } + GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); + GrStatement grStatement = factory.createStatementFromText( + String.format("apply plugin: '%s'", selected.getFirst()), + null + ); - PsiElement anchor = file.findElementAt(editor.getCaretModel().getOffset()); - PsiElement currentElement = PsiTreeUtil.getParentOfType(anchor, GrClosableBlock.class, GroovyFile.class); - if (currentElement != null) { - currentElement.addAfter(grStatement, anchor); - } - else { - file.addAfter(grStatement, file.findElementAt(editor.getCaretModel().getOffset() - 1)); - } - PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); - Document document = documentManager.getDocument(file); - if (document != null) { - documentManager.commitDocument(document); - } - } - }.execute(); + PsiElement anchor = file.findElementAt(editor.getCaretModel().getOffset()); + PsiElement currentElement = PsiTreeUtil.getParentOfType(anchor, GrClosableBlock.class, GroovyFile.class); + if (currentElement != null) { + currentElement.addAfter(grStatement, anchor); + } + else { + file.addAfter(grStatement, file.findElementAt(editor.getCaretModel().getOffset() - 1)); + } + PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); + Document document = documentManager.getDocument(file); + if (document != null) { + documentManager.commitDocument(document); + } + } + }.execute(); - JBPopup popup = JBPopupFactory.getInstance().createPopupChooserBuilder(List.of(myPlugins)) - .setTitle(GradleBundle.message("gradle.codeInsight.action.apply_plugin.popup.title")) - .setNamerForFiltering(pair -> String.valueOf(pair.getFirst())) - .setItemChosenCallback(runnable) - .setRenderer(new ColoredListCellRenderer>() { + JBPopup popup = JBPopupFactory.getInstance().createPopupChooserBuilder(List.of(myPlugins)) + .setTitle(GradleBundle.message("gradle.codeInsight.action.apply_plugin.popup.title")) + .setNamerForFiltering(pair -> String.valueOf(pair.getFirst())) + .setItemChosenCallback(runnable) + .setRenderer(new ColoredListCellRenderer>() { - @Override - protected void customizeCellRenderer(@Nonnull JList> list, - Pair descriptor, - int index, - boolean selected, - boolean hasFocus) { - EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); - Font font = scheme.getFont(EditorFontType.PLAIN); - setFont(font); + @Override + protected void customizeCellRenderer( + @Nonnull JList> list, + Pair descriptor, + int index, + boolean selected, + boolean hasFocus + ) { + EditorColorsScheme scheme = EditorColorsManager.getInstance().getGlobalScheme(); + Font font = scheme.getFont(EditorFontType.PLAIN); + setFont(font); - append(String.valueOf(descriptor.getFirst())); + append(String.valueOf(descriptor.getFirst())); - String description = String.valueOf(descriptor.getSecond()); - append(description, SimpleTextAttributes.GRAY_ATTRIBUTES); - } - }) - .createPopup(); + String description = String.valueOf(descriptor.getSecond()); + append(description, SimpleTextAttributes.GRAY_ATTRIBUTES); + } + }) + .createPopup(); - EditorPopupHelper.getInstance().showPopupInBestPositionFor(editor, popup); - } + EditorPopupHelper.getInstance().showPopupInBestPositionFor(editor, popup); + } - @Override - public boolean startInWriteAction() { - return false; - } + @Override + public boolean startInWriteAction() { + return false; + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java index 2f9b38b..69a6706 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java @@ -24,9 +24,9 @@ * @since 11/21/13 */ public abstract class GradleBaseInspection extends BaseInspection { - @Nonnull - @Override - public String[] getGroupPath() { - return new String[]{"Gradle", getGroupDisplayName()}; - } + @Nonnull + @Override + public String[] getGroupPath() { + return new String[]{"Gradle", getGroupDisplayName()}; + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java index 7cc9521..6eef93a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java @@ -22,24 +22,20 @@ * @author Vladislav.Soroka * @since 9/13/13 */ -public class GradleInspectionBundle extends AbstractBundle -{ - private static final String BUNDLE = "org.jetbrains.plugins.gradle.codeInspection.GradleInspectionBundle"; +public class GradleInspectionBundle extends AbstractBundle { + private static final String BUNDLE = "org.jetbrains.plugins.gradle.codeInspection.GradleInspectionBundle"; - private static final GradleInspectionBundle ourInstance = new GradleInspectionBundle(); + private static final GradleInspectionBundle ourInstance = new GradleInspectionBundle(); - private GradleInspectionBundle() - { - super(BUNDLE); - } + private GradleInspectionBundle() { + super(BUNDLE); + } - public static String message(@PropertyKey(resourceBundle = BUNDLE) String key) - { - return ourInstance.getMessage(key); - } + public static String message(@PropertyKey(resourceBundle = BUNDLE) String key) { + return ourInstance.getMessage(key); + } - public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) - { - return ourInstance.getMessage(key, params); - } + public static String message(@PropertyKey(resourceBundle = BUNDLE) String key, Object... params) { + return ourInstance.getMessage(key, params); + } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java index 3ed7129..c2e0c8c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java @@ -35,41 +35,48 @@ * @since 11/21/13 */ public class MultipleRepositoryUrlsFix extends GroovyFix { - private final GrClosableBlock myClosure; - private final String myRepoType; + private final GrClosableBlock myClosure; + private final String myRepoType; - public MultipleRepositoryUrlsFix(@Nonnull GrClosableBlock closure, @Nonnull String repoType) { - myClosure = closure; - myRepoType = repoType; - } + public MultipleRepositoryUrlsFix(@Nonnull GrClosableBlock closure, @Nonnull String repoType) { + myClosure = closure; + myRepoType = repoType; + } - @Override - protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { - List statements = MultipleRepositoryUrlsInspection.findUrlCallExpressions(myClosure); - if (statements.size() <= 1) return; - statements.remove(0); + @Override + protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { + List statements = MultipleRepositoryUrlsInspection.findUrlCallExpressions(myClosure); + if (statements.size() <= 1) { + return; + } + statements.remove(0); - List elements = new ArrayList(statements); - for (GrCallExpression statement : statements) { - PsiElement newLineCandidate = statement.getNextSibling(); - if (PsiUtil.isNewLine(newLineCandidate)) { - elements.add(newLineCandidate); - } - } + List elements = new ArrayList<>(statements); + for (GrCallExpression statement : statements) { + PsiElement newLineCandidate = statement.getNextSibling(); + if (PsiUtil.isNewLine(newLineCandidate)) { + elements.add(newLineCandidate); + } + } - myClosure.removeElements(elements.toArray(new PsiElement[elements.size()])); - GrClosableBlock closableBlock = PsiTreeUtil.getParentOfType(myClosure, GrClosableBlock.class); - if (closableBlock == null) return; + myClosure.removeElements(elements.toArray(new PsiElement[elements.size()])); + GrClosableBlock closableBlock = PsiTreeUtil.getParentOfType(myClosure, GrClosableBlock.class); + if (closableBlock == null) { + return; + } - GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(project); - for (GrCallExpression statement : statements) { - closableBlock.addStatementBefore(elementFactory.createStatementFromText(myRepoType + '{' + statement.getText() + '}'), null); + GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(project); + for (GrCallExpression statement : statements) { + closableBlock.addStatementBefore( + elementFactory.createStatementFromText(myRepoType + '{' + statement.getText() + '}'), + null + ); + } } - } - @Nonnull - @Override - public String getName() { - return GradleInspectionBundle.message("multiple.repository.urls.fix.name"); - } + @Nonnull + @Override + public String getName() { + return GradleInspectionBundle.message("multiple.repository.urls.fix.name"); + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java index 31788ad..4c85b66 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java @@ -42,85 +42,97 @@ */ @ExtensionImpl public class MultipleRepositoryUrlsInspection extends GradleBaseInspection { + @Nonnull + @Override + protected BaseInspectionVisitor buildVisitor() { + return new MyVisitor(); + } - @Nonnull - @Override - protected BaseInspectionVisitor buildVisitor() { - return new MyVisitor(); - } - - @Nls - @Nonnull - @Override - public String getGroupDisplayName() { - return PROBABLE_BUGS; - } - - @Nonnull - @Override - public String[] getGroupPath() { - return new String[] {"Gradle"}; - } + @Nls + @Nonnull + @Override + public String getGroupDisplayName() { + return PROBABLE_BUGS; + } - @Override - protected String buildErrorString(Object... args) { - return GradleInspectionBundle.message("multiple.repository.urls", args); - } + @Nonnull + @Override + public String[] getGroupPath() { + return new String[]{"Gradle"}; + } - @Nls - @Nonnull - @Override - public String getDisplayName() { - return GradleInspectionBundle.message("multiple.repository.urls"); - } + @Override + protected String buildErrorString(Object... args) { + return GradleInspectionBundle.message("multiple.repository.urls", args); + } - private static class MyVisitor extends BaseInspectionVisitor { + @Nls + @Nonnull @Override - public void visitClosure(GrClosableBlock closure) { - PsiFile file = closure.getContainingFile(); - if (file == null || !FileUtil.extensionEquals(file.getName(), GradleConstants.EXTENSION)) return; + public String getDisplayName() { + return GradleInspectionBundle.message("multiple.repository.urls"); + } - super.visitClosure(closure); - GrMethodCall mavenMethodCall = PsiTreeUtil.getParentOfType(closure, GrMethodCall.class); - if (mavenMethodCall == null) return; - GrExpression mavenMethodExpression = mavenMethodCall.getInvokedExpression(); - if (mavenMethodExpression == null || - !ArrayUtil.contains(mavenMethodExpression.getText(), "maven", "ivy")) { - return; - } + private static class MyVisitor extends BaseInspectionVisitor { + @Override + public void visitClosure(GrClosableBlock closure) { + PsiFile file = closure.getContainingFile(); + if (file == null || !FileUtil.extensionEquals(file.getName(), GradleConstants.EXTENSION)) { + return; + } - GrMethodCall repositoryMethodCall = PsiTreeUtil.getParentOfType(mavenMethodCall, GrMethodCall.class); - if (repositoryMethodCall == null) return; - GrExpression repositoryMethodExpression = repositoryMethodCall.getInvokedExpression(); - if (repositoryMethodExpression == null || !repositoryMethodExpression.getText().equals("repositories")) return; + super.visitClosure(closure); + GrMethodCall mavenMethodCall = PsiTreeUtil.getParentOfType(closure, GrMethodCall.class); + if (mavenMethodCall == null) { + return; + } + GrExpression mavenMethodExpression = mavenMethodCall.getInvokedExpression(); + if (mavenMethodExpression == null || + !ArrayUtil.contains(mavenMethodExpression.getText(), "maven", "ivy")) { + return; + } - List statements = findUrlCallExpressions(closure); - if (statements.size() > 1) { - registerError(closure); + GrMethodCall repositoryMethodCall = PsiTreeUtil.getParentOfType(mavenMethodCall, GrMethodCall.class); + if (repositoryMethodCall == null) { + return; + } + GrExpression repositoryMethodExpression = repositoryMethodCall.getInvokedExpression(); + if (repositoryMethodExpression == null || !repositoryMethodExpression.getText().equals("repositories")) { + return; + } - registerError(closure, GradleInspectionBundle.message("multiple.repository.urls"), - new LocalQuickFix[]{new MultipleRepositoryUrlsFix(closure, mavenMethodExpression.getText())}, - ProblemHighlightType.GENERIC_ERROR); - } + List statements = findUrlCallExpressions(closure); + if (statements.size() > 1) { + registerError(closure); + + registerError(closure, GradleInspectionBundle.message("multiple.repository.urls"), + new LocalQuickFix[]{new MultipleRepositoryUrlsFix(closure, mavenMethodExpression.getText())}, + ProblemHighlightType.GENERIC_ERROR + ); + } + } } - } - @Nonnull - static List findUrlCallExpressions(@Nonnull GrClosableBlock closure) { - GrCallExpression[] applicationStatements = PsiTreeUtil.getChildrenOfType(closure, GrCallExpression.class); - if (applicationStatements == null) return Collections.emptyList(); + @Nonnull + static List findUrlCallExpressions(@Nonnull GrClosableBlock closure) { + GrCallExpression[] applicationStatements = PsiTreeUtil.getChildrenOfType(closure, GrCallExpression.class); + if (applicationStatements == null) { + return Collections.emptyList(); + } - List statements = new ArrayList<>(); - for (GrCallExpression statement : applicationStatements) { - GrReferenceExpression[] referenceExpressions = PsiTreeUtil.getChildrenOfType(statement, GrReferenceExpression.class); - if (referenceExpressions == null) continue; - for (GrReferenceExpression expression : referenceExpressions) { - String expressionText = expression.getText(); - if ("url".equals(expressionText) || "setUrl".equals(expressionText)) { - statements.add(statement); + List statements = new ArrayList<>(); + for (GrCallExpression statement : applicationStatements) { + GrReferenceExpression[] referenceExpressions = PsiTreeUtil.getChildrenOfType(statement, GrReferenceExpression.class); + if (referenceExpressions == null) { + continue; + } + for (GrReferenceExpression expression : referenceExpressions) { + String expressionText = expression.getText(); + if ("url".equals(expressionText) || "setUrl".equals(expressionText)) { + statements.add(statement); + } + } } - } + return statements; } - return statements; - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/DelegatingGradleSettingsListenerAdapter.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/DelegatingGradleSettingsListenerAdapter.java index 2b49555..a17ebbe 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/DelegatingGradleSettingsListenerAdapter.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/DelegatingGradleSettingsListenerAdapter.java @@ -29,26 +29,25 @@ * @since 6/24/13 6:35 PM */ public class DelegatingGradleSettingsListenerAdapter extends DelegatingExternalSystemSettingsListener - implements GradleSettingsListener -{ + implements GradleSettingsListener { - public DelegatingGradleSettingsListenerAdapter(@Nonnull ExternalSystemSettingsListener delegate) { - super(delegate); - } + public DelegatingGradleSettingsListenerAdapter(@Nonnull ExternalSystemSettingsListener delegate) { + super(delegate); + } - @Override - public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @Nonnull String linkedProjectPath) { - } + @Override + public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @Nonnull String linkedProjectPath) { + } - @Override - public void onGradleDistributionTypeChange(DistributionType currentValue, @Nonnull String linkedProjectPath) { - } + @Override + public void onGradleDistributionTypeChange(DistributionType currentValue, @Nonnull String linkedProjectPath) { + } - @Override - public void onServiceDirectoryPathChange(@Nullable String oldPath, @Nullable String newPath) { - } + @Override + public void onServiceDirectoryPathChange(@Nullable String oldPath, @Nullable String newPath) { + } - @Override - public void onGradleVmOptionsChange(@Nullable String oldOptions, @Nullable String newOptions) { - } + @Override + public void onGradleVmOptionsChange(@Nullable String oldOptions, @Nullable String newOptions) { + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleBuildClasspathResolveScopeEnlarger.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleBuildClasspathResolveScopeEnlarger.java index b93a8cf..426e1be 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleBuildClasspathResolveScopeEnlarger.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleBuildClasspathResolveScopeEnlarger.java @@ -34,19 +34,20 @@ */ @ExtensionImpl public class GradleBuildClasspathResolveScopeEnlarger extends ResolveScopeEnlarger { - @Override - public SearchScope getAdditionalResolveScope(@Nonnull VirtualFile file, Project project) { - String fileExtension = file.getExtension(); - if (GroovyFileType.DEFAULT_EXTENSION.equals(fileExtension)) { - GradleClassFinder gradleClassFinder = project.getExtensionPoint(PsiElementFinder.class).findExtensionOrFail(GradleClassFinder.class); + @Override + public SearchScope getAdditionalResolveScope(@Nonnull VirtualFile file, Project project) { + String fileExtension = file.getExtension(); + if (GroovyFileType.DEFAULT_EXTENSION.equals(fileExtension)) { + GradleClassFinder gradleClassFinder = + project.getExtensionPoint(PsiElementFinder.class).findExtensionOrFail(GradleClassFinder.class); - final List roots = gradleClassFinder.getClassRoots(); - for (VirtualFile root : roots) { - if (VfsUtilCore.isAncestor(root, file, true)) { - return NonClasspathDirectoriesScope.compose(roots); + final List roots = gradleClassFinder.getClassRoots(); + for (VirtualFile root : roots) { + if (VfsUtilCore.isAncestor(root, file, true)) { + return NonClasspathDirectoriesScope.compose(roots); + } + } } - } + return null; } - return null; - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleClassFinder.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleClassFinder.java index b07932f..406e07c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleClassFinder.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleClassFinder.java @@ -44,59 +44,64 @@ */ @ExtensionImpl public class GradleClassFinder extends NonClasspathClassFinder { - @Nonnull - private final GradleBuildClasspathManager myBuildClasspathManager; - private final Map myCaches; + @Nonnull + private final GradleBuildClasspathManager myBuildClasspathManager; + private final Map myCaches; - @Inject - public GradleClassFinder(@Nonnull Project project, @Nonnull GradleBuildClasspathManager buildClasspathManager) { - super(project, JavaFileType.DEFAULT_EXTENSION, GroovyFileType.DEFAULT_EXTENSION); - myBuildClasspathManager = buildClasspathManager; + @Inject + public GradleClassFinder(@Nonnull Project project, @Nonnull GradleBuildClasspathManager buildClasspathManager) { + super(project, JavaFileType.DEFAULT_EXTENSION, GroovyFileType.DEFAULT_EXTENSION); + myBuildClasspathManager = buildClasspathManager; - myCaches = ConcurrentFactoryMap.createMap(path -> createCache(myBuildClasspathManager.getModuleClasspathEntries(path))); - } - - @Override - protected List calcClassRoots() { - return myBuildClasspathManager.getAllClasspathEntries(); - } + myCaches = ConcurrentFactoryMap.createMap(path -> createCache(myBuildClasspathManager.getModuleClasspathEntries(path))); + } - @Nonnull - @Override - protected PackageDirectoryCache getCache(@Nullable GlobalSearchScope scope) { - if (scope instanceof ExternalModuleBuildGlobalSearchScope) { - return myCaches.get(((ExternalModuleBuildGlobalSearchScope)scope).getExternalModulePath()); + @Override + protected List calcClassRoots() { + return myBuildClasspathManager.getAllClasspathEntries(); } - return super.getCache(scope); - } - @Override - public void clearCache() { - super.clearCache(); - myCaches.clear(); - } + @Nonnull + @Override + protected PackageDirectoryCache getCache(@Nullable GlobalSearchScope scope) { + if (scope instanceof ExternalModuleBuildGlobalSearchScope externalModuleBuildGlobalSearchScope) { + return myCaches.get(externalModuleBuildGlobalSearchScope.getExternalModulePath()); + } + return super.getCache(scope); + } - @Override - public PsiClass findClass(@Nonnull String qualifiedName, @Nonnull GlobalSearchScope scope) { - PsiClass aClass = super.findClass(qualifiedName, scope); - if (aClass == null || scope instanceof ExternalModuleBuildGlobalSearchScope || scope instanceof EverythingGlobalScope) { - return aClass; + @Override + public void clearCache() { + super.clearCache(); + myCaches.clear(); } - PsiFile containingFile = aClass.getContainingFile(); - VirtualFile file = containingFile != null ? containingFile.getVirtualFile() : null; - return (file != null && !ProjectFileIndex.SERVICE.getInstance(myProject).isInContent(file) && !ProjectFileIndex.SERVICE.getInstance - (myProject).isInLibraryClasses(file) && !ProjectFileIndex.SERVICE.getInstance(myProject).isInLibrarySource(file)) ? aClass : null; - } + @Override + public PsiClass findClass(@Nonnull String qualifiedName, @Nonnull GlobalSearchScope scope) { + PsiClass aClass = super.findClass(qualifiedName, scope); + if (aClass == null || scope instanceof ExternalModuleBuildGlobalSearchScope || scope instanceof EverythingGlobalScope) { + return aClass; + } - @Nonnull - @Override - public PsiJavaPackage[] getSubPackages(@Nonnull PsiJavaPackage psiPackage, @Nonnull GlobalSearchScope scope) { - if (scope instanceof ExternalModuleBuildGlobalSearchScope) { - return super.getSubPackages(psiPackage, scope); + PsiFile containingFile = aClass.getContainingFile(); + VirtualFile file = containingFile != null ? containingFile.getVirtualFile() : null; + ProjectFileIndex projectFileIndex = ProjectFileIndex.SERVICE.getInstance(myProject); + return file != null + && !projectFileIndex.isInContent(file) + && !projectFileIndex.isInLibraryClasses(file) + && !projectFileIndex.isInLibrarySource(file) + ? aClass + : null; } - else { - return PsiJavaPackage.EMPTY_ARRAY; + + @Nonnull + @Override + public PsiJavaPackage[] getSubPackages(@Nonnull PsiJavaPackage psiPackage, @Nonnull GlobalSearchScope scope) { + if (scope instanceof ExternalModuleBuildGlobalSearchScope) { + return super.getSubPackages(psiPackage, scope); + } + else { + return PsiJavaPackage.EMPTY_ARRAY; + } } - } } \ No newline at end of file diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleDefaultImportContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleDefaultImportContributor.java index 925e146..e71c6c5 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleDefaultImportContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleDefaultImportContributor.java @@ -30,121 +30,120 @@ */ @ExtensionImpl public class GradleDefaultImportContributor extends DefaultImportContributor { + // As listed here - http://www.gradle.org/docs/current/userguide/userguide_single.html#sec:using_gradle_without_ide_support + public static final String[] IMPLICIT_GRADLE_PACKAGES = { + "org.gradle", + "org.gradle.api", + "org.gradle.api.artifacts", + "org.gradle.api.artifacts.cache", + "org.gradle.api.artifacts.dsl", + "org.gradle.api.artifacts.maven", + "org.gradle.api.artifacts.repositories", + "org.gradle.api.artifacts.result", + "org.gradle.api.component", + "org.gradle.api.distribution", + "org.gradle.api.distribution.plugins", + "org.gradle.api.dsl", + "org.gradle.api.execution", + "org.gradle.api.file", + "org.gradle.api.initialization", + "org.gradle.api.initialization.dsl", + "org.gradle.api.invocation", + "org.gradle.api.java.archives", + "org.gradle.api.logging", + "org.gradle.api.plugins", + "org.gradle.api.plugins.announce", + "org.gradle.api.plugins.antlr", + "org.gradle.api.plugins.buildcomparison.gradle", + "org.gradle.api.plugins.jetty", + "org.gradle.api.plugins.osgi", + "org.gradle.api.plugins.quality", + "org.gradle.api.plugins.scala", + "org.gradle.api.plugins.sonar", + "org.gradle.api.plugins.sonar.model", + "org.gradle.api.publish", + "org.gradle.api.publish.ivy", + "org.gradle.api.publish.ivy.plugins", + "org.gradle.api.publish.ivy.tasks", + "org.gradle.api.publish.maven", + "org.gradle.api.publish.maven.plugins", + "org.gradle.api.publish.maven.tasks", + "org.gradle.api.publish.plugins", + "org.gradle.api.reporting", + "org.gradle.api.reporting.plugins", + "org.gradle.api.resources", + "org.gradle.api.sonar.runner", + "org.gradle.api.specs", + "org.gradle.api.tasks", + "org.gradle.api.tasks.ant", + "org.gradle.api.tasks.application", + "org.gradle.api.tasks.bundling", + "org.gradle.api.tasks.compile", + "org.gradle.api.tasks.diagnostics", + "org.gradle.api.tasks.incremental", + "org.gradle.api.tasks.javadoc", + "org.gradle.api.tasks.scala", + "org.gradle.api.tasks.testing", + "org.gradle.api.tasks.testing.junit", + "org.gradle.api.tasks.testing.testng", + "org.gradle.api.tasks.util", + "org.gradle.api.tasks.wrapper", + "org.gradle.buildsetup.plugins", + "org.gradle.buildsetup.tasks", + "org.gradle.external.javadoc", + "org.gradle.language.base", + "org.gradle.language.base.plugins", + "org.gradle.language.java", + "org.gradle.language.jvm", + "org.gradle.language.jvm.plugins", + "org.gradle.language.jvm.tasks", + "org.gradle.nativecode.base", + "org.gradle.nativecode.base.plugins", + "org.gradle.nativecode.base.tasks", + "org.gradle.nativecode.cdt", + "org.gradle.nativecode.cdt.tasks", + "org.gradle.nativecode.language.cpp", + "org.gradle.nativecode.language.cpp.plugins", + "org.gradle.nativecode.language.cpp.tasks", + "org.gradle.nativecode.toolchain.plugins", + "org.gradle.plugins.binaries", + "org.gradle.plugins.cpp", + "org.gradle.plugins.cpp.cdt", + "org.gradle.plugins.cpp.cdt.tasks", + "org.gradle.plugins.cpp.compiler.capability", + "org.gradle.plugins.cpp.gpp", + "org.gradle.plugins.cpp.msvcpp", + "org.gradle.plugins.ear", + "org.gradle.plugins.ear.descriptor", + "org.gradle.plugins.ide.api", + "org.gradle.plugins.ide.eclipse", + "org.gradle.plugins.ide.idea", + "org.gradle.plugins.javascript.base", + "org.gradle.plugins.javascript.coffeescript", + "org.gradle.plugins.javascript.envjs", + "org.gradle.plugins.javascript.envjs.browser", + "org.gradle.plugins.javascript.envjs.http", + "org.gradle.plugins.javascript.envjs.http.simple", + "org.gradle.plugins.javascript.jshint", + "org.gradle.plugins.javascript.rhino", + "org.gradle.plugins.javascript.rhino.worker", + "org.gradle.plugins.signing", + "org.gradle.plugins.signing.signatory", + "org.gradle.plugins.signing.signatory.pgp", + "org.gradle.plugins.signing.type", + "org.gradle.plugins.signing.type.pgp", + "org.gradle.process", + "org.gradle.testing.jacoco.plugins", + "org.gradle.testing.jacoco.tasks", + "org.gradle.util" + }; - // As listed here - http://www.gradle.org/docs/current/userguide/userguide_single.html#sec:using_gradle_without_ide_support - public static final String[] IMPLICIT_GRADLE_PACKAGES = { - "org.gradle", - "org.gradle.api", - "org.gradle.api.artifacts", - "org.gradle.api.artifacts.cache", - "org.gradle.api.artifacts.dsl", - "org.gradle.api.artifacts.maven", - "org.gradle.api.artifacts.repositories", - "org.gradle.api.artifacts.result", - "org.gradle.api.component", - "org.gradle.api.distribution", - "org.gradle.api.distribution.plugins", - "org.gradle.api.dsl", - "org.gradle.api.execution", - "org.gradle.api.file", - "org.gradle.api.initialization", - "org.gradle.api.initialization.dsl", - "org.gradle.api.invocation", - "org.gradle.api.java.archives", - "org.gradle.api.logging", - "org.gradle.api.plugins", - "org.gradle.api.plugins.announce", - "org.gradle.api.plugins.antlr", - "org.gradle.api.plugins.buildcomparison.gradle", - "org.gradle.api.plugins.jetty", - "org.gradle.api.plugins.osgi", - "org.gradle.api.plugins.quality", - "org.gradle.api.plugins.scala", - "org.gradle.api.plugins.sonar", - "org.gradle.api.plugins.sonar.model", - "org.gradle.api.publish", - "org.gradle.api.publish.ivy", - "org.gradle.api.publish.ivy.plugins", - "org.gradle.api.publish.ivy.tasks", - "org.gradle.api.publish.maven", - "org.gradle.api.publish.maven.plugins", - "org.gradle.api.publish.maven.tasks", - "org.gradle.api.publish.plugins", - "org.gradle.api.reporting", - "org.gradle.api.reporting.plugins", - "org.gradle.api.resources", - "org.gradle.api.sonar.runner", - "org.gradle.api.specs", - "org.gradle.api.tasks", - "org.gradle.api.tasks.ant", - "org.gradle.api.tasks.application", - "org.gradle.api.tasks.bundling", - "org.gradle.api.tasks.compile", - "org.gradle.api.tasks.diagnostics", - "org.gradle.api.tasks.incremental", - "org.gradle.api.tasks.javadoc", - "org.gradle.api.tasks.scala", - "org.gradle.api.tasks.testing", - "org.gradle.api.tasks.testing.junit", - "org.gradle.api.tasks.testing.testng", - "org.gradle.api.tasks.util", - "org.gradle.api.tasks.wrapper", - "org.gradle.buildsetup.plugins", - "org.gradle.buildsetup.tasks", - "org.gradle.external.javadoc", - "org.gradle.language.base", - "org.gradle.language.base.plugins", - "org.gradle.language.java", - "org.gradle.language.jvm", - "org.gradle.language.jvm.plugins", - "org.gradle.language.jvm.tasks", - "org.gradle.nativecode.base", - "org.gradle.nativecode.base.plugins", - "org.gradle.nativecode.base.tasks", - "org.gradle.nativecode.cdt", - "org.gradle.nativecode.cdt.tasks", - "org.gradle.nativecode.language.cpp", - "org.gradle.nativecode.language.cpp.plugins", - "org.gradle.nativecode.language.cpp.tasks", - "org.gradle.nativecode.toolchain.plugins", - "org.gradle.plugins.binaries", - "org.gradle.plugins.cpp", - "org.gradle.plugins.cpp.cdt", - "org.gradle.plugins.cpp.cdt.tasks", - "org.gradle.plugins.cpp.compiler.capability", - "org.gradle.plugins.cpp.gpp", - "org.gradle.plugins.cpp.msvcpp", - "org.gradle.plugins.ear", - "org.gradle.plugins.ear.descriptor", - "org.gradle.plugins.ide.api", - "org.gradle.plugins.ide.eclipse", - "org.gradle.plugins.ide.idea", - "org.gradle.plugins.javascript.base", - "org.gradle.plugins.javascript.coffeescript", - "org.gradle.plugins.javascript.envjs", - "org.gradle.plugins.javascript.envjs.browser", - "org.gradle.plugins.javascript.envjs.http", - "org.gradle.plugins.javascript.envjs.http.simple", - "org.gradle.plugins.javascript.jshint", - "org.gradle.plugins.javascript.rhino", - "org.gradle.plugins.javascript.rhino.worker", - "org.gradle.plugins.signing", - "org.gradle.plugins.signing.signatory", - "org.gradle.plugins.signing.signatory.pgp", - "org.gradle.plugins.signing.type", - "org.gradle.plugins.signing.type.pgp", - "org.gradle.process", - "org.gradle.testing.jacoco.plugins", - "org.gradle.testing.jacoco.tasks", - "org.gradle.util" - }; - - @Override - public List appendImplicitlyImportedPackages(@Nonnull GroovyFile file) { - if (file.isScript() && GroovyScriptUtil.getScriptType(file) instanceof GradleScriptType) { - return Arrays.asList(IMPLICIT_GRADLE_PACKAGES); + @Override + public List appendImplicitlyImportedPackages(@Nonnull GroovyFile file) { + if (file.isScript() && GroovyScriptUtil.getScriptType(file) instanceof GradleScriptType) { + return Arrays.asList(IMPLICIT_GRADLE_PACKAGES); + } + return Collections.emptyList(); } - return Collections.emptyList(); - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleLibraryPresentationProvider.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleLibraryPresentationProvider.java index fec2b2c..f710b5b 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleLibraryPresentationProvider.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleLibraryPresentationProvider.java @@ -40,92 +40,91 @@ */ @ExtensionImpl public class GradleLibraryPresentationProvider extends GroovyLibraryPresentationProviderBase { + private static final LibraryKind GRADLE_KIND = LibraryKind.create(GradleConstants.EXTENSION); - private static final LibraryKind GRADLE_KIND = LibraryKind.create(GradleConstants.EXTENSION); + private final GradleInstallationManager myLibraryManager; - private final GradleInstallationManager myLibraryManager; - - @Inject - public GradleLibraryPresentationProvider(@Nonnull GradleInstallationManager libraryManager) { - super(GRADLE_KIND); - myLibraryManager = libraryManager; - } + @Inject + public GradleLibraryPresentationProvider(@Nonnull GradleInstallationManager libraryManager) { + super(GRADLE_KIND); + myLibraryManager = libraryManager; + } - @Nonnull - @Override - public Image getIcon() { - return GradleIconGroup.gradle(); - } + @Nonnull + @Override + public Image getIcon() { + return GradleIconGroup.gradle(); + } - @Nls - @Override - public String getLibraryVersion(final VirtualFile[] libraryFiles) { - return getGradleVersion(libraryFiles); - } + @Nls + @Override + public String getLibraryVersion(final VirtualFile[] libraryFiles) { + return getGradleVersion(libraryFiles); + } - @Override - public boolean isSDKHome(@Nonnull VirtualFile file) { - return myLibraryManager.isGradleSdkHome(file); - } + @Override + public boolean isSDKHome(@Nonnull VirtualFile file) { + return myLibraryManager.isGradleSdkHome(file); + } - @Override - public boolean managesLibrary(final VirtualFile[] libraryFiles) { - return myLibraryManager.isGradleSdk(libraryFiles); - } + @Override + public boolean managesLibrary(final VirtualFile[] libraryFiles) { + return myLibraryManager.isGradleSdk(libraryFiles); + } - @Nonnull - @Override - public String getSDKVersion(String path) { - final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); - assert file != null; - VirtualFile lib = file.findChild("lib"); - assert lib != null; - for (VirtualFile virtualFile : lib.getChildren()) { - final String version = getGradleJarVersion(virtualFile); - if (version != null) { - return version; - } + @Nonnull + @Override + public String getSDKVersion(String path) { + final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); + assert file != null; + VirtualFile lib = file.findChild("lib"); + assert lib != null; + for (VirtualFile virtualFile : lib.getChildren()) { + final String version = getGradleJarVersion(virtualFile); + if (version != null) { + return version; + } + } + throw new AssertionError(path); } - throw new AssertionError(path); - } - @Nls - @Nonnull - @Override - public String getLibraryCategoryName() { - return "Gradle"; - } + @Nls + @Nonnull + @Override + public String getLibraryCategoryName() { + return "Gradle"; + } - @Override - protected void fillLibrary(String path, LibraryEditor libraryEditor) { - File lib = new File(path + "/lib"); - File[] jars = lib.exists() ? lib.listFiles() : new File[0]; - if (jars != null) { - for (File file : jars) { - if (file.getName().endsWith(".jar")) { - libraryEditor.addRoot(VfsUtil.getUrlForLibraryRoot(file), BinariesOrderRootType.getInstance()); + @Override + protected void fillLibrary(String path, LibraryEditor libraryEditor) { + File lib = new File(path + "/lib"); + File[] jars = lib.exists() ? lib.listFiles() : new File[0]; + if (jars != null) { + for (File file : jars) { + if (file.getName().endsWith(".jar")) { + libraryEditor.addRoot(VfsUtil.getUrlForLibraryRoot(file), BinariesOrderRootType.getInstance()); + } + } } - } } - } - @Nullable - private static String getGradleVersion(VirtualFile[] libraryFiles) { - for (VirtualFile file : libraryFiles) { - final String version = getGradleJarVersion(file); - if (version != null) { - return version; - } + @Nullable + private static String getGradleVersion(VirtualFile[] libraryFiles) { + for (VirtualFile file : libraryFiles) { + final String version = getGradleJarVersion(file); + if (version != null) { + return version; + } + } + return null; } - return null; - } - @Nullable - private static String getGradleJarVersion(VirtualFile file) { - final Matcher matcher = GradleInstallationManager.GRADLE_JAR_FILE_PATTERN.matcher(file.getName()); - if (matcher.matches()) { - return matcher.group(2); + @Nullable + private static String getGradleJarVersion(VirtualFile file) { + final Matcher matcher = GradleInstallationManager.GRADLE_JAR_FILE_PATTERN.matcher(file.getName()); + if (matcher.matches()) { + return matcher.group(2); + } + return null; } - return null; - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePatcher.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePatcher.java index d14e280..c934f31 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePatcher.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePatcher.java @@ -9,27 +9,26 @@ * Encapsulates functionality of patching problems from the previous gradle integration releases. *

* Thread-safe. - * + * * @author Denis Zhdanov * @since 3/19/12 3:48 PM */ public class GradlePatcher { + @SuppressWarnings("MethodMayBeStatic") + public void patch(@Nonnull Project project) { + patchGradleHomeIfNecessary(project); + } - @SuppressWarnings("MethodMayBeStatic") - public void patch(@Nonnull Project project) { - patchGradleHomeIfNecessary(project); - } + private static void patchGradleHomeIfNecessary(@Nonnull Project project) { + // Old gradle integration didn't save gradle home at project-local settings (only default project has that information). - private static void patchGradleHomeIfNecessary(@Nonnull Project project) { - // Old gradle integration didn't save gradle home at project-local settings (only default project has that information). - - final Project defaultProject = ProjectManager.getInstance().getDefaultProject(); - if (defaultProject.equals(project)) { - return; - } + final Project defaultProject = ProjectManager.getInstance().getDefaultProject(); + if (defaultProject.equals(project)) { + return; + } - // Propagate gradle settings from the current project to the default project if necessary. - // TODO den implement + // Propagate gradle settings from the current project to the default project if necessary. + // TODO den implement // final GradleSettings defaultProjectSettings = GradleSettings.getInstance(defaultProject); // final GradleSettings currentProjectSettings = GradleSettings.getInstance(project); // String projectGradleHome = currentProjectSettings.getGradleHome(); @@ -43,5 +42,5 @@ private static void patchGradleHomeIfNecessary(@Nonnull Project project) { // if (autodetectedGradleHome == null || !FileUtil.filesEqual(autodetectedGradleHome, new File(projectGradleHome))) { // GradleSettings.applyGradleHome(projectGradleHome, defaultProject); // } - } + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePositionManager.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePositionManager.java index c5bae71..1530dac 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePositionManager.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePositionManager.java @@ -57,139 +57,147 @@ */ @ExtensionImpl public class GradlePositionManager extends ScriptPositionManagerHelper { + private static final Logger LOG = Logger.getInstance(GradlePositionManager.class); - private static final Logger LOG = Logger.getInstance(GradlePositionManager.class); + private static final Pattern GRADLE_CLASS_PATTERN = Pattern.compile(".*_gradle_.*"); + private static final String SCRIPT_CLOSURE_PREFIX = "build_"; + private static final Key> GRADLE_CLASS_LOADER = Key.create("GRADLE_CLASS_LOADER"); + private static final Key>> GRADLE_CLASS_NAME = Key.create("GRADLE_CLASS_NAME"); - private static final Pattern GRADLE_CLASS_PATTERN = Pattern.compile(".*_gradle_.*"); - private static final String SCRIPT_CLOSURE_PREFIX = "build_"; - private static final Key> GRADLE_CLASS_LOADER = Key.create("GRADLE_CLASS_LOADER"); - private static final Key>> GRADLE_CLASS_NAME = Key.create("GRADLE_CLASS_NAME"); + private final GradleInstallationManager myLibraryManager; - private final GradleInstallationManager myLibraryManager; + @Inject + public GradlePositionManager(@Nonnull GradleInstallationManager manager) { + myLibraryManager = manager; + } - @Inject - public GradlePositionManager(@Nonnull GradleInstallationManager manager) { - myLibraryManager = manager; - } + public boolean isAppropriateRuntimeName(@Nonnull final String runtimeName) { + return runtimeName.startsWith(SCRIPT_CLOSURE_PREFIX) || GRADLE_CLASS_PATTERN.matcher(runtimeName).matches(); + } - public boolean isAppropriateRuntimeName(@Nonnull final String runtimeName) { - return runtimeName.startsWith(SCRIPT_CLOSURE_PREFIX) || GRADLE_CLASS_PATTERN.matcher(runtimeName).matches(); - } + public boolean isAppropriateScriptFile(@Nonnull final GroovyFile scriptFile) { + return GroovyScriptUtil.isSpecificScriptFile((GroovyFile)scriptFile, GradleScriptType.INSTANCE); + } - public boolean isAppropriateScriptFile(@Nonnull final GroovyFile scriptFile) { - return GroovyScriptUtil.isSpecificScriptFile((GroovyFile)scriptFile, GradleScriptType.INSTANCE); - } + @Nonnull + public String getRuntimeScriptName(GroovyFile groovyFile) { + VirtualFile virtualFile = groovyFile.getVirtualFile(); + if (virtualFile == null) { + return ""; + } - @Nonnull - public String getRuntimeScriptName(GroovyFile groovyFile) { - VirtualFile virtualFile = groovyFile.getVirtualFile(); - if (virtualFile == null) return ""; + final Module module = ModuleUtilCore.findModuleForPsiElement(groovyFile); + if (module == null) { + return ""; + } - final Module module = ModuleUtilCore.findModuleForPsiElement(groovyFile); - if (module == null) { - return ""; + final File scriptFile = VfsUtilCore.virtualToIoFile(virtualFile); + final String className = CachedValuesManager.getManager(module.getProject()) + .getCachedValue(module, GRADLE_CLASS_NAME, new ScriptSourceMapCalculator(module), false).get(scriptFile); + return className == null ? "" : className; } - final File scriptFile = VfsUtilCore.virtualToIoFile(virtualFile); - final String className = CachedValuesManager.getManager(module.getProject()) - .getCachedValue(module, GRADLE_CLASS_NAME, new ScriptSourceMapCalculator(module), false).get(scriptFile); - return className == null ? "" : className; - } - - public PsiFile getExtraScriptIfNotFound(ReferenceType refType, @Nonnull String runtimeName, Project project, GlobalSearchScope scope) { - String sourceFilePath = getScriptForClassName(refType); - if (sourceFilePath == null) return null; - - VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(sourceFilePath)); - if (virtualFile == null) return null; - - return PsiManager.getInstance(project).findFile(virtualFile); - } - - @Nullable - private static String getScriptForClassName(@Nonnull ReferenceType refType) { - try { - final List data = refType.sourcePaths(null); - if (!data.isEmpty()) { - return data.get(0); - } - } - catch (AbsentInformationException ignored) { - } - return null; - } - - @Nullable - private ClassLoader getGradleClassLoader(@Nonnull final Module module) { - final Project project = module.getProject(); - return CachedValuesManager.getManager(project).getCachedValue(module, GRADLE_CLASS_LOADER, new CachedValueProvider() { - public Result compute() { - return Result.create(createGradleClassLoader(module), ProjectRootManager.getInstance(project)); + public PsiFile getExtraScriptIfNotFound(ReferenceType refType, @Nonnull String runtimeName, Project project, GlobalSearchScope scope) { + String sourceFilePath = getScriptForClassName(refType); + if (sourceFilePath == null) { + return null; } - }, false); - } - - @Nullable - private ClassLoader createGradleClassLoader(@Nonnull Module module) { - String rootProjectPath = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY); - if (StringUtil.isEmpty(rootProjectPath)) { - return null; - } - final VirtualFile sdkHome = myLibraryManager.getGradleHome(module, module.getProject(), rootProjectPath); - if (sdkHome == null) { - return null; - } - - List urls = new ArrayList(); - final VirtualFile libDir = sdkHome.findChild("lib"); - assert libDir != null; - for (final VirtualFile child : libDir.getChildren()) { - if ("jar".equals(child.getExtension())) { - urls.add(VfsUtil.convertToURL(child.getUrl())); - } - } - return UrlClassLoader.build().urls(urls).get(); - } + VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(sourceFilePath)); + if (virtualFile == null) { + return null; + } - private class ScriptSourceMapCalculator implements CachedValueProvider> { - private final Module myModule; + return PsiManager.getInstance(project).findFile(virtualFile); + } - public ScriptSourceMapCalculator(Module module) { - myModule = module; + @Nullable + private static String getScriptForClassName(@Nonnull ReferenceType refType) { + try { + final List data = refType.sourcePaths(null); + if (!data.isEmpty()) { + return data.get(0); + } + } + catch (AbsentInformationException ignored) { + } + return null; } - public Result> compute() { - final Map result = ConcurrentFactoryMap.createMap(this::calcClassName); - return Result.create(result, ProjectRootManager.getInstance(myModule.getProject())); + @Nullable + private ClassLoader getGradleClassLoader(@Nonnull final Module module) { + final Project project = module.getProject(); + return CachedValuesManager.getManager(project).getCachedValue( + module, + GRADLE_CLASS_LOADER, + ()-> CachedValueProvider.Result.create(createGradleClassLoader(module), ProjectRootManager.getInstance(project)), + false + ); } @Nullable - private String calcClassName(File scriptFile) { - final ClassLoader loader = getGradleClassLoader(myModule); - if (loader != null) { - Class fileScriptSource; - try { - fileScriptSource = Class.forName("org.gradle.groovy.scripts.UriScriptSource", true, loader); + private ClassLoader createGradleClassLoader(@Nonnull Module module) { + String rootProjectPath = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY); + if (StringUtil.isEmpty(rootProjectPath)) { + return null; } - catch (ClassNotFoundException e) { - try { - fileScriptSource = Class.forName("org.gradle.groovy.scripts.FileScriptSource", true, loader); //before 0.9 - } - catch (ClassNotFoundException e1) { + final VirtualFile sdkHome = myLibraryManager.getGradleHome(module, module.getProject(), rootProjectPath); + if (sdkHome == null) { return null; - } } - try { - final Object source = fileScriptSource.getConstructor(String.class, File.class).newInstance("script", scriptFile); - return (String)fileScriptSource.getMethod("getClassName").invoke(source); + List urls = new ArrayList(); + final VirtualFile libDir = sdkHome.findChild("lib"); + assert libDir != null; + for (final VirtualFile child : libDir.getChildren()) { + if ("jar".equals(child.getExtension())) { + urls.add(VfsUtil.convertToURL(child.getUrl())); + } + } + + return UrlClassLoader.build().urls(urls).get(); + } + + private class ScriptSourceMapCalculator implements CachedValueProvider> { + private final Module myModule; + + public ScriptSourceMapCalculator(Module module) { + myModule = module; } - catch (Exception e) { - LOG.error(e); + + public Result> compute() { + final Map result = ConcurrentFactoryMap.createMap(this::calcClassName); + return Result.create(result, ProjectRootManager.getInstance(myModule.getProject())); + } + + @Nullable + private String calcClassName(File scriptFile) { + final ClassLoader loader = getGradleClassLoader(myModule); + if (loader != null) { + Class fileScriptSource; + try { + fileScriptSource = Class.forName("org.gradle.groovy.scripts.UriScriptSource", true, loader); + } + catch (ClassNotFoundException e) { + try { + //before 0.9 + fileScriptSource = Class.forName("org.gradle.groovy.scripts.FileScriptSource", true, loader); + } + catch (ClassNotFoundException e1) { + return null; + } + } + + try { + final Object source = fileScriptSource.getConstructor(String.class, File.class) + .newInstance("script", scriptFile); + return (String)fileScriptSource.getMethod("getClassName").invoke(source); + } + catch (Exception e) { + LOG.error(e); + } + } + return null; } - } - return null; } - } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java index 26e5886..14c6c5a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java @@ -80,270 +80,275 @@ * @author peter */ public class GradleScriptType extends GroovyRunnableScriptType { - private static final Pattern MAIN_CLASS_NAME_PATTERN = Pattern.compile("\nSTARTER_MAIN_CLASS=(.*)\n"); + private static final Pattern MAIN_CLASS_NAME_PATTERN = Pattern.compile("\nSTARTER_MAIN_CLASS=(.*)\n"); - public static final GroovyScriptType INSTANCE = new GradleScriptType(); + public static final GroovyScriptType INSTANCE = new GradleScriptType(); - private GradleScriptType() { - super(GradleConstants.EXTENSION); - } - - @Nonnull - @Override - public Image getScriptIcon() { - return GradleIconGroup.gradle(); - } - - @Override - public boolean isConfigurationByLocation(@Nonnull GroovyScriptRunConfiguration existing, @Nonnull Location location) { - final String params = existing.getScriptParameters(); - if (params == null) { - return false; + private GradleScriptType() { + super(GradleConstants.EXTENSION); } - final List tasks = getTasksTarget(location); - if (tasks == null) { - return false; + @Nonnull + @Override + public Image getScriptIcon() { + return GradleIconGroup.gradle(); } - String s = StringUtil.join(tasks, " "); - return params.startsWith(s + " ") || params.equals(s); - } - - @Override - public void tuneConfiguration(@Nonnull GroovyFile file, @Nonnull GroovyScriptRunConfiguration configuration, Location location) { - List tasks = getTasksTarget(location); - if (tasks != null) { - String s = StringUtil.join(tasks, " "); - configuration.setScriptParameters(s); - configuration.setName("gradle:" + s); - } - - RunManager.getInstance(file.getProject()).disableTasks(configuration, CompileStepBeforeRun.ID, CompileStepBeforeRunNoErrorCheck.ID); - } + @Override + public boolean isConfigurationByLocation(@Nonnull GroovyScriptRunConfiguration existing, @Nonnull Location location) { + final String params = existing.getScriptParameters(); + if (params == null) { + return false; + } - @Nullable - private static List getTasksTarget(Location location) { - if (location instanceof GradleTaskLocation) { - return ((GradleTaskLocation)location).getTasks(); - } + final List tasks = getTasksTarget(location); + if (tasks == null) { + return false; + } - PsiElement parent = location.getPsiElement(); - while (parent.getParent() != null && !(parent.getParent() instanceof PsiFile)) { - parent = parent.getParent(); + String s = StringUtil.join(tasks, " "); + return params.startsWith(s + " ") || params.equals(s); } - if (isCreateTaskMethod(parent)) { - final GrExpression[] arguments = ((GrMethodCallExpression)parent).getExpressionArguments(); - if (arguments.length > 0 && arguments[0] instanceof GrLiteral && ((GrLiteral)arguments[0]).getValue() instanceof String) { - return Collections.singletonList((String)((GrLiteral)arguments[0]).getValue()); - } - } - else if (parent instanceof GrApplicationStatement) { - PsiElement shiftExpression = parent.getChildren()[1].getChildren()[0]; - if (GradleResolverUtil.isLShiftElement(shiftExpression)) { - PsiElement shiftiesChild = shiftExpression.getChildren()[0]; - if (shiftiesChild instanceof GrReferenceExpression) { - return Collections.singletonList(shiftiesChild.getText()); - } - else if (shiftiesChild instanceof GrMethodCallExpression) { - return Collections.singletonList(shiftiesChild.getChildren()[0].getText()); + @Override + public void tuneConfiguration(@Nonnull GroovyFile file, @Nonnull GroovyScriptRunConfiguration configuration, Location location) { + List tasks = getTasksTarget(location); + if (tasks != null) { + String s = StringUtil.join(tasks, " "); + configuration.setScriptParameters(s); + configuration.setName("gradle:" + s); } - } - else if (shiftExpression instanceof GrMethodCallExpression) { - return Collections.singletonList(shiftExpression.getChildren()[0].getText()); - } + + RunManager.getInstance(file.getProject()) + .disableTasks(configuration, CompileStepBeforeRun.ID, CompileStepBeforeRunNoErrorCheck.ID); } - return null; - } - - private static boolean isCreateTaskMethod(PsiElement parent) { - return parent instanceof GrMethodCallExpression && PsiUtil.isMethodCall((GrMethodCallExpression)parent, "createTask"); - } - - @Override - public GroovyScriptRunner getRunner() { - return new GroovyScriptRunner() { - @Override - public boolean shouldRefreshAfterFinish() { - return true; - } - - @Override - public boolean isValidModule(@Nonnull Module module) { - GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); - return libraryManager.isGradleSdk(OrderEnumerator.orderEntries(module).getAllLibrariesAndSdkClassesRoots()); - } - - @Override - public boolean ensureRunnerConfigured(@Nullable Module module, - RunProfile profile, - Executor executor, - final Project project) throws ExecutionException { - if (project != null && profile instanceof GroovyScriptRunConfiguration) { - GroovyScriptRunConfiguration configuration = (GroovyScriptRunConfiguration)profile; - String parameters = configuration.getScriptParameters(); - if (parameters != null) { - // TODO den implement - // GradleTasksList list = GradleUtil.getToolWindowElement(GradleTasksList.class, project, - // ExternalSystemDataKeys.RECENT_TASKS_LIST); - // if (list != null) { - // ExternalSystemTaskDescriptor descriptor = new ExternalSystemTaskDescriptor(parameters, null); - // descriptor.setExecutorId(executor.getId()); - // list.setFirst(descriptor); - // GradleLocalSettings.getInstance(project).setRecentTasks(list.getModel().getTasks()); - // } - } - } - final GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); - // TODO den implement - //if (libraryManager.getGradleHome(module, project) == null) { - // int result = 0; - // int result = Messages.showOkCancelDialog( - // ExternalSystemBundle.message("gradle.run.no.sdk.text"), - // ExternalSystemBundle.message("gradle.run.no.sdk.title"), - // GradleIcons.Gradle - // ); - // if (result == 0) { - // ShowSettingsUtil.getInstance().editConfigurable(project, new AbstractExternalProjectConfigurable(project)); - // } - // if (libraryManager.getGradleHome(module, project) == null) { - // return false; - // } - // } - return true; - } - - @Override - public void configureCommandLine(OwnJavaParameters params, - @Nullable Module module, - boolean tests, - VirtualFile script, - GroovyScriptRunConfiguration configuration) throws CantRunException { - final Project project = configuration.getProject(); - String scriptParameters = configuration.getScriptParameters(); - - final GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); - if (module == null) { - throw new CantRunException("Target module is undefined"); - } - String rootProjectPath = ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY); - if (StringUtil.isEmpty(rootProjectPath)) { - throw new CantRunException(String.format("Module '%s' is not backed by gradle", module.getName())); - } - final VirtualFile gradleHome = libraryManager.getGradleHome(module, project, rootProjectPath); - if (gradleHome == null) { - throw new CantRunException("Gradle home can not be found"); + @Nullable + private static List getTasksTarget(Location location) { + if (location instanceof GradleTaskLocation gradleTaskLocation) { + return gradleTaskLocation.getTasks(); } - params.setMainClass(findMainClass(gradleHome, script, project)); - - final File[] groovyJars = GroovyConfigUtils.getGroovyAllJars(gradleHome.getPath() + "/lib/"); - if (groovyJars.length > 0) { - params.getClassPath().add(groovyJars[0].getAbsolutePath()); - } - else { - final VirtualFile groovyJar = findGroovyJar(module); - if (groovyJar != null) { - params.getClassPath().add(groovyJar); - } + PsiElement parent = location.getPsiElement(); + while (parent.getParent() != null && !(parent.getParent() instanceof PsiFile)) { + parent = parent.getParent(); } - final String userDefinedClasspath = System.getProperty("gradle.launcher.classpath"); - if (StringUtil.isNotEmpty(userDefinedClasspath)) { - params.getClassPath().add(userDefinedClasspath); + if (isCreateTaskMethod(parent)) { + final GrExpression[] arguments = ((GrMethodCallExpression)parent).getExpressionArguments(); + if (arguments.length > 0 && arguments[0] instanceof GrLiteral literal && literal.getValue() instanceof String arg0) { + return Collections.singletonList(arg0); + } } - else { - final Collection roots = libraryManager.getClassRoots(project); - if (roots != null) { - params.getClassPath().addVirtualFiles(roots); - } + else if (parent instanceof GrApplicationStatement) { + PsiElement shiftExpression = parent.getChildren()[1].getChildren()[0]; + if (GradleResolverUtil.isLShiftElement(shiftExpression)) { + PsiElement shiftiesChild = shiftExpression.getChildren()[0]; + if (shiftiesChild instanceof GrReferenceExpression) { + return Collections.singletonList(shiftiesChild.getText()); + } + else if (shiftiesChild instanceof GrMethodCallExpression) { + return Collections.singletonList(shiftiesChild.getChildren()[0].getText()); + } + } + else if (shiftExpression instanceof GrMethodCallExpression) { + return Collections.singletonList(shiftExpression.getChildren()[0].getText()); + } } - params.getVMParametersList().addParametersString(configuration.getVMParameters()); + return null; + } + private static boolean isCreateTaskMethod(PsiElement parent) { + return parent instanceof GrMethodCallExpression callExpr && PsiUtil.isMethodCall(callExpr, "createTask"); + } - params.getVMParametersList().add("-Dgradle.home=" + FileUtil.toSystemDependentName(gradleHome.getPath())); + @Override + public GroovyScriptRunner getRunner() { + return new GroovyScriptRunner() { + @Override + public boolean shouldRefreshAfterFinish() { + return true; + } + + @Override + public boolean isValidModule(@Nonnull Module module) { + GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); + return libraryManager.isGradleSdk(OrderEnumerator.orderEntries(module).getAllLibrariesAndSdkClassesRoots()); + } + + @Override + public boolean ensureRunnerConfigured( + @Nullable Module module, + RunProfile profile, + Executor executor, + final Project project + ) throws ExecutionException { + if (project != null && profile instanceof GroovyScriptRunConfiguration configuration) { + String parameters = configuration.getScriptParameters(); + if (parameters != null) { + // TODO den implement + // GradleTasksList list = GradleUtil.getToolWindowElement(GradleTasksList.class, project, + // ExternalSystemDataKeys.RECENT_TASKS_LIST); + // if (list != null) { + // ExternalSystemTaskDescriptor descriptor = new ExternalSystemTaskDescriptor(parameters, null); + // descriptor.setExecutorId(executor.getId()); + // list.setFirst(descriptor); + // GradleLocalSettings.getInstance(project).setRecentTasks(list.getModel().getTasks()); + // } + } + } + final GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); + // TODO den implement + //if (libraryManager.getGradleHome(module, project) == null) { + // int result = 0; + // int result = Messages.showOkCancelDialog( + // ExternalSystemBundle.message("gradle.run.no.sdk.text"), + // ExternalSystemBundle.message("gradle.run.no.sdk.title"), + // GradleIcons.Gradle + // ); + // if (result == 0) { + // ShowSettingsUtil.getInstance().editConfigurable(project, new AbstractExternalProjectConfigurable(project)); + // } + // if (libraryManager.getGradleHome(module, project) == null) { + // return false; + // } + // } + return true; + } + + @Override + public void configureCommandLine( + OwnJavaParameters params, + @Nullable Module module, + boolean tests, + VirtualFile script, + GroovyScriptRunConfiguration configuration + ) throws CantRunException { + final Project project = configuration.getProject(); + String scriptParameters = configuration.getScriptParameters(); + + final GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); + if (module == null) { + throw new CantRunException("Target module is undefined"); + } + String rootProjectPath = + ExternalSystemApiUtil.getExtensionSystemOption(module, ExternalSystemConstants.ROOT_PROJECT_PATH_KEY); + if (StringUtil.isEmpty(rootProjectPath)) { + throw new CantRunException(String.format("Module '%s' is not backed by gradle", module.getName())); + } + final VirtualFile gradleHome = libraryManager.getGradleHome(module, project, rootProjectPath); + if (gradleHome == null) { + throw new CantRunException("Gradle home can not be found"); + } + + params.setMainClass(findMainClass(gradleHome, script, project)); + + final File[] groovyJars = GroovyConfigUtils.getGroovyAllJars(gradleHome.getPath() + "/lib/"); + if (groovyJars.length > 0) { + params.getClassPath().add(groovyJars[0].getAbsolutePath()); + } + else { + final VirtualFile groovyJar = findGroovyJar(module); + if (groovyJar != null) { + params.getClassPath().add(groovyJar); + } + } + + final String userDefinedClasspath = System.getProperty("gradle.launcher.classpath"); + if (StringUtil.isNotEmpty(userDefinedClasspath)) { + params.getClassPath().add(userDefinedClasspath); + } + else { + final Collection roots = libraryManager.getClassRoots(project); + if (roots != null) { + params.getClassPath().addVirtualFiles(roots); + } + } + + params.getVMParametersList().addParametersString(configuration.getVMParameters()); + + + params.getVMParametersList().add("-Dgradle.home=" + FileUtil.toSystemDependentName(gradleHome.getPath())); + + setToolsJar(params); + + final String scriptPath = configuration.getScriptPath(); + if (scriptPath == null) { + throw new CantRunException("Target script is undefined"); + } + params.getProgramParametersList().add("--build-file"); + params.getProgramParametersList().add(FileUtil.toSystemDependentName(scriptPath)); + params.getProgramParametersList().addParametersString(configuration.getProgramParameters()); + params.getProgramParametersList().addParametersString(scriptParameters); + } + }; + } - setToolsJar(params); + @Nonnull + private static String findMainClass(VirtualFile gradleHome, VirtualFile script, Project project) { + final String userDefined = System.getProperty("gradle.launcher.class"); + if (StringUtil.isNotEmpty(userDefined)) { + return userDefined; + } - final String scriptPath = configuration.getScriptPath(); - if (scriptPath == null) { - throw new CantRunException("Target script is undefined"); + VirtualFile launcher = gradleHome.findFileByRelativePath("bin/gradle"); + if (launcher == null) { + launcher = gradleHome.findFileByRelativePath("bin/gradle.bat"); + } + if (launcher != null) { + try { + final String text = StringUtil.convertLineSeparators(VfsUtilCore.loadText(launcher)); + final Matcher matcher = MAIN_CLASS_NAME_PATTERN.matcher(text); + if (matcher.find()) { + String candidate = matcher.group(1); + if (StringUtil.isNotEmpty(candidate)) { + return candidate; + } + } + } + catch (IOException ignored) { + } } - params.getProgramParametersList().add("--build-file"); - params.getProgramParametersList().add(FileUtil.toSystemDependentName(scriptPath)); - params.getProgramParametersList().addParametersString(configuration.getProgramParameters()); - params.getProgramParametersList().addParametersString(scriptParameters); - } - }; - } - - @Nonnull - private static String findMainClass(VirtualFile gradleHome, VirtualFile script, Project project) { - final String userDefined = System.getProperty("gradle.launcher.class"); - if (StringUtil.isNotEmpty(userDefined)) { - return userDefined; - } - VirtualFile launcher = gradleHome.findFileByRelativePath("bin/gradle"); - if (launcher == null) { - launcher = gradleHome.findFileByRelativePath("bin/gradle.bat"); - } - if (launcher != null) { - try { - final String text = StringUtil.convertLineSeparators(VfsUtilCore.loadText(launcher)); - final Matcher matcher = MAIN_CLASS_NAME_PATTERN.matcher(text); - if (matcher.find()) { - String candidate = matcher.group(1); - if (StringUtil.isNotEmpty(candidate)) { - return candidate; - } + final PsiFile grFile = PsiManager.getInstance(project).findFile(script); + if (grFile != null && JavaPsiFacade.getInstance(project).findClass("org.gradle.BootstrapMain", grFile.getResolveScope()) != null) { + return "org.gradle.BootstrapMain"; } - } - catch (IOException ignored) { - } - } - final PsiFile grFile = PsiManager.getInstance(project).findFile(script); - if (grFile != null && JavaPsiFacade.getInstance(project).findClass("org.gradle.BootstrapMain", grFile.getResolveScope()) != null) { - return "org.gradle.BootstrapMain"; + return "org.gradle.launcher.GradleMain"; } - return "org.gradle.launcher.GradleMain"; - } - - @Override - public GlobalSearchScope patchResolveScope(@Nonnull GroovyFile file, @Nonnull GlobalSearchScope baseScope) { - if (!FileUtil.extensionEquals(file.getName(), GradleConstants.EXTENSION)) { - return baseScope; - } + @Override + public GlobalSearchScope patchResolveScope(@Nonnull GroovyFile file, @Nonnull GlobalSearchScope baseScope) { + if (!FileUtil.extensionEquals(file.getName(), GradleConstants.EXTENSION)) { + return baseScope; + } - final Module module = ModuleUtilCore.findModuleForPsiElement(file); - if (module == null) { - return GlobalSearchScope.EMPTY_SCOPE; - } + final Module module = ModuleUtilCore.findModuleForPsiElement(file); + if (module == null) { + return GlobalSearchScope.EMPTY_SCOPE; + } - Project project = module.getProject(); - GlobalSearchScope result = GlobalSearchScope.EMPTY_SCOPE; - for (OrderEntry entry : ModuleRootManager.getInstance(module).getOrderEntries()) { - if (entry instanceof ModuleExtensionWithSdkOrderEntry) { - GlobalSearchScope scopeForSdk = LibraryScopeCache.getInstance(project).getScopeForSdk((ModuleExtensionWithSdkOrderEntry) - entry); - result = result.uniteWith(scopeForSdk); - } - } + Project project = module.getProject(); + GlobalSearchScope result = GlobalSearchScope.EMPTY_SCOPE; + for (OrderEntry entry : ModuleRootManager.getInstance(module).getOrderEntries()) { + if (entry instanceof ModuleExtensionWithSdkOrderEntry) { + GlobalSearchScope scopeForSdk = LibraryScopeCache.getInstance(project).getScopeForSdk((ModuleExtensionWithSdkOrderEntry) + entry); + result = result.uniteWith(scopeForSdk); + } + } - String modulePath = ExternalSystemApiUtil.getExternalProjectPath(module); - if (modulePath == null) { - return result; - } + String modulePath = ExternalSystemApiUtil.getExternalProjectPath(module); + if (modulePath == null) { + return result; + } - final Collection files = GradleBuildClasspathManager.getInstance(project).getModuleClasspathEntries(modulePath); + final Collection files = GradleBuildClasspathManager.getInstance(project).getModuleClasspathEntries(modulePath); - result = new ExternalModuleBuildGlobalSearchScope(project, result.uniteWith(new NonClasspathDirectoriesScope(files)), modulePath); + result = new ExternalModuleBuildGlobalSearchScope(project, result.uniteWith(new NonClasspathDirectoriesScope(files)), modulePath); - return result; - } + return result; + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptTypeDetector.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptTypeDetector.java index 9eaa3df..37543a0 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptTypeDetector.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptTypeDetector.java @@ -27,12 +27,12 @@ */ @ExtensionImpl public class GradleScriptTypeDetector extends GroovyScriptTypeDetector { - public GradleScriptTypeDetector() { - super(GradleScriptType.INSTANCE); - } + public GradleScriptTypeDetector() { + super(GradleScriptType.INSTANCE); + } - @Override - public boolean isSpecificScriptFile(@Nonnull GroovyFile script) { - return GradleConstants.EXTENSION.equals(script.getViewProvider().getVirtualFile().getExtension()); - } + @Override + public boolean isSpecificScriptFile(@Nonnull GroovyFile script) { + return GradleConstants.EXTENSION.equals(script.getViewProvider().getVirtualFile().getExtension()); + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java index 8b093b5..f69cee8 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java @@ -13,22 +13,21 @@ * @since 3/13/12 3:53 PM */ public abstract class GradleSettingsListenerAdapter extends ExternalSystemSettingsListenerAdapter - implements GradleSettingsListener -{ + implements GradleSettingsListener { - @Override - public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @Nonnull String linkedProjectPath) { - } + @Override + public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @Nonnull String linkedProjectPath) { + } - @Override - public void onGradleDistributionTypeChange(DistributionType currentValue, @Nonnull String linkedProjectPath) { - } + @Override + public void onGradleDistributionTypeChange(DistributionType currentValue, @Nonnull String linkedProjectPath) { + } - @Override - public void onServiceDirectoryPathChange(@Nullable String oldPath, @Nullable String newPath) { - } + @Override + public void onServiceDirectoryPathChange(@Nullable String oldPath, @Nullable String newPath) { + } - @Override - public void onGradleVmOptionsChange(@Nullable String oldOptions, @Nullable String newOptions) { - } + @Override + public void onGradleVmOptionsChange(@Nullable String oldOptions, @Nullable String newOptions) { + } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java index d6a52b7..c820b98 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java @@ -28,33 +28,32 @@ * *

* Not thread-safe. - * + * * @author Denis Zhdanov * @since 12/26/11 5:19 PM */ public abstract class GradleToolWindowPanel extends SimpleToolWindowPanel { + private static final String NON_LINKED_CARD_NAME = "NON_LINKED"; + private static final String CONTENT_CARD_NAME = "CONTENT"; + private static final String TOOL_WINDOW_TOOLBAR_ID = "Gradle.ChangeActionsToolbar"; - private static final String NON_LINKED_CARD_NAME = "NON_LINKED"; - private static final String CONTENT_CARD_NAME = "CONTENT"; - private static final String TOOL_WINDOW_TOOLBAR_ID = "Gradle.ChangeActionsToolbar"; + /** Show info control when no gradle project is linked, using {@link CardLayout} for that. */ + private final CardLayout myLayout = new CardLayout(); + /** Top-level container, managed by the card layout. */ + private final JPanel myContent = new JPanel(myLayout); - /** Show info control when no gradle project is linked, using {@link CardLayout} for that. */ - private final CardLayout myLayout = new CardLayout(); - /** Top-level container, managed by the card layout. */ - private final JPanel myContent = new JPanel(myLayout); + private final Project myProject; + private final String myPlace; - private final Project myProject; - private final String myPlace; + protected GradleToolWindowPanel(@Nonnull Project project, @Nonnull String place) { + super(true); + myProject = project; + myPlace = place; + setContent(myContent); - protected GradleToolWindowPanel(@Nonnull Project project, @Nonnull String place) { - super(true); - myProject = project; - myPlace = place; - setContent(myContent); - - MessageBusConnection connection = project.getMessageBus().connect(project); - connection.subscribe(GradleSettingsListener.TOPIC, new GradleSettingsListenerAdapter() { - // TODO den implement + MessageBusConnection connection = project.getMessageBus().connect(project); + connection.subscribe(GradleSettingsListener.TOPIC, new GradleSettingsListenerAdapter() { + // TODO den implement // @Override public void onLinkedProjectConfigChange(@Nullable String oldPath, @Nullable String newPath) { // if (StringUtil.isEmpty(newPath)) { // myLayout.show(myContent, NON_LINKED_CARD_NAME); @@ -64,77 +63,77 @@ protected GradleToolWindowPanel(@Nonnull Project project, @Nonnull String place) // myLayout.show(myContent, CONTENT_CARD_NAME); // } // } - }); - } + }); + } - public void initContent() { - final ActionManager actionManager = ActionManager.getInstance(); - final ActionGroup actionGroup = (ActionGroup)actionManager.getAction(TOOL_WINDOW_TOOLBAR_ID); - ActionToolbar actionToolbar = actionManager.createActionToolbar(myPlace, actionGroup, true); - JPanel toolbarControl = new JPanel(new GridBagLayout()); - GridBagConstraints constraints = new GridBagConstraints(); - constraints.gridwidth = GridBagConstraints.REMAINDER; - constraints.weightx = 1; - constraints.fill = GridBagConstraints.HORIZONTAL; - constraints.anchor = GridBagConstraints.WEST; - toolbarControl.add(actionToolbar.getComponent(), constraints); - for (JComponent component : getToolbarControls()) { - component.setBorder(IdeBorderFactory.createBorder(SideBorder.TOP)); - toolbarControl.add(component, constraints); + public void initContent() { + final ActionManager actionManager = ActionManager.getInstance(); + final ActionGroup actionGroup = (ActionGroup)actionManager.getAction(TOOL_WINDOW_TOOLBAR_ID); + ActionToolbar actionToolbar = actionManager.createActionToolbar(myPlace, actionGroup, true); + JPanel toolbarControl = new JPanel(new GridBagLayout()); + GridBagConstraints constraints = new GridBagConstraints(); + constraints.gridwidth = GridBagConstraints.REMAINDER; + constraints.weightx = 1; + constraints.fill = GridBagConstraints.HORIZONTAL; + constraints.anchor = GridBagConstraints.WEST; + toolbarControl.add(actionToolbar.getComponent(), constraints); + for (JComponent component : getToolbarControls()) { + component.setBorder(IdeBorderFactory.createBorder(SideBorder.TOP)); + toolbarControl.add(component, constraints); + } + setToolbar(toolbarControl); + + final JComponent payloadControl = buildContent(); + JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(payloadControl); + JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); + scrollBar.setUnitIncrement(scrollBar.getUnitIncrement() * 7); + myContent.add(scrollPane, CONTENT_CARD_NAME); + RichTextControlBuilder builder = new RichTextControlBuilder(); + builder.setBackgroundColor(payloadControl.getBackground()); + builder.setForegroundColor(UIUtil.getInactiveTextColor()); + builder.setFont(payloadControl.getFont()); + builder.setText(GradleBundle.message("gradle.toolwindow.text.no.linked.project")); + final JComponent noLinkedProjectControl = builder.build(); + myContent.add(noLinkedProjectControl, NON_LINKED_CARD_NAME); + update(); } - setToolbar(toolbarControl); - - final JComponent payloadControl = buildContent(); - JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(payloadControl); - JScrollBar scrollBar = scrollPane.getVerticalScrollBar(); - scrollBar.setUnitIncrement(scrollBar.getUnitIncrement() * 7); - myContent.add(scrollPane, CONTENT_CARD_NAME); - RichTextControlBuilder builder = new RichTextControlBuilder(); - builder.setBackgroundColor(payloadControl.getBackground()); - builder.setForegroundColor(UIUtil.getInactiveTextColor()); - builder.setFont(payloadControl.getFont()); - builder.setText(GradleBundle.message("gradle.toolwindow.text.no.linked.project")); - final JComponent noLinkedProjectControl = builder.build(); - myContent.add(noLinkedProjectControl, NON_LINKED_CARD_NAME); - update(); - } - /** - * @return list of UI controls to be displayed vertically at the toolbar - */ - @Nonnull - protected List getToolbarControls() { - return Collections.emptyList(); - } - - /** - * Asks current control to update its state. - */ - public void update() { - final GradleSettings settings = GradleSettings.getInstance(myProject); - // TODO den implement - String cardToShow = "sf"; + /** + * @return list of UI controls to be displayed vertically at the toolbar + */ + @Nonnull + protected List getToolbarControls() { + return Collections.emptyList(); + } + + /** + * Asks current control to update its state. + */ + public void update() { + final GradleSettings settings = GradleSettings.getInstance(myProject); + // TODO den implement + String cardToShow = "sf"; // String cardToShow = StringUtil.isEmpty(settings.getLinkedExternalProjectPath()) ? NON_LINKED_CARD_NAME : CONTENT_CARD_NAME; - myLayout.show(myContent, cardToShow); - boolean showToolbar = cardToShow != NON_LINKED_CARD_NAME; - for (JComponent component : getToolbarControls()) { - component.setVisible(showToolbar); + myLayout.show(myContent, cardToShow); + boolean showToolbar = cardToShow != NON_LINKED_CARD_NAME; + for (JComponent component : getToolbarControls()) { + component.setVisible(showToolbar); + } + } + + @Nonnull + public Project getProject() { + return myProject; } - } - @Nonnull - public Project getProject() { - return myProject; - } + /** + * @return GUI control to be displayed at the current tab + */ + @Nonnull + protected abstract JComponent buildContent(); - /** - * @return GUI control to be displayed at the current tab - */ - @Nonnull - protected abstract JComponent buildContent(); - - /** - * Callback for asking content control to update its state. - */ - protected abstract void updateContent(); + /** + * Callback for asking content control to update its state. + */ + protected abstract void updateContent(); } From e2abe8e195986c054740a3fddb2d913577c7ec66 Mon Sep 17 00:00:00 2001 From: UNV Date: Fri, 9 Aug 2024 15:59:11 +0300 Subject: [PATCH 05/16] =?UTF-8?q?GradleBundle=20=E2=86=92=20GradleLocalize?= =?UTF-8?q?.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../maven/action/AddGradleDslDependencyAction.java | 6 +++--- .../action/AddGradleDslDependencyActionHandler.java | 4 ++-- .../importProvider/GradleModuleImportProvider.java | 4 ++-- .../plugins/gradle/action/GradleOpenScriptAction.java | 6 +++--- .../codeInsight/actions/AddGradleDslPluginAction.java | 10 +++++----- .../actions/AddGradleDslPluginActionHandler.java | 6 +++--- .../plugins/gradle/config/GradleToolWindowPanel.java | 4 ++-- 7 files changed, 20 insertions(+), 20 deletions(-) diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java index 26ed075..b80af3e 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java @@ -20,8 +20,8 @@ import consulo.annotation.component.ActionRef; import consulo.application.AllIcons; import consulo.codeEditor.Editor; -import consulo.gradle.GradleBundle; import consulo.gradle.GradleConstants; +import consulo.gradle.localize.GradleLocalize; import consulo.language.editor.action.CodeInsightAction; import consulo.language.editor.action.CodeInsightActionHandler; import consulo.language.psi.PsiCompiledElement; @@ -42,8 +42,8 @@ public class AddGradleDslDependencyAction extends CodeInsightAction { static final ThreadLocal> TEST_THREAD_LOCAL = new ThreadLocal<>(); public AddGradleDslDependencyAction() { - getTemplatePresentation().setDescription(GradleBundle.message("gradle.codeInsight.action.add_maven_dependency.description")); - getTemplatePresentation().setText(GradleBundle.message("gradle.codeInsight.action.add_maven_dependency.text")); + getTemplatePresentation().setDescriptionValue(GradleLocalize.gradleCodeinsightActionAdd_maven_dependencyDescription()); + getTemplatePresentation().setTextValue(GradleLocalize.gradleCodeinsightActionAdd_maven_dependencyText()); getTemplatePresentation().setIcon(AllIcons.Nodes.PpLib); } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java index ecccabe..7110c62 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java @@ -17,7 +17,7 @@ import consulo.application.ApplicationManager; import consulo.codeEditor.Editor; -import consulo.gradle.GradleBundle; +import consulo.gradle.localize.GradleLocalize; import consulo.language.editor.WriteCommandAction; import consulo.language.editor.action.CodeInsightActionHandler; import consulo.language.editor.util.LanguageEditorUtil; @@ -63,7 +63,7 @@ public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, return; } - new WriteCommandAction.Simple(project, GradleBundle.message("gradle.codeInsight.action.add_maven_dependency.text"), file) { + new WriteCommandAction.Simple(project, GradleLocalize.gradleCodeinsightActionAdd_maven_dependencyText().get(), file) { @Override protected void run() { GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); diff --git a/plugin/src/main/java/consulo/gradle/impl/importProvider/GradleModuleImportProvider.java b/plugin/src/main/java/consulo/gradle/impl/importProvider/GradleModuleImportProvider.java index 74fdee5..1843a60 100644 --- a/plugin/src/main/java/consulo/gradle/impl/importProvider/GradleModuleImportProvider.java +++ b/plugin/src/main/java/consulo/gradle/impl/importProvider/GradleModuleImportProvider.java @@ -7,9 +7,9 @@ import consulo.externalSystem.model.DataNode; import consulo.externalSystem.service.project.ProjectData; import consulo.externalSystem.util.ExternalSystemApiUtil; -import consulo.gradle.GradleBundle; import consulo.gradle.GradleConstants; import consulo.gradle.icon.GradleIconGroup; +import consulo.gradle.localize.GradleLocalize; import consulo.ide.impl.externalSystem.service.module.wizard.AbstractExternalModuleImportProvider; import consulo.ide.impl.externalSystem.service.module.wizard.ExternalModuleImportContext; import consulo.ide.impl.idea.openapi.externalSystem.service.project.manage.ProjectDataManager; @@ -46,7 +46,7 @@ public GradleModuleImportProvider(@Nonnull ProjectDataManager dataManager) { @Nonnull @Override public String getName() { - return GradleBundle.message("gradle.name"); + return GradleLocalize.gradleName().get(); } @Nullable diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java index 2808646..cb9d9bd 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java @@ -2,6 +2,7 @@ import consulo.application.dumb.DumbAware; import consulo.fileEditor.FileEditorManager; +import consulo.gradle.localize.GradleLocalize; import consulo.logging.Logger; import consulo.navigation.OpenFileDescriptor; import consulo.navigation.OpenFileDescriptorFactory; @@ -10,7 +11,6 @@ import consulo.virtualFileSystem.LocalFileSystem; import consulo.virtualFileSystem.VirtualFile; import org.jetbrains.plugins.gradle.settings.GradleSettings; -import consulo.gradle.GradleBundle; import javax.annotation.Nonnull; @@ -26,8 +26,8 @@ public class GradleOpenScriptAction extends AbstractGradleLinkedProjectAction im private static final Logger LOG = Logger.getInstance(GradleOpenScriptAction.class); public GradleOpenScriptAction() { - getTemplatePresentation().setText(GradleBundle.message("gradle.action.open.script.text")); - getTemplatePresentation().setDescription(GradleBundle.message("gradle.action.open.script.description")); + getTemplatePresentation().setTextValue(GradleLocalize.gradleActionOpenScriptText()); + getTemplatePresentation().setDescriptionValue(GradleLocalize.gradleActionOpenScriptDescription()); } @Override diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java index c8216cd..df7ae68 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java @@ -21,6 +21,9 @@ import consulo.annotation.component.ActionRefAnchor; import consulo.application.AllIcons; import consulo.codeEditor.Editor; +import consulo.gradle.GradleConstants; +import consulo.gradle.GradleDocumentationBundle; +import consulo.gradle.localize.GradleLocalize; import consulo.language.editor.action.CodeInsightAction; import consulo.language.editor.action.CodeInsightActionHandler; import consulo.language.psi.PsiCompiledElement; @@ -29,9 +32,6 @@ import consulo.util.collection.ContainerUtil; import consulo.util.lang.Pair; import consulo.util.lang.StringUtil; -import consulo.gradle.GradleBundle; -import consulo.gradle.GradleConstants; -import consulo.gradle.GradleDocumentationBundle; import org.jetbrains.plugins.groovy.GroovyFileType; import javax.annotation.Nonnull; @@ -47,8 +47,8 @@ public class AddGradleDslPluginAction extends CodeInsightAction { private final Pair[] myPlugins; public AddGradleDslPluginAction() { - getTemplatePresentation().setDescription(GradleBundle.message("gradle.codeInsight.action.apply_plugin.description")); - getTemplatePresentation().setText(GradleBundle.message("gradle.codeInsight.action.apply_plugin.text")); + getTemplatePresentation().setDescriptionValue(GradleLocalize.gradleCodeinsightActionApply_pluginDescription()); + getTemplatePresentation().setTextValue(GradleLocalize.gradleCodeinsightActionApply_pluginText()); getTemplatePresentation().setIcon(AllIcons.Nodes.Plugin); final List plugins = StringUtil.split( diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java index 1c386cc..40ae8b5 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java @@ -21,6 +21,7 @@ import consulo.colorScheme.EditorColorsScheme; import consulo.colorScheme.EditorFontType; import consulo.document.Document; +import consulo.gradle.localize.GradleLocalize; import consulo.language.editor.WriteCommandAction; import consulo.language.editor.action.CodeInsightActionHandler; import consulo.language.editor.util.LanguageEditorUtil; @@ -34,7 +35,6 @@ import consulo.ui.ex.popup.JBPopup; import consulo.ui.ex.popup.JBPopupFactory; import consulo.util.lang.Pair; -import consulo.gradle.GradleBundle; import org.jetbrains.plugins.groovy.lang.psi.GroovyFile; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement; @@ -64,7 +64,7 @@ public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, } Consumer runnable = - selected -> new WriteCommandAction.Simple(project, GradleBundle.message("gradle.codeInsight.action.apply_plugin.text"), file) { + selected -> new WriteCommandAction.Simple(project, GradleLocalize.gradleCodeinsightActionApply_pluginText().get(), file) { @Override protected void run() { if (selected == null) { @@ -93,7 +93,7 @@ protected void run() { }.execute(); JBPopup popup = JBPopupFactory.getInstance().createPopupChooserBuilder(List.of(myPlugins)) - .setTitle(GradleBundle.message("gradle.codeInsight.action.apply_plugin.popup.title")) + .setTitle(GradleLocalize.gradleCodeinsightActionApply_pluginPopupTitle().get()) .setNamerForFiltering(pair -> String.valueOf(pair.getFirst())) .setItemChosenCallback(runnable) .setRenderer(new ColoredListCellRenderer>() { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java index c820b98..84f5d29 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java @@ -1,6 +1,7 @@ package org.jetbrains.plugins.gradle.config; import consulo.component.messagebus.MessageBusConnection; +import consulo.gradle.localize.GradleLocalize; import consulo.project.Project; import consulo.ui.ex.action.ActionGroup; import consulo.ui.ex.action.ActionManager; @@ -9,7 +10,6 @@ import org.jetbrains.plugins.gradle.settings.GradleSettings; import org.jetbrains.plugins.gradle.settings.GradleSettingsListener; import org.jetbrains.plugins.gradle.ui.RichTextControlBuilder; -import consulo.gradle.GradleBundle; import javax.annotation.Nonnull; import javax.swing.*; @@ -92,7 +92,7 @@ public void initContent() { builder.setBackgroundColor(payloadControl.getBackground()); builder.setForegroundColor(UIUtil.getInactiveTextColor()); builder.setFont(payloadControl.getFont()); - builder.setText(GradleBundle.message("gradle.toolwindow.text.no.linked.project")); + builder.setText(GradleLocalize.gradleToolwindowTextNoLinkedProject().get()); final JComponent noLinkedProjectControl = builder.build(); myContent.add(noLinkedProjectControl, NON_LINKED_CARD_NAME); update(); From df33aa476e1029e157be582fb32bd7767e578be2 Mon Sep 17 00:00:00 2001 From: UNV Date: Fri, 9 Aug 2024 20:50:15 +0300 Subject: [PATCH 06/16] Refactoring to reduce number of inspection warnings. --- .../maven/ImportMavenRepositoriesTask.java | 31 ++++--- .../action/AddGradleDslDependencyAction.java | 10 ++- .../AddGradleDslDependencyActionHandler.java | 16 ++-- ...pendenciesGradleCompletionContributor.java | 51 +++++------ .../AbstractGradleLinkedProjectAction.java | 6 +- .../gradle/action/GradleOpenScriptAction.java | 2 +- .../action/GradleToolWindowHelpAction.java | 2 + ...butionWithSourcesNotificationProvider.java | 88 +++++++++++-------- .../actions/AddGradleDslPluginAction.java | 30 ++++--- .../AddGradleDslPluginActionHandler.java | 60 +++++++------ .../MultipleRepositoryUrlsFix.java | 2 + .../MultipleRepositoryUrlsInspection.java | 3 + .../gradle/config/GradlePositionManager.java | 21 ++++- .../gradle/config/GradleScriptType.java | 28 +++--- 14 files changed, 208 insertions(+), 142 deletions(-) diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java index a28bab6..3a96871 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java @@ -16,6 +16,7 @@ package org.jetbrains.plugins.gradle.integrations.maven; import com.intellij.java.language.psi.PsiLiteral; +import consulo.annotation.access.RequiredReadAction; import consulo.application.ReadAction; import consulo.externalSystem.util.ExternalSystemApiUtil; import consulo.externalSystem.util.ExternalSystemConstants; @@ -51,8 +52,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.*; -import java.util.function.Consumer; -import java.util.function.Function; /** * @author Vladislav.Soroka @@ -74,6 +73,7 @@ public ImportMavenRepositoriesTask(Project project) { } @Override + @RequiredReadAction public void run() { if (myProject.isDisposed()) { return; @@ -134,19 +134,22 @@ public void run() { return; } - MavenRepositoriesHolder.getInstance(myProject).update(mavenRemoteRepositories); + MavenRepositoriesHolder repositoriesHolder = MavenRepositoriesHolder.getInstance(myProject); + MavenProjectIndicesManager projectIndicesManager = MavenProjectIndicesManager.getInstance(myProject); - MavenProjectIndicesManager.getInstance(myProject).scheduleUpdateIndicesList(indexes -> { + repositoriesHolder.update(mavenRemoteRepositories); + + projectIndicesManager.scheduleUpdateIndicesList(indexes -> { for (MavenIndex mavenIndex : indexes) { - if (mavenIndex.getUpdateTimestamp() == -1 - && MavenRepositoriesHolder.getInstance(myProject).contains(mavenIndex.getRepositoryId())) { - MavenProjectIndicesManager.getInstance(myProject).scheduleUpdate(Collections.singletonList(mavenIndex)); + if (mavenIndex.getUpdateTimestamp() == -1 && repositoriesHolder.contains(mavenIndex.getRepositoryId())) { + projectIndicesManager.scheduleUpdate(Collections.singletonList(mavenIndex)); } } }); } @Nonnull + @RequiredReadAction private static Collection findClosableBlocks( @Nonnull final PsiElement element, @Nonnull final String... blockNames @@ -160,16 +163,19 @@ private static Collection findClosableBlocks( } GrExpression expression = call.getInvokedExpression(); - return expression != null && ArrayUtil.contains(expression.getText(), blockNames) ? call.getClosureArguments()[0] : null; + //noinspection RequiredXAction + return expression != null && ArrayUtil.contains(expression.getText(), blockNames) + ? call.getClosureArguments()[0] + : null; } ); } @Nonnull + @RequiredReadAction private static Collection findMavenRemoteRepositories(@Nullable GrClosableBlock repositoriesBlock) { Set myRemoteRepositories = new HashSet<>(); - for (GrMethodCall repo : PsiTreeUtil - .getChildrenOfTypeAsList(repositoriesBlock, GrMethodCall.class)) { + for (GrMethodCall repo : PsiTreeUtil.getChildrenOfTypeAsList(repositoriesBlock, GrMethodCall.class)) { if (repo.getInvokedExpression() == null) { continue; } @@ -242,14 +248,15 @@ else if ("maven".equals(expressionText) && repo.getClosureArguments().length > 0 } @Nullable + @RequiredReadAction private static URI resolveUriFromSimpleExpression(@Nullable GrExpression expression) { if (expression == null) { return null; } try { - if (expression instanceof PsiLiteral) { - URI uri = new URI(String.valueOf(PsiLiteral.class.cast(expression).getValue())); + if (expression instanceof PsiLiteral literal) { + URI uri = new URI(String.valueOf(literal.getValue())); if (uri.getScheme() != null && StringUtil.startsWith(uri.getScheme(), "http")) { return uri; } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java index b80af3e..f54e47c 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.gradle.integrations.maven.action; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ActionImpl; import consulo.annotation.component.ActionParentRef; import consulo.annotation.component.ActionRef; @@ -54,10 +55,11 @@ protected CodeInsightActionHandler getHandler() { } @Override + @RequiredReadAction protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file) { - if (file instanceof PsiCompiledElement || !GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType())) { - return false; - } - return !GradleConstants.SETTINGS_FILE_NAME.equals(file.getName()) && file.getName().endsWith(GradleConstants.EXTENSION); + return !(file instanceof PsiCompiledElement) + && GroovyFileType.INSTANCE.equals(file.getFileType()) + && !GradleConstants.SETTINGS_FILE_NAME.equals(file.getName()) + && file.getName().endsWith(GradleConstants.EXTENSION); } } diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java index 7110c62..1edfc64 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java @@ -15,7 +15,6 @@ */ package org.jetbrains.plugins.gradle.integrations.maven.action; -import consulo.application.ApplicationManager; import consulo.codeEditor.Editor; import consulo.gradle.localize.GradleLocalize; import consulo.language.editor.WriteCommandAction; @@ -25,6 +24,7 @@ import consulo.language.psi.util.PsiTreeUtil; import consulo.maven.rt.server.common.model.MavenId; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.util.collection.ArrayUtil; import consulo.util.collection.ContainerUtil; import org.jetbrains.idea.maven.dom.model.MavenDomDependency; @@ -38,7 +38,6 @@ import javax.annotation.Nonnull; import java.util.Collections; import java.util.List; -import java.util.function.Predicate; /** * @author Vladislav.Soroka @@ -46,13 +45,14 @@ */ class AddGradleDslDependencyActionHandler implements CodeInsightActionHandler { @Override + @RequiredUIAccess public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) { if (!LanguageEditorUtil.checkModificationAllowed(editor)) { return; } final List ids; - if (ApplicationManager.getApplication().isUnitTestMode()) { + if (project.getApplication().isUnitTestMode()) { ids = AddGradleDslDependencyAction.TEST_THREAD_LOCAL.get(); } else { @@ -68,13 +68,14 @@ public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, protected void run() { GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); List closableBlocks = PsiTreeUtil.getChildrenOfTypeAsList(file, GrMethodCall.class); - GrCall dependenciesBlock = ContainerUtil.find(closableBlocks, new Predicate() { - @Override - public boolean test(GrMethodCall call) { + GrCall dependenciesBlock = ContainerUtil.find( + closableBlocks, + call -> { GrExpression expression = call.getInvokedExpression(); + //noinspection RequiredXAction return expression != null && "dependencies".equals(expression.getText()); } - }); + ); if (dependenciesBlock == null) { StringBuilder buf = new StringBuilder(); @@ -104,7 +105,6 @@ public boolean startInWriteAction() { return false; } - @Nonnull private static String getMavenArtifactKey(MavenId mavenId) { StringBuilder builder = new StringBuilder(); diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java index 2658a4c..7f905cf 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.gradle.integrations.maven.codeInsight; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.application.AllIcons; import consulo.gradle.codeInsight.AbstractGradleCompletionContributor; @@ -57,27 +58,26 @@ public class MavenDependenciesGradleCompletionContributor extends AbstractGradle private static final String VERSION_LABEL = "version"; private static final String DEPENDENCIES_SCRIPT_BLOCK = "dependencies"; - private static final ElementPattern DEPENDENCIES_CALL_PATTERN = psiElement() - .inside( - true, - psiElement(GrMethodCallExpression.class).with(new PatternCondition<>("withInvokedExpressionText") { - @Override - public boolean accepts(@Nonnull GrMethodCallExpression expression, ProcessingContext context) { - if (checkExpression(expression)) { - return true; - } - return checkExpression(PsiTreeUtil.getParentOfType(expression, GrMethodCallExpression.class)); - } + private static final ElementPattern DEPENDENCIES_CALL_PATTERN = psiElement().inside( + true, + psiElement(GrMethodCallExpression.class).with(new PatternCondition<>("withInvokedExpressionText") { + @Override + @RequiredReadAction + public boolean accepts(@Nonnull GrMethodCallExpression expression, ProcessingContext context) { + return checkExpression(expression) + || checkExpression(PsiTreeUtil.getParentOfType(expression, GrMethodCallExpression.class)); + } - private boolean checkExpression(@Nullable GrMethodCallExpression expression) { - if (expression == null) { - return false; - } - GrExpression grExpression = expression.getInvokedExpression(); - return grExpression != null && DEPENDENCIES_SCRIPT_BLOCK.equals(grExpression.getText()); + @RequiredReadAction + private boolean checkExpression(@Nullable GrMethodCallExpression expression) { + if (expression == null) { + return false; } - }) - ); + GrExpression grExpression = expression.getInvokedExpression(); + return grExpression != null && DEPENDENCIES_SCRIPT_BLOCK.equals(grExpression.getText()); + } + }) + ); private static final ElementPattern IN_MAP_DEPENDENCY_NOTATION = psiElement() .and(AbstractGradleCompletionContributor.GRADLE_FILE_PATTERN) @@ -95,13 +95,10 @@ public MavenDependenciesGradleCompletionContributor() { // compile group: 'com.google.code.guice', name: 'guice', version: '1.0' // runtime([group:'junit', name:'junit-dep', version:'4.7']) // compile(group:'junit', name:'junit-dep', version:'4.7') - extend(CompletionType.BASIC, IN_MAP_DEPENDENCY_NOTATION, new CompletionProvider() { - @Override - public void addCompletions( - @Nonnull CompletionParameters params, - ProcessingContext context, - @Nonnull final CompletionResultSet result - ) { + extend( + CompletionType.BASIC, + IN_MAP_DEPENDENCY_NOTATION, + (params, context, result) -> { result.stopHere(); final PsiElement parent = params.getPosition().getParent().getParent(); @@ -149,7 +146,7 @@ else if (VERSION_LABEL.equals(namedArgument.getLabelName())) { } } } - }); + ); // group:name:version notation // e.g.: diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java index 6b7399f..68a5386 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java @@ -1,8 +1,8 @@ package org.jetbrains.plugins.gradle.action; import consulo.dataContext.DataContext; -import consulo.language.editor.CommonDataKeys; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.action.AnAction; import consulo.ui.ex.action.AnActionEvent; import consulo.util.lang.Pair; @@ -21,6 +21,7 @@ */ public abstract class AbstractGradleLinkedProjectAction extends AnAction { @Override + @RequiredUIAccess public void update(AnActionEvent e) { final Pair pair = deriveProjects(e.getDataContext()); final boolean visible = pair != null; @@ -32,6 +33,7 @@ public void update(AnActionEvent e) { } @Override + @RequiredUIAccess public void actionPerformed(AnActionEvent e) { final Project project = e.getData(Project.KEY); if (project == null) { @@ -51,7 +53,7 @@ private static Pair deriveProjects(@Nullable DataContext contex return null; } - final Project project = context.getData(CommonDataKeys.PROJECT); + final Project project = context.getData(Project.KEY); if (project == null) { return null; } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java index cb9d9bd..b3b43d3 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java @@ -15,7 +15,7 @@ import javax.annotation.Nonnull; /** - * Forces the IntelliJ IDEA to open {@link GradleSettings#getLinkedExternalProjectPath() linked gradle project} at the editor + * Forces the Consulo to open {@link GradleSettings#getLinkedExternalProjectPath() linked gradle project} at the editor *

* Not thread-safe. * diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java index 1375f0e..b5d0e5f 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java @@ -2,6 +2,7 @@ import consulo.dataContext.DataContext; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.action.AnActionEvent; import consulo.ui.ex.action.ContextHelpAction; import consulo.gradle.GradleConstants; @@ -12,6 +13,7 @@ */ public class GradleToolWindowHelpAction extends ContextHelpAction { @Override + @RequiredUIAccess public void update(AnActionEvent event) { final Project project = event.getData(Project.KEY); if (project == null) { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java index c1ef086..fbdb2f1 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java @@ -122,44 +122,58 @@ public EditorNotificationBuilder buildNotification( final EditorNotificationBuilder panel = supplier.get(); panel.withText(GradleLocalize.gradleNotificationsUseDistributionWithSources()); - panel.withAction(GradleLocalize.gradleNotificationsHideTip(), (e) -> - { - settings.setDisableWrapperSourceDistributionNotification(true); - EditorNotifications.getInstance(module.getProject()).updateAllNotifications(); - }); - panel.withAction(GradleLocalize.gradleNotificationsApplySuggestion(), (e) -> - { - updateDefaultWrapperConfiguration(rootProjectPath); - EditorNotifications.getInstance(module.getProject()).updateAllNotifications(); - final ProjectDataManager projectDataManager = ServiceManager.getService(ProjectDataManager.class); - ExternalSystemUtil.refreshProject(module.getProject(), GradleConstants.SYSTEM_ID, settings.getExternalProjectPath(), new - ExternalProjectRefreshCallback() { - @Override - public void onSuccess(@Nullable final DataNode externalProject) { - if (externalProject == null) { - return; - } - ExternalSystemApiUtil.executeProjectChangeAction(true, new DisposeAwareProjectChange(module.getProject()) { - @RequiredUIAccess - @Override - public void execute() { - ProjectRootManager.getInstance(module.getProject()).mergeRootsChangesDuring( - () -> projectDataManager.importData( - externalProject.getKey(), - Collections.singleton(externalProject), - module.getProject(), - true - ) - ); + panel.withAction( + GradleLocalize.gradleNotificationsHideTip(), + e -> { + settings.setDisableWrapperSourceDistributionNotification(true); + EditorNotifications.getInstance(module.getProject()).updateAllNotifications(); + } + ); + panel.withAction( + GradleLocalize.gradleNotificationsApplySuggestion(), + e -> { + updateDefaultWrapperConfiguration(rootProjectPath); + final Project project = module.getProject(); + EditorNotifications.getInstance(project).updateAllNotifications(); + final ProjectDataManager projectDataManager = project.getInstance(ProjectDataManager.class); + ExternalSystemUtil.refreshProject( + project, + GradleConstants.SYSTEM_ID, + settings.getExternalProjectPath(), + new ExternalProjectRefreshCallback() { + @Override + public void onSuccess(@Nullable final DataNode externalProject) { + if (externalProject == null) { + return; } - }); - } - - @Override - public void onFailure(@Nonnull String errorMessage, @Nullable String errorDetails) { - } - }, true, ProgressExecutionMode.START_IN_FOREGROUND_ASYNC); - }); + ExternalSystemApiUtil.executeProjectChangeAction( + true, + new DisposeAwareProjectChange(project) { + @RequiredUIAccess + @Override + public void execute() { + ProjectRootManager.getInstance(project).mergeRootsChangesDuring( + () -> projectDataManager.importData( + externalProject.getKey(), + Collections.singleton(externalProject), + project, + true + ) + ); + } + } + ); + } + + @Override + public void onFailure(@Nonnull String errorMessage, @Nullable String errorDetails) { + } + }, + true, + ProgressExecutionMode.START_IN_FOREGROUND_ASYNC + ); + } + ); return panel; } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java index df7ae68..281d0d5 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.gradle.codeInsight.actions; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ActionImpl; import consulo.annotation.component.ActionParentRef; import consulo.annotation.component.ActionRef; @@ -30,6 +31,7 @@ import consulo.language.psi.PsiFile; import consulo.project.Project; import consulo.util.collection.ContainerUtil; +import consulo.util.lang.Couple; import consulo.util.lang.Pair; import consulo.util.lang.StringUtil; import org.jetbrains.plugins.groovy.GroovyFileType; @@ -42,7 +44,10 @@ * @author Vladislav.Soroka * @since 10/22/13 */ -@ActionImpl(id = "AddGradleDslPluginAction", parents = @ActionParentRef(value = @ActionRef(id = "GenerateGroup"), anchor = ActionRefAnchor.FIRST)) +@ActionImpl( + id = "AddGradleDslPluginAction", + parents = @ActionParentRef(value = @ActionRef(id = "GenerateGroup"), anchor = ActionRefAnchor.FIRST) +) public class AddGradleDslPluginAction extends CodeInsightAction { private final Pair[] myPlugins; @@ -53,10 +58,12 @@ public AddGradleDslPluginAction() { final List plugins = StringUtil.split( "java,groovy,idea,eclipse,scala,antlr,application,ear,jetty,maven,osgi,war,announce," + - "build-announcements,checkstyle,codenarc,eclipse-wtp,findbugs,jdepend,pmd,project-report,signing,sonar", ","); + "build-announcements,checkstyle,codenarc,eclipse-wtp,findbugs,jdepend,pmd,project-report,signing,sonar", + "," + ); myPlugins = new Pair[plugins.size()]; - ContainerUtil.map2Array(plugins, myPlugins, o -> createPluginKey(o)); + ContainerUtil.map2Array(plugins, myPlugins, AddGradleDslPluginAction::createPluginKey); Arrays.sort(myPlugins, (o1, o2) -> String.valueOf(o1.getFirst()).compareTo(String.valueOf(o2.getFirst()))); } @@ -67,17 +74,20 @@ protected CodeInsightActionHandler getHandler() { } @Override + @RequiredReadAction protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull PsiFile file) { - if (file instanceof PsiCompiledElement || !GroovyFileType.GROOVY_FILE_TYPE.equals(file.getFileType())) { - return false; - } - return !GradleConstants.SETTINGS_FILE_NAME.equals(file.getName()) && file.getName().endsWith(GradleConstants.EXTENSION); + return !(file instanceof PsiCompiledElement) + && GroovyFileType.INSTANCE.equals(file.getFileType()) + && !GradleConstants.SETTINGS_FILE_NAME.equals(file.getName()) + && file.getName().endsWith(GradleConstants.EXTENSION); } @Nonnull - private static Pair createPluginKey(@Nonnull String pluginName) { + private static Couple createPluginKey(@Nonnull String pluginName) { String description = GradleDocumentationBundle.messageOrDefault( - String.format("gradle.documentation.org.gradle.api.Project.apply.plugin.%s.non-html", pluginName), ""); - return Pair.create(pluginName, description); + String.format("gradle.documentation.org.gradle.api.Project.apply.plugin.%s.non-html", pluginName), + "" + ); + return Couple.of(pluginName, description); } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java index 40ae8b5..7062922 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.gradle.codeInsight.actions; +import consulo.annotation.access.RequiredReadAction; import consulo.codeEditor.Editor; import consulo.codeEditor.EditorPopupHelper; import consulo.colorScheme.EditorColorsManager; @@ -30,6 +31,7 @@ import consulo.language.psi.PsiFile; import consulo.language.psi.util.PsiTreeUtil; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.ex.SimpleTextAttributes; import consulo.ui.ex.awt.ColoredListCellRenderer; import consulo.ui.ex.popup.JBPopup; @@ -58,46 +60,50 @@ public AddGradleDslPluginActionHandler(Pair[] plugins) { } @Override + @RequiredUIAccess public void invoke(@Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) { if (!LanguageEditorUtil.checkModificationAllowed(editor)) { return; } - Consumer runnable = - selected -> new WriteCommandAction.Simple(project, GradleLocalize.gradleCodeinsightActionApply_pluginText().get(), file) { - @Override - protected void run() { - if (selected == null) { - return; - } - GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); - GrStatement grStatement = factory.createStatementFromText( - String.format("apply plugin: '%s'", selected.getFirst()), - null - ); + Consumer runnable = selected -> new WriteCommandAction.Simple( + project, + GradleLocalize.gradleCodeinsightActionApply_pluginText().get(), + file + ) { + @Override + @RequiredReadAction + protected void run() { + if (selected == null) { + return; + } + GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project); + GrStatement grStatement = factory.createStatementFromText( + String.format("apply plugin: '%s'", selected.getFirst()), + null + ); - PsiElement anchor = file.findElementAt(editor.getCaretModel().getOffset()); - PsiElement currentElement = PsiTreeUtil.getParentOfType(anchor, GrClosableBlock.class, GroovyFile.class); - if (currentElement != null) { - currentElement.addAfter(grStatement, anchor); - } - else { - file.addAfter(grStatement, file.findElementAt(editor.getCaretModel().getOffset() - 1)); - } - PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); - Document document = documentManager.getDocument(file); - if (document != null) { - documentManager.commitDocument(document); - } + PsiElement anchor = file.findElementAt(editor.getCaretModel().getOffset()); + PsiElement currentElement = PsiTreeUtil.getParentOfType(anchor, GrClosableBlock.class, GroovyFile.class); + if (currentElement != null) { + currentElement.addAfter(grStatement, anchor); + } + else { + file.addAfter(grStatement, file.findElementAt(editor.getCaretModel().getOffset() - 1)); } - }.execute(); + PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project); + Document document = documentManager.getDocument(file); + if (document != null) { + documentManager.commitDocument(document); + } + } + }.execute(); JBPopup popup = JBPopupFactory.getInstance().createPopupChooserBuilder(List.of(myPlugins)) .setTitle(GradleLocalize.gradleCodeinsightActionApply_pluginPopupTitle().get()) .setNamerForFiltering(pair -> String.valueOf(pair.getFirst())) .setItemChosenCallback(runnable) .setRenderer(new ColoredListCellRenderer>() { - @Override protected void customizeCellRenderer( @Nonnull JList> list, diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java index c2e0c8c..ea71f1a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.gradle.codeInspection; +import consulo.annotation.access.RequiredWriteAction; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; @@ -44,6 +45,7 @@ public MultipleRepositoryUrlsFix(@Nonnull GrClosableBlock closure, @Nonnull Stri } @Override + @RequiredWriteAction protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException { List statements = MultipleRepositoryUrlsInspection.findUrlCallExpressions(myClosure); if (statements.size() <= 1) { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java index 4c85b66..d88f4e4 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.gradle.codeInspection; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemHighlightType; @@ -75,6 +76,7 @@ public String getDisplayName() { private static class MyVisitor extends BaseInspectionVisitor { @Override + @RequiredReadAction public void visitClosure(GrClosableBlock closure) { PsiFile file = closure.getContainingFile(); if (file == null || !FileUtil.extensionEquals(file.getName(), GradleConstants.EXTENSION)) { @@ -114,6 +116,7 @@ public void visitClosure(GrClosableBlock closure) { } @Nonnull + @RequiredReadAction static List findUrlCallExpressions(@Nonnull GrClosableBlock closure) { GrCallExpression[] applicationStatements = PsiTreeUtil.getChildrenOfType(closure, GrCallExpression.class); if (applicationStatements == null) { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePositionManager.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePositionManager.java index 1530dac..471bbb5 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePositionManager.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePositionManager.java @@ -15,6 +15,7 @@ */ package org.jetbrains.plugins.gradle.config; +import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; import consulo.application.util.*; import consulo.externalSystem.util.ExternalSystemApiUtil; @@ -71,15 +72,19 @@ public GradlePositionManager(@Nonnull GradleInstallationManager manager) { myLibraryManager = manager; } + @Override public boolean isAppropriateRuntimeName(@Nonnull final String runtimeName) { return runtimeName.startsWith(SCRIPT_CLOSURE_PREFIX) || GRADLE_CLASS_PATTERN.matcher(runtimeName).matches(); } + @Override public boolean isAppropriateScriptFile(@Nonnull final GroovyFile scriptFile) { - return GroovyScriptUtil.isSpecificScriptFile((GroovyFile)scriptFile, GradleScriptType.INSTANCE); + return GroovyScriptUtil.isSpecificScriptFile(scriptFile, GradleScriptType.INSTANCE); } @Nonnull + @Override + @RequiredReadAction public String getRuntimeScriptName(GroovyFile groovyFile) { VirtualFile virtualFile = groovyFile.getVirtualFile(); if (virtualFile == null) { @@ -97,7 +102,14 @@ public String getRuntimeScriptName(GroovyFile groovyFile) { return className == null ? "" : className; } - public PsiFile getExtraScriptIfNotFound(ReferenceType refType, @Nonnull String runtimeName, Project project, GlobalSearchScope scope) { + @Override + @RequiredReadAction + public PsiFile getExtraScriptIfNotFound( + @Nonnull ReferenceType refType, + @Nonnull String runtimeName, + @Nonnull Project project, + @Nonnull GlobalSearchScope scope + ) { String sourceFilePath = getScriptForClassName(refType); if (sourceFilePath == null) { return null; @@ -130,7 +142,7 @@ private ClassLoader getGradleClassLoader(@Nonnull final Module module) { return CachedValuesManager.getManager(project).getCachedValue( module, GRADLE_CLASS_LOADER, - ()-> CachedValueProvider.Result.create(createGradleClassLoader(module), ProjectRootManager.getInstance(project)), + () -> CachedValueProvider.Result.create(createGradleClassLoader(module), ProjectRootManager.getInstance(project)), false ); } @@ -146,7 +158,7 @@ private ClassLoader createGradleClassLoader(@Nonnull Module module) { return null; } - List urls = new ArrayList(); + List urls = new ArrayList<>(); final VirtualFile libDir = sdkHome.findChild("lib"); assert libDir != null; for (final VirtualFile child : libDir.getChildren()) { @@ -165,6 +177,7 @@ public ScriptSourceMapCalculator(Module module) { myModule = module; } + @Override public Result> compute() { final Map result = ConcurrentFactoryMap.createMap(this::calcClassName); return Result.create(result, ProjectRootManager.getInstance(myModule.getProject())); diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java index 14c6c5a..d69cb2c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java @@ -17,6 +17,7 @@ import com.intellij.java.language.impl.psi.NonClasspathDirectoriesScope; import com.intellij.java.language.psi.JavaPsiFacade; +import consulo.annotation.access.RequiredReadAction; import consulo.compiler.execution.CompileStepBeforeRun; import consulo.compiler.execution.CompileStepBeforeRunNoErrorCheck; import consulo.execution.CantRunException; @@ -26,6 +27,7 @@ import consulo.execution.executor.Executor; import consulo.externalSystem.util.ExternalSystemApiUtil; import consulo.externalSystem.util.ExternalSystemConstants; +import consulo.gradle.GradleConstants; import consulo.gradle.icon.GradleIconGroup; import consulo.ide.ServiceManager; import consulo.ide.impl.idea.openapi.externalSystem.psi.search.ExternalModuleBuildGlobalSearchScope; @@ -42,8 +44,10 @@ import consulo.module.content.layer.OrderEnumerator; import consulo.module.content.layer.orderEntry.ModuleExtensionWithSdkOrderEntry; import consulo.module.content.layer.orderEntry.OrderEntry; +import consulo.platform.Platform; import consulo.process.ExecutionException; import consulo.project.Project; +import consulo.ui.annotation.RequiredUIAccess; import consulo.ui.image.Image; import consulo.util.io.FileUtil; import consulo.util.lang.StringUtil; @@ -52,7 +56,6 @@ import org.jetbrains.plugins.gradle.service.GradleBuildClasspathManager; import org.jetbrains.plugins.gradle.service.GradleInstallationManager; import org.jetbrains.plugins.gradle.service.resolve.GradleResolverUtil; -import consulo.gradle.GradleConstants; import org.jetbrains.plugins.groovy.config.GroovyConfigUtils; import org.jetbrains.plugins.groovy.extensions.GroovyScriptType; import org.jetbrains.plugins.groovy.impl.extensions.GroovyRunnableScriptType; @@ -95,6 +98,7 @@ public Image getScriptIcon() { } @Override + @RequiredReadAction public boolean isConfigurationByLocation(@Nonnull GroovyScriptRunConfiguration existing, @Nonnull Location location) { final String params = existing.getScriptParameters(); if (params == null) { @@ -111,6 +115,7 @@ public boolean isConfigurationByLocation(@Nonnull GroovyScriptRunConfiguration e } @Override + @RequiredUIAccess public void tuneConfiguration(@Nonnull GroovyFile file, @Nonnull GroovyScriptRunConfiguration configuration, Location location) { List tasks = getTasksTarget(location); if (tasks != null) { @@ -124,6 +129,7 @@ public void tuneConfiguration(@Nonnull GroovyFile file, @Nonnull GroovyScriptRun } @Nullable + @RequiredReadAction private static List getTasksTarget(Location location) { if (location instanceof GradleTaskLocation gradleTaskLocation) { return gradleTaskLocation.getTasks(); @@ -173,7 +179,7 @@ public boolean shouldRefreshAfterFinish() { @Override public boolean isValidModule(@Nonnull Module module) { - GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); + GradleInstallationManager libraryManager = module.getInstance(GradleInstallationManager.class); return libraryManager.isGradleSdk(OrderEnumerator.orderEntries(module).getAllLibrariesAndSdkClassesRoots()); } @@ -218,6 +224,7 @@ public boolean ensureRunnerConfigured( } @Override + @RequiredReadAction public void configureCommandLine( OwnJavaParameters params, @Nullable Module module, @@ -228,7 +235,7 @@ public void configureCommandLine( final Project project = configuration.getProject(); String scriptParameters = configuration.getScriptParameters(); - final GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); + final GradleInstallationManager libraryManager = project.getInstance(GradleInstallationManager.class); if (module == null) { throw new CantRunException("Target module is undefined"); } @@ -255,7 +262,7 @@ public void configureCommandLine( } } - final String userDefinedClasspath = System.getProperty("gradle.launcher.classpath"); + final String userDefinedClasspath = Platform.current().jvm().getRuntimeProperty("gradle.launcher.classpath"); if (StringUtil.isNotEmpty(userDefinedClasspath)) { params.getClassPath().add(userDefinedClasspath); } @@ -268,7 +275,6 @@ public void configureCommandLine( params.getVMParametersList().addParametersString(configuration.getVMParameters()); - params.getVMParametersList().add("-Dgradle.home=" + FileUtil.toSystemDependentName(gradleHome.getPath())); setToolsJar(params); @@ -286,8 +292,9 @@ public void configureCommandLine( } @Nonnull + @RequiredReadAction private static String findMainClass(VirtualFile gradleHome, VirtualFile script, Project project) { - final String userDefined = System.getProperty("gradle.launcher.class"); + final String userDefined = Platform.current().jvm().getRuntimeProperty("gradle.launcher.class"); if (StringUtil.isNotEmpty(userDefined)) { return userDefined; } @@ -312,7 +319,8 @@ private static String findMainClass(VirtualFile gradleHome, VirtualFile script, } final PsiFile grFile = PsiManager.getInstance(project).findFile(script); - if (grFile != null && JavaPsiFacade.getInstance(project).findClass("org.gradle.BootstrapMain", grFile.getResolveScope()) != null) { + if (grFile != null + && JavaPsiFacade.getInstance(project).findClass("org.gradle.BootstrapMain", grFile.getResolveScope()) != null) { return "org.gradle.BootstrapMain"; } @@ -320,6 +328,7 @@ private static String findMainClass(VirtualFile gradleHome, VirtualFile script, } @Override + @RequiredReadAction public GlobalSearchScope patchResolveScope(@Nonnull GroovyFile file, @Nonnull GlobalSearchScope baseScope) { if (!FileUtil.extensionEquals(file.getName(), GradleConstants.EXTENSION)) { return baseScope; @@ -333,9 +342,8 @@ public GlobalSearchScope patchResolveScope(@Nonnull GroovyFile file, @Nonnull Gl Project project = module.getProject(); GlobalSearchScope result = GlobalSearchScope.EMPTY_SCOPE; for (OrderEntry entry : ModuleRootManager.getInstance(module).getOrderEntries()) { - if (entry instanceof ModuleExtensionWithSdkOrderEntry) { - GlobalSearchScope scopeForSdk = LibraryScopeCache.getInstance(project).getScopeForSdk((ModuleExtensionWithSdkOrderEntry) - entry); + if (entry instanceof ModuleExtensionWithSdkOrderEntry moduleExtensionWithSdkOrderEntry) { + GlobalSearchScope scopeForSdk = LibraryScopeCache.getInstance(project).getScopeForSdk(moduleExtensionWithSdkOrderEntry); result = result.uniteWith(scopeForSdk); } } From 07d61e499a41e726e5cedc8a00d146bbd11fd219 Mon Sep 17 00:00:00 2001 From: UNV Date: Fri, 9 Aug 2024 21:09:17 +0300 Subject: [PATCH 07/16] Using ISO-8601 date format in @since javadoc. --- .../project/AbstractProjectResolverExtension.java | 2 +- maven-impl/src/main/java/module-info.java | 10 +++++----- .../GradleMavenProjectImportNotificationListener.java | 2 +- .../maven/GradleMavenRepositoryProvider.java | 2 +- .../maven/GradleProjectStartupActivity.java | 2 +- .../maven/ImportMavenRepositoriesTask.java | 2 +- .../integrations/maven/MavenRepositoriesHolder.java | 2 +- .../maven/action/AddGradleDslDependencyAction.java | 2 +- .../action/AddGradleDslDependencyActionHandler.java | 2 +- .../MavenDependenciesGradleCompletionContributor.java | 2 +- .../action/AbstractGradleLinkedProjectAction.java | 2 +- .../plugins/gradle/action/GradleOpenScriptAction.java | 2 +- .../gradle/action/GradleToolWindowHelpAction.java | 2 +- ...UseDistributionWithSourcesNotificationProvider.java | 2 +- .../codeInsight/actions/AddGradleDslPluginAction.java | 2 +- .../actions/AddGradleDslPluginActionHandler.java | 2 +- .../gradle/codeInspection/GradleBaseInspection.java | 2 +- .../gradle/codeInspection/GradleInspectionBundle.java | 2 +- .../codeInspection/MultipleRepositoryUrlsFix.java | 2 +- .../MultipleRepositoryUrlsInspection.java | 2 +- .../DelegatingGradleSettingsListenerAdapter.java | 2 +- .../GradleBuildClasspathResolveScopeEnlarger.java | 2 +- .../jetbrains/plugins/gradle/config/GradlePatcher.java | 2 +- .../gradle/config/GradleSettingsListenerAdapter.java | 2 +- .../plugins/gradle/config/GradleToolWindowPanel.java | 2 +- .../gradle/remote/impl/GradleLibraryNamesMixer.java | 2 +- .../gradle/service/GradleInstallationManager.java | 2 +- .../execution/GradleExternalTaskConfigurationType.java | 2 +- .../execution/GradleRuntimeConfigurationProducer.java | 2 +- .../project/AbstractProjectImportErrorHandler.java | 2 +- .../project/BaseGradleProjectResolverExtension.java | 2 +- .../service/project/BaseProjectImportErrorHandler.java | 2 +- .../gradle/service/project/DistributionFactoryExt.java | 2 +- .../gradle/service/project/GradleAutoImportAware.java | 2 +- .../gradle/service/project/GradleExecutionHelper.java | 2 +- .../gradle/service/project/GradleNotification.java | 2 +- .../service/project/GradleNotificationContributor.java | 2 +- .../gradle/service/project/GradleProjectResolver.java | 2 +- .../gradle/service/project/GradleStartupActivity.java | 2 +- .../plugins/gradle/service/project/OutputWrapper.java | 2 +- .../data/BuildClasspathModuleGradleDataService.java | 2 +- .../project/data/ExternalProjectDataService.java | 2 +- .../project/data/ExternalProjectSerializer.java | 2 +- .../service/resolve/GradleArtifactsContributor.java | 2 +- .../service/resolve/GradleBuildScriptContributor.java | 2 +- .../gradle/service/resolve/GradleCommonClassNames.java | 2 +- .../resolve/GradleConfigurationsContributor.java | 2 +- .../GradleConfigurationsNonCodeMembersContributor.java | 2 +- .../service/resolve/GradleDependenciesContributor.java | 2 +- .../resolve/GradleIdeaPluginScriptContributor.java | 2 +- .../GradleMavenArtifactRepositoryContributor.java | 2 +- .../resolve/GradleMavenDeployerContributor.java | 2 +- .../resolve/GradleMethodContextContributor.java | 2 +- .../service/resolve/GradleRepositoriesContributor.java | 2 +- .../gradle/service/resolve/GradleResolverUtil.java | 2 +- .../gradle/service/resolve/GradleRootContributor.java | 2 +- .../service/resolve/GradleScriptContributor.java | 2 +- .../resolve/GradleSettingsScriptContributor.java | 2 +- .../service/resolve/GradleSimpleContributor.java | 2 +- .../service/resolve/GradleSourceSetsContributor.java | 2 +- .../gradle/service/resolve/GradleTaskContributor.java | 2 +- .../resolve/GradleUnresolvedReferenceFilter.java | 2 +- .../NamedDomainObjectCollectionTypeEnhancer.java | 2 +- .../gradle/service/resolve/dsl/GradleDslAnnotator.java | 2 +- .../service/resolve/dsl/GradleDslAnnotatorFactory.java | 2 +- .../gradle/service/settings/GradleConfigLocator.java | 2 +- .../gradle/service/settings/GradleConfigurable.java | 2 +- .../service/settings/GradleProjectSettingsControl.java | 2 +- .../service/settings/GradleSystemSettingsControl.java | 2 +- .../service/settings/ImportFromGradleControl.java | 2 +- .../plugins/gradle/service/task/GradleTaskManager.java | 2 +- .../service/task/GradleTaskManagerExtension.java | 2 +- 72 files changed, 76 insertions(+), 76 deletions(-) diff --git a/gradle-api/src/main/java/consulo/gradle/service/project/AbstractProjectResolverExtension.java b/gradle-api/src/main/java/consulo/gradle/service/project/AbstractProjectResolverExtension.java index e3674fb..99ea1b0 100644 --- a/gradle-api/src/main/java/consulo/gradle/service/project/AbstractProjectResolverExtension.java +++ b/gradle-api/src/main/java/consulo/gradle/service/project/AbstractProjectResolverExtension.java @@ -40,7 +40,7 @@ * {@link AbstractProjectResolverExtension} provides dummy implementation of Gradle project resolver. * * @author Vladislav.Soroka - * @since 10/14/13 + * @since 2013-10-14 */ public abstract class AbstractProjectResolverExtension implements GradleProjectResolverExtension { diff --git a/maven-impl/src/main/java/module-info.java b/maven-impl/src/main/java/module-info.java index 115ea8b..ce3daa8 100644 --- a/maven-impl/src/main/java/module-info.java +++ b/maven-impl/src/main/java/module-info.java @@ -1,10 +1,10 @@ /** * @author VISTALL - * @since 01/04/2023 + * @since 2023-04-01 */ module org.jetbrains.plugins.gradle.maven.impl { - requires consulo.ide.api; - requires org.jetbrains.plugins.gradle.api; - requires org.jetbrains.idea.maven; - requires org.jetbrains.idea.maven.server.common; + requires consulo.ide.api; + requires org.jetbrains.plugins.gradle.api; + requires org.jetbrains.idea.maven; + requires org.jetbrains.idea.maven.server.common; } \ No newline at end of file diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenProjectImportNotificationListener.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenProjectImportNotificationListener.java index 03a80a1..f6c7aee 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenProjectImportNotificationListener.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenProjectImportNotificationListener.java @@ -29,7 +29,7 @@ * {@link GradleMavenProjectImportNotificationListener} listens for Gradle project import events. * * @author Vladislav.Soroka - * @since 10/28/13 + * @since 2013-10-28 */ @ExtensionImpl public class GradleMavenProjectImportNotificationListener extends ExternalSystemTaskNotificationListenerAdapter { diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenRepositoryProvider.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenRepositoryProvider.java index ed734b2..fdd6a9e 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenRepositoryProvider.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleMavenRepositoryProvider.java @@ -25,7 +25,7 @@ /** * @author Vladislav.Soroka - * @since 10/25/13 + * @since 2013-10-25 */ @ExtensionImpl public class GradleMavenRepositoryProvider implements MavenRepositoryProvider { diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleProjectStartupActivity.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleProjectStartupActivity.java index 9461306..c23bc90 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleProjectStartupActivity.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/GradleProjectStartupActivity.java @@ -25,7 +25,7 @@ /** * @author Vladislav.Soroka - * @since 10/28/13 + * @since 2013-10-28 */ @ExtensionImpl public class GradleProjectStartupActivity implements PostStartupActivity { diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java index 3a96871..07194cf 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java @@ -55,7 +55,7 @@ /** * @author Vladislav.Soroka - * @since 10/29/13 + * @since 2013-10-29 */ public class ImportMavenRepositoriesTask implements Runnable { @Nonnull diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/MavenRepositoriesHolder.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/MavenRepositoriesHolder.java index 69d5781..e0fd621 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/MavenRepositoriesHolder.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/MavenRepositoriesHolder.java @@ -27,7 +27,7 @@ /** * @author Vladislav.Soroka - * @since 10/28/13 + * @since 2013-10-28 */ @Singleton @ServiceAPI(ComponentScope.PROJECT) diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java index f54e47c..ee40c13 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyAction.java @@ -36,7 +36,7 @@ /** * @author Vladislav.Soroka - * @since 10/23/13 + * @since 2013-10-23 */ @ActionImpl(id = "Gradle.AddGradleDslDependencyAction", parents = @ActionParentRef(value = @ActionRef(id = "GenerateGroup"))) public class AddGradleDslDependencyAction extends CodeInsightAction { diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java index 1edfc64..8237887 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/action/AddGradleDslDependencyActionHandler.java @@ -41,7 +41,7 @@ /** * @author Vladislav.Soroka - * @since 10/23/13 + * @since 2013-10-23 */ class AddGradleDslDependencyActionHandler implements CodeInsightActionHandler { @Override diff --git a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java index 7f905cf..8cac123 100644 --- a/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java +++ b/maven-impl/src/main/java/org/jetbrains/plugins/gradle/integrations/maven/codeInsight/MavenDependenciesGradleCompletionContributor.java @@ -49,7 +49,7 @@ /** * @author Vladislav.Soroka - * @since 10/31/13 + * @since 2013-10-31 */ @ExtensionImpl public class MavenDependenciesGradleCompletionContributor extends AbstractGradleCompletionContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java index 68a5386..261f1e5 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java @@ -17,7 +17,7 @@ * Not thread-safe. * * @author Denis Zhdanov - * @since 1/31/12 5:36 PM + * @since 2021-01-31 */ public abstract class AbstractGradleLinkedProjectAction extends AnAction { @Override diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java index b3b43d3..a6fae1b 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleOpenScriptAction.java @@ -20,7 +20,7 @@ * Not thread-safe. * * @author Denis Zhdanov - * @since 1/31/12 5:16 PM + * @since 2012-01-31 */ public class GradleOpenScriptAction extends AbstractGradleLinkedProjectAction implements DumbAware { private static final Logger LOG = Logger.getInstance(GradleOpenScriptAction.class); diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java index b5d0e5f..c4318a9 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java @@ -9,7 +9,7 @@ /** * @author Denis Zhdanov - * @since 3/17/12 2:34 PM + * @since 2012-03-17 */ public class GradleToolWindowHelpAction extends ContextHelpAction { @Override diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java index fbdb2f1..f282d18 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java @@ -65,7 +65,7 @@ /** * @author Vladislav.Soroka - * @since 9/13/13 + * @since 2013-09-13 */ @ExtensionImpl public class UseDistributionWithSourcesNotificationProvider implements EditorNotificationProvider { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java index 281d0d5..9e185e7 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java @@ -42,7 +42,7 @@ /** * @author Vladislav.Soroka - * @since 10/22/13 + * @since 2013-10-22 */ @ActionImpl( id = "AddGradleDslPluginAction", diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java index 7062922..6d3f026 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginActionHandler.java @@ -50,7 +50,7 @@ /** * @author Vladislav.Soroka - * @since 10/24/13 + * @since 2013-10-24 */ class AddGradleDslPluginActionHandler implements CodeInsightActionHandler { private final Pair[] myPlugins; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java index 69a6706..cd5ff15 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java @@ -21,7 +21,7 @@ /** * @author Vladislav.Soroka - * @since 11/21/13 + * @since 2013-11-21 */ public abstract class GradleBaseInspection extends BaseInspection { @Nonnull diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java index 6eef93a..346b8ac 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java @@ -20,7 +20,7 @@ /** * @author Vladislav.Soroka - * @since 9/13/13 + * @since 2013-09-13 */ public class GradleInspectionBundle extends AbstractBundle { private static final String BUNDLE = "org.jetbrains.plugins.gradle.codeInspection.GradleInspectionBundle"; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java index ea71f1a..f105196 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java @@ -33,7 +33,7 @@ /** * @author Vladislav.Soroka - * @since 11/21/13 + * @since 2013-11-21 */ public class MultipleRepositoryUrlsFix extends GroovyFix { private final GrClosableBlock myClosure; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java index d88f4e4..ef270f4 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java @@ -39,7 +39,7 @@ /** * @author Vladislav.Soroka - * @since 11/21/13 + * @since 2013-11-21 */ @ExtensionImpl public class MultipleRepositoryUrlsInspection extends GradleBaseInspection { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/DelegatingGradleSettingsListenerAdapter.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/DelegatingGradleSettingsListenerAdapter.java index a17ebbe..518f9bb 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/DelegatingGradleSettingsListenerAdapter.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/DelegatingGradleSettingsListenerAdapter.java @@ -26,7 +26,7 @@ /** * @author Denis Zhdanov - * @since 6/24/13 6:35 PM + * @since 2013-06-24 */ public class DelegatingGradleSettingsListenerAdapter extends DelegatingExternalSystemSettingsListener implements GradleSettingsListener { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleBuildClasspathResolveScopeEnlarger.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleBuildClasspathResolveScopeEnlarger.java index 426e1be..cc690f4 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleBuildClasspathResolveScopeEnlarger.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleBuildClasspathResolveScopeEnlarger.java @@ -30,7 +30,7 @@ /** * @author Vladislav.Soroka - * @since 5/16/2014 + * @since 2014-05-16 */ @ExtensionImpl public class GradleBuildClasspathResolveScopeEnlarger extends ResolveScopeEnlarger { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePatcher.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePatcher.java index c934f31..344063c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePatcher.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradlePatcher.java @@ -11,7 +11,7 @@ * Thread-safe. * * @author Denis Zhdanov - * @since 3/19/12 3:48 PM + * @since 2012-03-19 */ public class GradlePatcher { @SuppressWarnings("MethodMayBeStatic") diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java index f69cee8..69c53f3 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java @@ -10,7 +10,7 @@ /** * @author Denis Zhdanov - * @since 3/13/12 3:53 PM + * @since 2012-03-13 */ public abstract class GradleSettingsListenerAdapter extends ExternalSystemSettingsListenerAdapter implements GradleSettingsListener { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java index 84f5d29..36b1395 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java @@ -30,7 +30,7 @@ * Not thread-safe. * * @author Denis Zhdanov - * @since 12/26/11 5:19 PM + * @since 2011-12-26 */ public abstract class GradleToolWindowPanel extends SimpleToolWindowPanel { private static final String NON_LINKED_CARD_NAME = "NON_LINKED"; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/remote/impl/GradleLibraryNamesMixer.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/remote/impl/GradleLibraryNamesMixer.java index c23995a..3390e74 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/remote/impl/GradleLibraryNamesMixer.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/remote/impl/GradleLibraryNamesMixer.java @@ -17,7 +17,7 @@ * Thread-safe. * * @author Denis Zhdanov - * @since 10/19/11 2:04 PM + * @since 2011-10-19 2:04 PM */ public class GradleLibraryNamesMixer { 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 fe48dc9..1851675 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 @@ -47,7 +47,7 @@ * Thread-safe. * * @author Denis Zhdanov - * @since 8/4/11 11:06 AM + * @since 2011-08-04 */ @ServiceAPI(ComponentScope.APPLICATION) @ServiceImpl 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 b4d3946..b0f8cce 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 @@ -23,7 +23,7 @@ /** * @author Denis Zhdanov - * @since 23.05.13 17:56 + * @since 2013-05-23 */ @ExtensionImpl public class GradleExternalTaskConfigurationType extends AbstractExternalSystemTaskConfigurationType { 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 6d25620..934d95d 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 @@ -20,7 +20,7 @@ /** * @author Denis Zhdanov - * @since 6/5/13 8:17 PM + * @since 2013-06-05 */ @ExtensionImpl public class GradleRuntimeConfigurationProducer extends AbstractExternalSystemRuntimeConfigurationProducer { 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 94ba688..b3a77dd 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 @@ -27,7 +27,7 @@ /** * @author Vladislav.Soroka - * @since 10/16/13 + * @since 2013-10-16 */ public abstract class AbstractProjectImportErrorHandler { public static final String OPEN_GRADLE_SETTINGS = "Please fix the project's Gradle settings."; 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 fa3872b..cba2962 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 @@ -76,7 +76,7 @@ * {@link BaseGradleProjectResolverExtension} provides base implementation of Gradle project resolver. * * @author Vladislav.Soroka - * @since 10/14/13 + * @since 2013-10-14 */ @ExtensionImpl(order = "last") public class BaseGradleProjectResolverExtension implements GradleProjectResolverExtension { 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 6a734ff..1e41a6e 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 @@ -30,7 +30,7 @@ /** * @author Vladislav.Soroka - * @since 10/16/13 + * @since 2013-10-16 */ public class BaseProjectImportErrorHandler extends AbstractProjectImportErrorHandler { private static final Logger LOG = Logger.getInstance(BaseProjectImportErrorHandler.class); 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 b542d20..84ecb03 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 @@ -46,7 +46,7 @@ /** * @author Vladislav.Soroka - * @since 8/23/13 + * @since 2013-08-23 */ public class DistributionFactoryExt extends DistributionFactory { public DistributionFactoryExt() { 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 8083098..7a1cf14 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 @@ -32,7 +32,7 @@ /** * @author Denis Zhdanov - * @since 6/8/13 3:49 PM + * @since 2013-06-08 */ public class GradleAutoImportAware implements ExternalSystemAutoImportAware { @Nullable 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 fe0b1d1..18b4cb6 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 @@ -55,7 +55,7 @@ /** * @author Denis Zhdanov - * @since 3/14/13 5:11 PM + * @since 2013-03-14 */ public class GradleExecutionHelper { private static final Logger LOG = Logger.getInstance(GradleExecutionHelper.class); 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 3b1989f..9563e64 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 @@ -31,7 +31,7 @@ /** * @author Vladislav.Soroka - * @since 12/10/13 + * @since 2013-12-10 */ @ServiceAPI(ComponentScope.PROJECT) @ServiceImpl 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 fd145d1..9cc1c49 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 @@ -9,7 +9,7 @@ /** * @author VISTALL - * @since 31/03/2023 + * @since 2023-03-31 */ @ExtensionImpl public class GradleNotificationContributor implements NotificationGroupContributor { 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 6213026..a2ec9f5 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 @@ -57,7 +57,7 @@ /** * @author Denis Zhdanov, Vladislav Soroka - * @since 8/8/11 11:09 AM + * @since 2011-08-08 */ public class GradleProjectResolver implements ExternalSystemProjectResolver { private static final Logger LOG = Logger.getInstance(GradleProjectResolver.class); 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 0f88559..f791b40 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 @@ -51,7 +51,7 @@ /** * @author Vladislav.Soroka - * @since 12/10/13 + * @since 2013-12-10 */ @ExtensionImpl public class GradleStartupActivity implements PostStartupActivity { 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 4978860..9bc141f 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 @@ -10,7 +10,7 @@ /** * @author Denis Zhdanov - * @since 23.05.13 15:50 + * @since 2013-05-23 */ public class OutputWrapper extends OutputStream { @Nonnull 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 194e014..62982bc 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 @@ -46,7 +46,7 @@ /** * @author Vladislav.Soroka - * @since 8/27/13 + * @since 2013-08-27 */ @ExtensionImpl @Order(ExternalSystemConstants.UNORDERED) 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 42c304f..69228bf 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 @@ -57,7 +57,7 @@ /** * @author Vladislav.Soroka - * @since 7/17/2014 + * @since 2014-07-17 */ @Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER) public class ExternalProjectDataService implements ProjectDataService { 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 bfac51e..97e5cde 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 @@ -42,7 +42,7 @@ /** * @author Vladislav.Soroka - * @since 7/15/2014 + * @since 2014-07-15 */ public class ExternalProjectSerializer { private static final Logger LOG = Logger.getInstance(ExternalProjectSerializer.class); diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleArtifactsContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleArtifactsContributor.java index ac20e8a..0eb350c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleArtifactsContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleArtifactsContributor.java @@ -33,7 +33,7 @@ /** * @author Vladislav.Soroka - * @since 8/30/13 + * @since 2013-08-30 */ @ExtensionImpl public class GradleArtifactsContributor implements GradleMethodContextContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleBuildScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleBuildScriptContributor.java index a8b8722..c272e55 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleBuildScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleBuildScriptContributor.java @@ -19,7 +19,7 @@ /** * @author Vladislav.Soroka - * @since 8/30/13 + * @since 2013-08-30 */ @ExtensionImpl public class GradleBuildScriptContributor extends GradleSimpleContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleCommonClassNames.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleCommonClassNames.java index 1ae9177..757a008 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleCommonClassNames.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleCommonClassNames.java @@ -19,7 +19,7 @@ /** * @author Vladislav.Soroka - * @since 9/3/13 + * @since 2013-09-03 */ public final class GradleCommonClassNames { @NonNls diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsContributor.java index 3694183..21ac7b6 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsContributor.java @@ -27,7 +27,7 @@ /** * @author Vladislav.Soroka - * @since 8/29/13 + * @since 2013-08-29 */ @ExtensionImpl public class GradleConfigurationsContributor implements GradleMethodContextContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java index ae31148..77c2048 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleConfigurationsNonCodeMembersContributor.java @@ -41,7 +41,7 @@ /** * @author Vladislav.Soroka - * @since 8/30/13 + * @since 2013-08-30 */ @ExtensionImpl public class GradleConfigurationsNonCodeMembersContributor extends NonCodeMembersContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java index 7e6f225..730e08d 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java @@ -29,7 +29,7 @@ /** * @author Denis Zhdanov - * @since 8/14/13 12:58 PM + * @since 2013-08-14 */ @ExtensionImpl public class GradleDependenciesContributor implements GradleMethodContextContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleIdeaPluginScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleIdeaPluginScriptContributor.java index ec5cef4..e9f1d80 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleIdeaPluginScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleIdeaPluginScriptContributor.java @@ -20,7 +20,7 @@ /** * @author Vladislav.Soroka - * @since 11/18/13 + * @since 2013-11-18 */ @ExtensionImpl public class GradleIdeaPluginScriptContributor extends GradleSimpleContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenArtifactRepositoryContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenArtifactRepositoryContributor.java index 38f32a2..a265803 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenArtifactRepositoryContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenArtifactRepositoryContributor.java @@ -36,7 +36,7 @@ * } * * @author Vladislav.Soroka - * @since 10/21/13 + * @since 2013-10-21 */ @ExtensionImpl public class GradleMavenArtifactRepositoryContributor implements GradleMethodContextContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenDeployerContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenDeployerContributor.java index 20ff71c..8aa9121 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenDeployerContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMavenDeployerContributor.java @@ -36,7 +36,7 @@ * } * * @author Vladislav.Soroka - * @since 10/21/13 + * @since 2013-10-21 */ @ExtensionImpl public class GradleMavenDeployerContributor implements GradleMethodContextContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java index 4dcbac0..68f77a4 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java @@ -43,7 +43,7 @@ * is expected to be backed by corresponding implementation of the current interface. * * @author Denis Zhdanov - * @since 7/23/13 7:32 PM + * @since 2013-07-23 */ @ExtensionAPI(ComponentScope.APPLICATION) public interface GradleMethodContextContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java index 134ffe1..538c9e5 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java @@ -19,7 +19,7 @@ /** * @author Denis Zhdanov - * @since 8/14/13 12:56 PM + * @since 2013-08-14 */ @ExtensionImpl public class GradleRepositoriesContributor extends GradleSimpleContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java index 982b05b..805c27a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java @@ -46,7 +46,7 @@ /** * @author Vladislav.Soroka - * @since 8/30/13 + * @since 2013-08-30 */ public class GradleResolverUtil { public static int getGrMethodArumentsCount(@Nonnull GrArgumentList args) { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java index a071184..2024b6d 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java @@ -31,7 +31,7 @@ /** * @author Denis Zhdanov - * @since 8/14/13 1:03 PM + * @since 2013-08-14 */ @ExtensionImpl public class GradleRootContributor implements GradleMethodContextContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java index 3a12b6f..9ce3a6b 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java @@ -39,7 +39,7 @@ /** * @author Denis Zhdanov - * @since 7/23/13 4:21 PM + * @since 2013-07-23 */ @ExtensionImpl public class GradleScriptContributor extends NonCodeMembersContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java index 4dd2f17..f068cdc 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSettingsScriptContributor.java @@ -32,7 +32,7 @@ /** * @author Vladislav.Soroka - * @since 10/22/13 + * @since 2013-10-22 */ @ExtensionImpl public class GradleSettingsScriptContributor extends NonCodeMembersContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSimpleContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSimpleContributor.java index 7c034b2..289a220 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSimpleContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSimpleContributor.java @@ -26,7 +26,7 @@ /** * @author Vladislav.Soroka - * @since 8/30/13 + * @since 2013-08-30 */ public abstract class GradleSimpleContributor implements GradleMethodContextContributor { private final String blockName; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSourceSetsContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSourceSetsContributor.java index bd953c0..32aaeae 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSourceSetsContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleSourceSetsContributor.java @@ -31,7 +31,7 @@ /** * @author Vladislav.Soroka - * @since 8/29/13 + * @since 2013-08-29 */ @ExtensionImpl public class GradleSourceSetsContributor implements GradleMethodContextContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleTaskContributor.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleTaskContributor.java index 0c23c50..3e36306 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleTaskContributor.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleTaskContributor.java @@ -40,7 +40,7 @@ /** * @author Vladislav.Soroka - * @since 9/9/13 + * @since 2013-09-09 */ @ExtensionImpl public class GradleTaskContributor implements GradleMethodContextContributor { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleUnresolvedReferenceFilter.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleUnresolvedReferenceFilter.java index 94c1b6c..7c69a34 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleUnresolvedReferenceFilter.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/GradleUnresolvedReferenceFilter.java @@ -25,7 +25,7 @@ /** * @author Vladislav.Soroka - * @since 9/25/13 + * @since 2013-09-25 */ @ExtensionImpl public class GradleUnresolvedReferenceFilter extends GroovyUnresolvedHighlightFilter { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java index 580bb51..8436b82 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/NamedDomainObjectCollectionTypeEnhancer.java @@ -30,7 +30,7 @@ /** * @author Vladislav.Soroka - * @since 9/25/13 + * @since 2013-09-25 */ @ExtensionImpl public class NamedDomainObjectCollectionTypeEnhancer extends GrReferenceTypeEnhancer { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java index e5b134a..f8b8ad4 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java @@ -37,7 +37,7 @@ /** * @author Vladislav.Soroka - * @since 9/25/13 + * @since 2013-09-25 */ public class GradleDslAnnotator implements Annotator { @Override diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotatorFactory.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotatorFactory.java index 1d13f00..202622e 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotatorFactory.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotatorFactory.java @@ -11,7 +11,7 @@ /** * @author VISTALL - * @since 31/03/2023 + * @since 2023-03-31 */ @ExtensionImpl public class GradleDslAnnotatorFactory implements AnnotatorFactory { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigLocator.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigLocator.java index e29425d..1d39829 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigLocator.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigLocator.java @@ -22,7 +22,7 @@ * That's why we need to provide special code which maps that directory to exact config file. * * @author Denis Zhdanov - * @since 7/16/13 3:43 PM + * @since 2013-07-16 */ @ExtensionImpl public class GradleConfigLocator implements ExternalSystemConfigLocator { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java index bf01b0c..38d7046 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java @@ -32,7 +32,7 @@ /** * @author Denis Zhdanov - * @since 4/30/13 11:42 PM + * @since 2013-04-30 */ @ExtensionImpl public class GradleConfigurable extends AbstractExternalSystemConfigurable implements ProjectConfigurable { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java index 0ebf6f8..900cda8 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java @@ -58,7 +58,7 @@ /** * @author Denis Zhdanov - * @since 4/24/13 1:45 PM + * @since 2013-04-24 */ public class GradleProjectSettingsControl extends AbstractExternalProjectSettingsControl { private static final long BALLOON_DELAY_MILLIS = TimeUnit.SECONDS.toMillis(1); diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java index e4927b5..7fa1071 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java @@ -44,7 +44,7 @@ * a global one). * * @author Denis Zhdanov - * @since 4/28/13 11:06 AM + * @since 2013-04-28 */ public class GradleSystemSettingsControl implements ExternalSystemSettingsControl { @Nonnull diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java index 2a539c6..ce4ed71 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java @@ -30,7 +30,7 @@ /** * @author Denis Zhdanov - * @since 4/30/13 4:58 PM + * @since 2013-04-30 */ public class ImportFromGradleControl extends AbstractImportFromExternalSystemControl { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java index 8f947ad..d0f3c0c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java @@ -45,7 +45,7 @@ /** * @author Denis Zhdanov - * @since 3/14/13 5:09 PM + * @since 2013-03-14 */ public class GradleTaskManager extends AbstractExternalSystemTaskManager implements ExternalSystemTaskManager { diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java index 4a301df..afa2f6f 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java @@ -29,7 +29,7 @@ /** * @author Vladislav.Soroka - * @since 11/5/13 + * @since 2013-11-05 */ @ExtensionAPI(ComponentScope.APPLICATION) public interface GradleTaskManagerExtension { From 72a954557679c0f635c9cdd6b59cf0a1dc3c782a Mon Sep 17 00:00:00 2001 From: UNV Date: Fri, 9 Aug 2024 21:37:29 +0300 Subject: [PATCH 08/16] Fixed calling getInstance(GradleInstallationManager) not from application. --- .../jetbrains/plugins/gradle/config/GradleScriptType.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java index d69cb2c..b8d759a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/config/GradleScriptType.java @@ -18,6 +18,7 @@ import com.intellij.java.language.impl.psi.NonClasspathDirectoriesScope; import com.intellij.java.language.psi.JavaPsiFacade; import consulo.annotation.access.RequiredReadAction; +import consulo.application.Application; import consulo.compiler.execution.CompileStepBeforeRun; import consulo.compiler.execution.CompileStepBeforeRunNoErrorCheck; import consulo.execution.CantRunException; @@ -179,7 +180,7 @@ public boolean shouldRefreshAfterFinish() { @Override public boolean isValidModule(@Nonnull Module module) { - GradleInstallationManager libraryManager = module.getInstance(GradleInstallationManager.class); + GradleInstallationManager libraryManager = module.getApplication().getInstance(GradleInstallationManager.class); return libraryManager.isGradleSdk(OrderEnumerator.orderEntries(module).getAllLibrariesAndSdkClassesRoots()); } @@ -204,7 +205,7 @@ public boolean ensureRunnerConfigured( // } } } - final GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class); + final GradleInstallationManager libraryManager = Application.get().getInstance(GradleInstallationManager.class); // TODO den implement //if (libraryManager.getGradleHome(module, project) == null) { // int result = 0; @@ -235,7 +236,7 @@ public void configureCommandLine( final Project project = configuration.getProject(); String scriptParameters = configuration.getScriptParameters(); - final GradleInstallationManager libraryManager = project.getInstance(GradleInstallationManager.class); + final GradleInstallationManager libraryManager = project.getApplication().getInstance(GradleInstallationManager.class); if (module == null) { throw new CantRunException("Target module is undefined"); } From c6dcdf6200a9984009811b53510dd4a03194cd69 Mon Sep 17 00:00:00 2001 From: UNV Date: Fri, 9 Aug 2024 21:41:38 +0300 Subject: [PATCH 09/16] Fixed calling getInstance(ProjectDataManager) not from application. --- .../UseDistributionWithSourcesNotificationProvider.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java index f282d18..25953df 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java @@ -135,7 +135,7 @@ public EditorNotificationBuilder buildNotification( updateDefaultWrapperConfiguration(rootProjectPath); final Project project = module.getProject(); EditorNotifications.getInstance(project).updateAllNotifications(); - final ProjectDataManager projectDataManager = project.getInstance(ProjectDataManager.class); + final ProjectDataManager projectDataManager = project.getApplication().getInstance(ProjectDataManager.class); ExternalSystemUtil.refreshProject( project, GradleConstants.SYSTEM_ID, From c83bb2da629c6e5183c70cb767f31668e893ac8b Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 10 Aug 2024 10:35:47 +0300 Subject: [PATCH 10/16] Run configuration added. --- .../consulo_run_desktop_awt.xml | 45 +++++++++++++++++++ .gitignore | 4 +- 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 .consulo/runConfigurations/consulo_run_desktop_awt.xml diff --git a/.consulo/runConfigurations/consulo_run_desktop_awt.xml b/.consulo/runConfigurations/consulo_run_desktop_awt.xml new file mode 100644 index 0000000..b85bc2f --- /dev/null +++ b/.consulo/runConfigurations/consulo_run_desktop_awt.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/.gitignore b/.gitignore index b561e99..67f1d91 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ +/.consulo +!/.consulo/codeStyleSettings.xml +!/.consulo/runConfigurations /out /dep -.consulo/ target/ From 465beb790c7af777ce25d254d024e6ff0d066d5d Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 10 Aug 2024 11:27:12 +0300 Subject: [PATCH 11/16] Added CodeInspectionLocalize to replace CodeInspectionBundle. --- plugin/src/main/java/module-info.java | 2 ++ ...sulo.gradle.codeInspection.GradleInspectionLocalize.yaml | 6 ++++++ 2 files changed, 8 insertions(+) create mode 100644 plugin/src/main/resources/LOCALIZE-LIB/en_US/consulo.gradle.codeInspection.GradleInspectionLocalize.yaml diff --git a/plugin/src/main/java/module-info.java b/plugin/src/main/java/module-info.java index 97b8df6..624b6c5 100644 --- a/plugin/src/main/java/module-info.java +++ b/plugin/src/main/java/module-info.java @@ -31,4 +31,6 @@ // TODO remove in future requires consulo.ide.impl; requires java.desktop; + + exports consulo.gradle.codeInspection.localize; } \ No newline at end of file diff --git a/plugin/src/main/resources/LOCALIZE-LIB/en_US/consulo.gradle.codeInspection.GradleInspectionLocalize.yaml b/plugin/src/main/resources/LOCALIZE-LIB/en_US/consulo.gradle.codeInspection.GradleInspectionLocalize.yaml new file mode 100644 index 0000000..85a657d --- /dev/null +++ b/plugin/src/main/resources/LOCALIZE-LIB/en_US/consulo.gradle.codeInspection.GradleInspectionLocalize.yaml @@ -0,0 +1,6 @@ +group.other: + text: Other +multiple.repository.urls: + text: Multiple repository urls +multiple.repository.urls.fix.name: + text: Replace multiple repository urls with separate repository blocks From 5d66b96604e2484711fb7bbe7851f6f978aaf2d8 Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 10 Aug 2024 11:33:10 +0300 Subject: [PATCH 12/16] Reformatting with 4 spaces. Sorting module-info. --- plugin/pom.xml | 354 +++++++++--------- plugin/src/main/java/module-info.java | 58 ++- ...deInspection.GradleInspectionLocalize.yaml | 6 +- 3 files changed, 207 insertions(+), 211 deletions(-) diff --git a/plugin/pom.xml b/plugin/pom.xml index d85c871..5f47d84 100644 --- a/plugin/pom.xml +++ b/plugin/pom.xml @@ -16,182 +16,182 @@ --> - 4.0.0 - - consulo - arch.ide-api-provided + 4.0.0 + + consulo + arch.ide-api-provided + 3-SNAPSHOT + + + + consulo.plugin + org.jetbrains.plugins.gradle 3-SNAPSHOT - - - - consulo.plugin - org.jetbrains.plugins.gradle - 3-SNAPSHOT - consulo-plugin - - - - consulo - https://maven.consulo.io/repository/snapshots/ - - true - interval:60 - - - - - - 7.6.1 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - - - 5000 - - - - - consulo.maven - maven-consulo-plugin - true - - - consulo.java - consulo.javaee - org.intellij.groovy - com.intellij.xml - com.intellij.properties - - - ${dev.mode} - ${build.number} - - - - - gen - generate-sources - - generate-localize - generate-icon - - - - pack - package - - workspace - - - - - - - - - - ${project.groupId} - org.jetbrains.plugins.gradle-gradle.api - ${project.version} - - - - ${project.groupId} - org.jetbrains.plugins.gradle-maven.impl - ${project.version} - runtime - - - - ${project.groupId} - org.jetbrains.plugins.gradle-jakarta.web.impl - ${project.version} - runtime - - - - ${project.groupId} - org.jetbrains.plugins.gradle-tooling.extension.api - ${project.version} - - - - ${project.groupId} - org.jetbrains.plugins.gradle-tooling-extension.impl - ${project.version} - - - - consulo.internal.gradle.plugin - gradle-all - ${gradle.version} - - - - org.objenesis - objenesis - 2.5.1 - - - - com.esotericsoftware - minlog - 1.3.0 - - - - com.esotericsoftware - kryo - 4.0.2 - - - - commons-io - commons-io - 2.6 - - - - consulo - consulo-ide-impl - ${project.version} - provided - - - - ${project.groupId} - consulo.java - ${project.version} - provided - - - ${project.groupId} - com.intellij.properties - ${project.version} - provided - - - ${project.groupId} - consulo.javaee - ${project.version} - provided - - - ${project.groupId} - org.intellij.groovy - ${project.version} - provided - - - consulo - consulo-util-nodep - ${project.version} - provided - - + consulo-plugin + + + + consulo + https://maven.consulo.io/repository/snapshots/ + + true + interval:60 + + + + + + 7.6.1 + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + 5000 + + + + + consulo.maven + maven-consulo-plugin + true + + + consulo.java + consulo.javaee + org.intellij.groovy + com.intellij.xml + com.intellij.properties + + + ${dev.mode} + ${build.number} + + + + + gen + generate-sources + + generate-localize + generate-icon + + + + pack + package + + workspace + + + + + + + + + + ${project.groupId} + org.jetbrains.plugins.gradle-gradle.api + ${project.version} + + + + ${project.groupId} + org.jetbrains.plugins.gradle-maven.impl + ${project.version} + runtime + + + + ${project.groupId} + org.jetbrains.plugins.gradle-jakarta.web.impl + ${project.version} + runtime + + + + ${project.groupId} + org.jetbrains.plugins.gradle-tooling.extension.api + ${project.version} + + + + ${project.groupId} + org.jetbrains.plugins.gradle-tooling-extension.impl + ${project.version} + + + + consulo.internal.gradle.plugin + gradle-all + ${gradle.version} + + + + org.objenesis + objenesis + 2.5.1 + + + + com.esotericsoftware + minlog + 1.3.0 + + + + com.esotericsoftware + kryo + 4.0.2 + + + + commons-io + commons-io + 2.6 + + + + consulo + consulo-ide-impl + ${project.version} + provided + + + + ${project.groupId} + consulo.java + ${project.version} + provided + + + ${project.groupId} + com.intellij.properties + ${project.version} + provided + + + ${project.groupId} + consulo.javaee + ${project.version} + provided + + + ${project.groupId} + org.intellij.groovy + ${project.version} + provided + + + consulo + consulo-util-nodep + ${project.version} + provided + + \ No newline at end of file diff --git a/plugin/src/main/java/module-info.java b/plugin/src/main/java/module-info.java index 624b6c5..c02b7b3 100644 --- a/plugin/src/main/java/module-info.java +++ b/plugin/src/main/java/module-info.java @@ -1,36 +1,32 @@ /** * @author VISTALL - * @since 31/03/2023 + * @since 2023-03-31 */ open module org.jetbrains.plugins.gradle { - requires consulo.ide.api; - - requires consulo.java.execution.api; - requires consulo.java.execution.impl; - requires com.intellij.properties; - requires org.intellij.groovy.psi; - requires org.intellij.groovy; - - requires org.jetbrains.plugins.gradle.api; - - requires consulo.internal.jdi; - - requires com.google.gson; - requires org.apache.groovy; - - requires consulo.util.nodep; - - requires gradle.all; - requires kryo; - requires minlog; - requires objenesis; - - requires org.jetbrains.plugins.gradle.tooling; - requires org.jetbrains.plugins.gradle.tooling.impl; - - // TODO remove in future - requires consulo.ide.impl; - requires java.desktop; - - exports consulo.gradle.codeInspection.localize; + requires com.google.gson; + requires com.intellij.properties; + + requires consulo.ide.api; + requires consulo.internal.jdi; + requires consulo.java.execution.api; + requires consulo.java.execution.impl; + requires consulo.util.nodep; + + requires gradle.all; + requires kryo; + requires minlog; + requires objenesis; + + requires org.apache.groovy; + requires org.intellij.groovy; + requires org.intellij.groovy.psi; + requires org.jetbrains.plugins.gradle.api; + requires org.jetbrains.plugins.gradle.tooling; + requires org.jetbrains.plugins.gradle.tooling.impl; + + // TODO remove in future + requires consulo.ide.impl; + requires java.desktop; + + exports consulo.gradle.codeInspection.localize; } \ No newline at end of file diff --git a/plugin/src/main/resources/LOCALIZE-LIB/en_US/consulo.gradle.codeInspection.GradleInspectionLocalize.yaml b/plugin/src/main/resources/LOCALIZE-LIB/en_US/consulo.gradle.codeInspection.GradleInspectionLocalize.yaml index 85a657d..dcb4ab6 100644 --- a/plugin/src/main/resources/LOCALIZE-LIB/en_US/consulo.gradle.codeInspection.GradleInspectionLocalize.yaml +++ b/plugin/src/main/resources/LOCALIZE-LIB/en_US/consulo.gradle.codeInspection.GradleInspectionLocalize.yaml @@ -1,6 +1,6 @@ group.other: - text: Other + text: Other multiple.repository.urls: - text: Multiple repository urls + text: Multiple repository urls multiple.repository.urls.fix.name: - text: Replace multiple repository urls with separate repository blocks + text: Replace multiple repository urls with separate repository blocks From 93d66ba9d856c40aa06d944be1e35757d66a60db Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 10 Aug 2024 11:35:33 +0300 Subject: [PATCH 13/16] =?UTF-8?q?GradleInspectionBundle=20=E2=86=92=20Grad?= =?UTF-8?q?leInspectionLocalize.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../gradle/codeInspection/GradleInspectionBundle.java | 7 ++++++- .../gradle/codeInspection/MultipleRepositoryUrlsFix.java | 3 ++- .../codeInspection/MultipleRepositoryUrlsInspection.java | 9 ++++++--- 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java index 346b8ac..b776917 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java @@ -15,13 +15,18 @@ */ package org.jetbrains.plugins.gradle.codeInspection; +import consulo.annotation.DeprecationInfo; +import consulo.annotation.internal.MigratedExtensionsTo; import consulo.component.util.localize.AbstractBundle; -import org.jetbrains.annotations.PropertyKey; +import consulo.gradle.codeInspection.localize.GradleInspectionLocalize;import org.jetbrains.annotations.PropertyKey; /** * @author Vladislav.Soroka * @since 2013-09-13 */ +@Deprecated +@DeprecationInfo("GradleInspectionLocalize") +@MigratedExtensionsTo(GradleInspectionLocalize.class) public class GradleInspectionBundle extends AbstractBundle { private static final String BUNDLE = "org.jetbrains.plugins.gradle.codeInspection.GradleInspectionBundle"; diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java index f105196..703402a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java @@ -16,6 +16,7 @@ package org.jetbrains.plugins.gradle.codeInspection; import consulo.annotation.access.RequiredWriteAction; +import consulo.gradle.codeInspection.localize.GradleInspectionLocalize; import consulo.language.editor.inspection.ProblemDescriptor; import consulo.language.psi.PsiElement; import consulo.language.psi.util.PsiTreeUtil; @@ -79,6 +80,6 @@ protected void doFix(Project project, ProblemDescriptor descriptor) throws Incor @Nonnull @Override public String getName() { - return GradleInspectionBundle.message("multiple.repository.urls.fix.name"); + return GradleInspectionLocalize.multipleRepositoryUrlsFixName().get(); } } diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java index ef270f4..d0c084c 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java @@ -17,6 +17,7 @@ import consulo.annotation.access.RequiredReadAction; import consulo.annotation.component.ExtensionImpl; +import consulo.gradle.codeInspection.localize.GradleInspectionLocalize; import consulo.language.editor.inspection.LocalQuickFix; import consulo.language.editor.inspection.ProblemHighlightType; import consulo.language.psi.PsiFile; @@ -64,14 +65,14 @@ public String[] getGroupPath() { @Override protected String buildErrorString(Object... args) { - return GradleInspectionBundle.message("multiple.repository.urls", args); + return GradleInspectionLocalize.multipleRepositoryUrls().get(); } @Nls @Nonnull @Override public String getDisplayName() { - return GradleInspectionBundle.message("multiple.repository.urls"); + return GradleInspectionLocalize.multipleRepositoryUrls().get(); } private static class MyVisitor extends BaseInspectionVisitor { @@ -107,7 +108,9 @@ public void visitClosure(GrClosableBlock closure) { if (statements.size() > 1) { registerError(closure); - registerError(closure, GradleInspectionBundle.message("multiple.repository.urls"), + registerError( + closure, + GradleInspectionLocalize.multipleRepositoryUrls().get(), new LocalQuickFix[]{new MultipleRepositoryUrlsFix(closure, mavenMethodExpression.getText())}, ProblemHighlightType.GENERIC_ERROR ); From b0cc21ce6f39f36875ee570e36289969f403fad2 Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 10 Aug 2024 11:44:43 +0300 Subject: [PATCH 14/16] GradleInspectionBundle imports reformatted. --- .../plugins/gradle/codeInspection/GradleInspectionBundle.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java index b776917..0863112 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.java @@ -18,7 +18,8 @@ import consulo.annotation.DeprecationInfo; import consulo.annotation.internal.MigratedExtensionsTo; import consulo.component.util.localize.AbstractBundle; -import consulo.gradle.codeInspection.localize.GradleInspectionLocalize;import org.jetbrains.annotations.PropertyKey; +import consulo.gradle.codeInspection.localize.GradleInspectionLocalize; +import org.jetbrains.annotations.PropertyKey; /** * @author Vladislav.Soroka From 950a168ae0fb2a3a278549e594f7bf00ee2c98a2 Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 10 Aug 2024 16:55:37 +0300 Subject: [PATCH 15/16] Removed export of consulo.gradle.codeInspection.localize. --- plugin/src/main/java/module-info.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/plugin/src/main/java/module-info.java b/plugin/src/main/java/module-info.java index c02b7b3..910a925 100644 --- a/plugin/src/main/java/module-info.java +++ b/plugin/src/main/java/module-info.java @@ -27,6 +27,4 @@ // TODO remove in future requires consulo.ide.impl; requires java.desktop; - - exports consulo.gradle.codeInspection.localize; } \ No newline at end of file From 18acd346be4ba8c08924aa7355db8aa51060d6ed Mon Sep 17 00:00:00 2001 From: UNV Date: Sat, 10 Aug 2024 22:34:14 +0300 Subject: [PATCH 16/16] Fixed missing create() call for new annotation. --- .../gradle/service/resolve/dsl/GradleDslAnnotator.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java index f8b8ad4..9498d0a 100644 --- a/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java +++ b/plugin/src/main/java/org/jetbrains/plugins/gradle/service/resolve/dsl/GradleDslAnnotator.java @@ -18,6 +18,7 @@ import com.intellij.java.language.psi.PsiClass; import com.intellij.java.language.psi.PsiType; import com.intellij.java.language.psi.util.InheritanceUtil; +import consulo.annotation.access.RequiredReadAction; import consulo.language.editor.annotation.AnnotationHolder; import consulo.language.editor.annotation.Annotator; import consulo.language.editor.annotation.HighlightSeverity; @@ -41,6 +42,7 @@ */ public class GradleDslAnnotator implements Annotator { @Override + @RequiredReadAction public void annotate(@Nonnull PsiElement element, @Nonnull AnnotationHolder holder) { if (element instanceof GrReferenceExpression referenceExpression) { final GrExpression qualifier = ResolveUtil.getSelfOrWithQualifier(referenceExpression); @@ -71,7 +73,8 @@ public void annotate(@Nonnull PsiElement element, @Nonnull AnnotationHolder hold PsiElement nameElement = referenceExpression.getReferenceNameElement(); if (nameElement != null) { holder.newSilentAnnotation(HighlightSeverity.INFORMATION) - .textAttributes(GroovySyntaxHighlighter.MAP_KEY); + .textAttributes(GroovySyntaxHighlighter.MAP_KEY) + .create(); } } }