diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/JobHelpers.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/JobHelpers.java index c4f593166c..6a65d84487 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/JobHelpers.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/JobHelpers.java @@ -14,6 +14,7 @@ import java.util.Deque; import java.util.List; +import org.eclipse.buildship.core.internal.CorePlugin; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; @@ -195,7 +196,7 @@ static class BuildJobMatcher implements IJobMatcher { @Override public boolean matches(Job job) { return (job instanceof WorkspaceJob) || job.getClass().getName().matches("(.*\\.AutoBuild.*)") - || job.getClass().getName().endsWith("JREUpdateJob"); + || job.getClass().getName().endsWith("JREUpdateJob") || job.belongsTo(CorePlugin.GRADLE_JOB_FAMILY); } } diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/ProjectUtils.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/ProjectUtils.java index 11a2a38c97..d649b7fb96 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/ProjectUtils.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/ProjectUtils.java @@ -33,6 +33,7 @@ import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; @@ -368,5 +369,13 @@ private static IPath detectSources(Path file) { return Files.isRegularFile(sourcePath) ? new org.eclipse.core.runtime.Path(sourcePath.toString()) : null; } - + public static IProject findUniqueProject(IWorkspace workspace, String basename) { + IProject project = null; + String name; + for (int i = 1; project == null || project.exists(); i++) { + name = (i < 2) ? basename : basename + " (" + i + ")"; + project = workspace.getRoot().getProject(name); + } + return project; + } } diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/ResourceUtils.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/ResourceUtils.java index cc19c3c2b1..a4cba5f54b 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/ResourceUtils.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/ResourceUtils.java @@ -119,6 +119,22 @@ public static String getContent(URI fileURI) throws CoreException { return content; } + /** + * Reads file content directly from the filesystem. + */ + public static String getContent(File file) throws CoreException { + if (file == null) { + return null; + } + String content; + try { + content = Files.toString(file, Charsets.UTF_8); + } catch (IOException e) { + throw new CoreException(StatusFactory.newErrorStatus("Can not get " + file + " content", e)); + } + return content; + } + /** * Writes content to file, outside the workspace. No change event is * emitted. @@ -263,4 +279,16 @@ public static String toGlobPattern(IPath path) { return globPattern; } + public static IPath fixDevice(IPath path) { + if (path != null && path.getDevice() != null) { + return path.setDevice(path.getDevice().toUpperCase()); + } + if (Platform.OS_WIN32.equals(Platform.getOS()) && path != null && path.toString().startsWith("//")) { + String server = path.segment(0); + String pathStr = path.toString().replace(server, server.toUpperCase()); + return new Path(pathStr); + } + return path; + } + } diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/managers/EclipseProjectImporter.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/managers/EclipseProjectImporter.java index c231e318ad..810c74580f 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/managers/EclipseProjectImporter.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/managers/EclipseProjectImporter.java @@ -23,11 +23,12 @@ import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; -import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SubMonitor; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ls.core.internal.AbstractProjectImporter; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; +import org.eclipse.jdt.ls.core.internal.ProjectUtils; +import org.eclipse.jdt.ls.core.internal.ResourceUtils; public class EclipseProjectImporter extends AbstractProjectImporter { @@ -78,14 +79,14 @@ private void importDir(java.nio.file.Path dir, IProgressMonitor m) { IProject project = workspace.getRoot().getProject(name); if (project.exists()) { IPath existingProjectPath = project.getLocation(); - existingProjectPath = fixDevice(existingProjectPath); - dotProjectPath = fixDevice(dotProjectPath); + existingProjectPath = ResourceUtils.fixDevice(existingProjectPath); + dotProjectPath = ResourceUtils.fixDevice(dotProjectPath); if (existingProjectPath.equals(dotProjectPath.removeLastSegments(1))) { project.open(IResource.NONE, monitor.newChild(1)); project.refreshLocal(IResource.DEPTH_INFINITE, monitor.newChild(1)); return; } else { - project = findUniqueProject(workspace, name); + project = ProjectUtils.findUniqueProject(workspace, name); descriptor.setName(project.getName()); } } @@ -99,27 +100,4 @@ private void importDir(java.nio.file.Path dir, IProgressMonitor m) { } } - private IPath fixDevice(IPath path) { - if (path != null && path.getDevice() != null) { - return path.setDevice(path.getDevice().toUpperCase()); - } - if (Platform.OS_WIN32.equals(Platform.getOS()) && path != null && path.toString().startsWith("//")) { - String server = path.segment(0); - String pathStr = path.toString().replace(server, server.toUpperCase()); - return new Path(pathStr); - } - return path; - } - - //XXX should be package protected. Temporary fix (ahaha!) until test fragment can work in tycho builds - public IProject findUniqueProject(IWorkspace workspace, String basename) { - IProject project = null; - String name; - for (int i = 1; project == null || project.exists(); i++) { - name = (i < 2)? basename:basename + " ("+ i +")"; - project = workspace.getRoot().getProject(name); - } - return project; - } - } \ No newline at end of file diff --git a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/managers/GradleProjectImporter.java b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/managers/GradleProjectImporter.java index bc2bc901d8..915da06968 100644 --- a/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/managers/GradleProjectImporter.java +++ b/org.eclipse.jdt.ls.core/src/org/eclipse/jdt/ls/core/internal/managers/GradleProjectImporter.java @@ -10,30 +10,52 @@ *******************************************************************************/ package org.eclipse.jdt.ls.core.internal.managers; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; +import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Properties; import org.eclipse.buildship.core.BuildConfiguration; +import org.eclipse.buildship.core.GradleBuild; import org.eclipse.buildship.core.GradleCore; import org.eclipse.buildship.core.GradleDistribution; +import org.eclipse.buildship.core.LocalGradleDistribution; import org.eclipse.buildship.core.SynchronizationResult; import org.eclipse.buildship.core.WrapperGradleDistribution; import org.eclipse.buildship.core.internal.CorePlugin; +import org.eclipse.buildship.core.internal.DefaultGradleBuild; +import org.eclipse.buildship.core.internal.configuration.ConfigurationManager; +import org.eclipse.buildship.core.internal.configuration.WorkspaceConfiguration; +import org.eclipse.buildship.core.internal.operation.ToolingApiJobResultHandler; +import org.eclipse.buildship.core.internal.operation.ToolingApiStatus; import org.eclipse.buildship.core.internal.preferences.PersistentModel; import org.eclipse.buildship.core.internal.util.gradle.GradleVersion; +import org.eclipse.buildship.core.internal.workspace.SynchronizationJob; +import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubMonitor; +import org.eclipse.core.runtime.jobs.Job; import org.eclipse.jdt.ls.core.internal.AbstractProjectImporter; +import org.eclipse.jdt.ls.core.internal.IConstants; import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; import org.eclipse.jdt.ls.core.internal.ProjectUtils; +import org.eclipse.jdt.ls.core.internal.ResourceUtils; import org.eclipse.jdt.ls.core.internal.preferences.PreferenceManager; /** @@ -42,6 +64,12 @@ */ public class GradleProjectImporter extends AbstractProjectImporter { + private static final String CHECK_GRADLE_PROJECTS = "Check Gradle project(s)..."; + + private static final String DOT_SETTINGS = ".settings"; + + private static final String PREF_FILE = CorePlugin.PLUGIN_ID + ".prefs"; + public static final String GRADLE_HOME = "GRADLE_HOME"; private static final String BUILD_GRADLE_DESCRIPTOR = "build.gradle"; @@ -50,6 +78,8 @@ public class GradleProjectImporter extends AbstractProjectImporter { public static final String IMPORTING_GRADLE_PROJECTS = "Importing Gradle project(s)"; + public static final String JAVALS_GRADLE_FAMILY = IConstants.PLUGIN_ID + ".gradle.jobs"; + private Collection directories; /* (non-Javadoc) @@ -109,6 +139,7 @@ public static GradleDistribution getGradleDistribution(Path rootFolder) { for (GradleVersion version : versions) { if (version.compareTo(requiredVersion) == 0) { gradleVersion = version; + break; } } if (gradleVersion != null) { @@ -147,41 +178,200 @@ public static File getGradleHomeFile(Map env, Properties sysprop protected void startSynchronization(Path rootFolder, IProgressMonitor monitor) { File location = rootFolder.toFile(); boolean shouldSynchronize = shouldSynchronize(location); + if (shouldSynchronize) { + List projects = getGradleProjects(rootFolder); + if (projects.size() == 0) { + String content = getGradleSettings(rootFolder); + synchronizeWorkspace(rootFolder, monitor); + if (content != null) { + Job job = new Job(CHECK_GRADLE_PROJECTS) { + + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + getJobManager().join(CorePlugin.GRADLE_JOB_FAMILY, monitor); + } catch (OperationCanceledException | InterruptedException e) { + JavaLanguageServerPlugin.logException(e.getMessage(), e); + } + List projects = getGradleProjects(rootFolder); + IProject project = null; + for (IProject p : projects) { + File projectRoot = p.getRawLocation().toFile(); + if (projectRoot.isDirectory() && projectRoot.toPath().equals(rootFolder)) { + project = p; + break; + } + } + setGradleSettings(project, content, monitor); + return Status.OK_STATUS; + } + + /* (non-Javadoc) + * @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object) + */ + @Override + public boolean belongsTo(Object family) { + return JAVALS_GRADLE_FAMILY.equals(family); + } + }; + job.schedule(); + } + } else { + for (IProject project : projects) { + if (checkGradlePersistence(true, project, getProjectDirectory(project))) { + Optional gradleBuild = GradleCore.getWorkspace().getBuild(project); + GradleBuild build; + if (!gradleBuild.isPresent()) { + BuildConfiguration buildConfiguration = getBuildConfiguration(rootFolder); + build = GradleCore.getWorkspace().createBuild(buildConfiguration); + } else { + build = gradleBuild.get(); + } + if (!((DefaultGradleBuild) build).isSynchronizing()) { + SynchronizationJob job = new SynchronizationJob(build); + job.setResultHandler(new ToolingApiJobResultHandler() { + + @Override + public void onSuccess(Void result) { + } + + @Override + public void onFailure(ToolingApiStatus status) { + JavaLanguageServerPlugin.log(status); + } + }); + job.setUser(false); + job.schedule(); + } + } + } + } + } + } + + private String getGradleSettings(Path dir) { + Path settings = dir.resolve(DOT_SETTINGS); + if (settings.toFile().isDirectory()) { + File prefsFile = settings.resolve(PREF_FILE).toFile(); + if (prefsFile.isFile()) { + try { + return ResourceUtils.getContent(prefsFile); + } catch (CoreException e) { + // ignore + } + } + } + return null; + } + + private List getGradleProjects(Path rootFolder) { List projects = ProjectUtils.getGradleProjects(); - for (IProject project : projects) { - File projectDir = project.getLocation() == null ? null : project.getLocation().toFile(); - if (location.equals(projectDir)) { - // - shouldSynchronize = checkGradlePersistence(shouldSynchronize, project, projectDir); - break; + Iterator iter = projects.iterator(); + while (iter.hasNext()) { + IProject project = iter.next(); + Path projectPath = project.getLocation().toFile().toPath(); + if (!projectPath.startsWith(rootFolder)) { + iter.remove(); } } - if (shouldSynchronize) { - File gradleUserHome = getGradleHomeFile(); - GradleDistribution distribution = getGradleDistribution(rootFolder); - boolean overrideWorkspaceConfiguration = gradleUserHome != null || !(distribution instanceof WrapperGradleDistribution); - String javaHomeStr = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().getJavaHome(); - File javaHome = javaHomeStr == null ? null : new File(javaHomeStr); + return projects; + } + + private void synchronizeWorkspace(Path rootFolder, IProgressMonitor monitor) { + BuildConfiguration build = getBuildConfiguration(rootFolder); + if (build.isOverrideWorkspaceConfiguration()) { + File gradleUserHome = build.getGradleUserHome().isPresent() ? build.getGradleUserHome().get() : null; + File javaHome = build.getJavaHome().isPresent() ? build.getJavaHome().get() : null; // @formatter:off - BuildConfiguration build = BuildConfiguration.forRootProjectDirectory(location) - .overrideWorkspaceConfiguration(overrideWorkspaceConfiguration) - .gradleDistribution(distribution) - .javaHome(javaHome) - .gradleUserHome(gradleUserHome) - .build(); + WorkspaceConfiguration workspaceConfig = new WorkspaceConfiguration(build.getGradleDistribution(), + gradleUserHome, + javaHome, + build.isOfflineMode(), + build.isBuildScansEnabled(), + build.isAutoSync(), + build.getArguments(), + build.getJvmArguments(), + build.isShowConsoleView(), + build.isShowExecutionsView()); // @formatter:on - SynchronizationResult result = GradleCore.getWorkspace().createBuild(build).synchronize(monitor); - if (!result.getStatus().isOK()) { - JavaLanguageServerPlugin.log(result.getStatus()); - } + CorePlugin.configurationManager().saveWorkspaceConfiguration(workspaceConfig); + } + // @formatter:on + SynchronizationResult result = GradleCore.getWorkspace().createBuild(build).synchronize(monitor); + if (!result.getStatus().isOK()) { + JavaLanguageServerPlugin.log(result.getStatus()); + } + if (build.isOverrideWorkspaceConfiguration()) { + Job job = new Job(CHECK_GRADLE_PROJECTS) { + + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + getJobManager().join(CorePlugin.GRADLE_JOB_FAMILY, monitor); + } catch (OperationCanceledException | InterruptedException e) { + JavaLanguageServerPlugin.logException(e.getMessage(), e); + } + List gradleProjects = ProjectUtils.getGradleProjects(); + ConfigurationManager manager = CorePlugin.configurationManager(); + for (IProject project : gradleProjects) { + org.eclipse.buildship.core.internal.configuration.BuildConfiguration currentConfig = manager.loadProjectConfiguration(project).getBuildConfiguration(); + if (currentConfig.isOverrideWorkspaceSettings() != build.isOverrideWorkspaceConfiguration()) { + File gradleUserHome = build.getGradleUserHome().isPresent() ? build.getGradleUserHome().get() : null; + File javaHome = build.getJavaHome().isPresent() ? build.getJavaHome().get() : null; + // @formatter:off + org.eclipse.buildship.core.internal.configuration.BuildConfiguration updatedConfig = manager.createBuildConfiguration(currentConfig.getRootProjectDirectory(), + build.isOverrideWorkspaceConfiguration(), + build.getGradleDistribution(), + gradleUserHome, + javaHome, + build.isBuildScansEnabled(), + build.isOfflineMode(), + build.isAutoSync(), + build.getArguments(), + build.getJvmArguments(), + build.isShowConsoleView(), + build.isShowExecutionsView()); + // @formatter:on + manager.saveBuildConfiguration(updatedConfig); + } + } + return Status.OK_STATUS; + } + + /* (non-Javadoc) + * @see org.eclipse.core.runtime.jobs.Job#belongsTo(java.lang.Object) + */ + @Override + public boolean belongsTo(Object family) { + return JAVALS_GRADLE_FAMILY.equals(family); + } + }; + job.schedule(); } } + private BuildConfiguration getBuildConfiguration(Path rootFolder) { + File location = rootFolder.toFile(); + GradleDistribution distribution = getGradleDistribution(rootFolder); + File gradleUserHome = distribution instanceof LocalGradleDistribution ? getGradleHomeFile() : null; + boolean overrideWorkspaceConfiguration = gradleUserHome != null || !(distribution instanceof WrapperGradleDistribution); + String javaHomeStr = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().getJavaHome(); + File javaHome = javaHomeStr == null ? null : new File(javaHomeStr); + // @formatter:off + BuildConfiguration build = BuildConfiguration.forRootProjectDirectory(location) + .overrideWorkspaceConfiguration(overrideWorkspaceConfiguration) + .gradleDistribution(distribution) + .javaHome(javaHome) + .gradleUserHome(gradleUserHome) + .build(); + return build; + } + public static boolean shouldSynchronize(File location) { boolean shouldSynchronize = true; List projects = ProjectUtils.getGradleProjects(); for (IProject project : projects) { - File projectDir = project.getLocation() == null ? null : project.getLocation().toFile(); + File projectDir = getProjectDirectory(project); if (location.equals(projectDir)) { shouldSynchronize = checkGradlePersistence(shouldSynchronize, project, projectDir); break; @@ -190,6 +380,10 @@ public static boolean shouldSynchronize(File location) { return shouldSynchronize; } + private static File getProjectDirectory(IProject project) { + return project.getLocation() == null ? null : project.getLocation().toFile(); + } + private static boolean checkGradlePersistence(boolean shouldSynchronize, IProject project, File projectDir) { PersistentModel model = CorePlugin.modelPersistence().loadModel(project); if (model.isPresent()) { @@ -218,4 +412,17 @@ public boolean accept(File dir, String name) { public void reset() { } + private void setGradleSettings(IProject project, String content, IProgressMonitor monitor) { + if (content == null || project == null) { + return; + } + IPath prefsPath = new org.eclipse.core.runtime.Path(DOT_SETTINGS).append(PREF_FILE); + IFile prefsFile = project.getFile(prefsPath); + try (InputStream stream = new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8))) { + prefsFile.setContents(stream, true, false, monitor); + } catch (IOException | CoreException e) { + JavaLanguageServerPlugin.logException(e.getMessage(), e); + } + } + } diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/.classpath b/org.eclipse.jdt.ls.tests/projects/gradle/existing/.classpath new file mode 100644 index 0000000000..540156aa7c --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/.classpath @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/.project b/org.eclipse.jdt.ls.tests/projects/gradle/existing/.project new file mode 100644 index 0000000000..99b0126139 --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/.project @@ -0,0 +1,22 @@ + + + existing + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.buildship.core.gradleprojectnature + + diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/.settings/org.eclipse.buildship.core.prefs b/org.eclipse.jdt.ls.tests/projects/gradle/existing/.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 0000000000..545311f19e --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,13 @@ +arguments= +auto.sync=true +build.scans.enabled=false +connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER) +connection.project.dir= +eclipse.preferences.version=1 +gradle.user.home= +java.home= +jvm.arguments= +offline.mode=false +override.workspace.settings=true +show.console.view=false +show.executions.view=false diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/build.gradle b/org.eclipse.jdt.ls.tests/projects/gradle/existing/build.gradle new file mode 100644 index 0000000000..e4014a563a --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/build.gradle @@ -0,0 +1,29 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This generated file contains a sample Java Library project to get you started. + * For more details take a look at the Java Libraries chapter in the Gradle + * User Manual available at https://docs.gradle.org/5.4/userguide/java_library_plugin.html + */ + +plugins { + // Apply the java-library plugin to add support for Java Library + id 'java-library' +} + +repositories { + // Use jcenter for resolving your dependencies. + // You can declare any Maven/Ivy/file repository here. + jcenter() +} + +dependencies { + // This dependency is exported to consumers, that is to say found on their compile classpath. + api 'org.apache.commons:commons-math3:3.6.1' + + // This dependency is used internally, and not exposed to consumers on their own compile classpath. + implementation 'com.google.guava:guava:27.0.1-jre' + + // Use JUnit test framework + testImplementation 'junit:junit:4.12' +} diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradle/wrapper/gradle-wrapper.jar b/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..5c2d1cf016 Binary files /dev/null and b/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradle/wrapper/gradle-wrapper.jar differ diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradle/wrapper/gradle-wrapper.properties b/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..5f1b1201a7 --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradlew b/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradlew new file mode 100755 index 0000000000..b0d6d0ab5d --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradlew @@ -0,0 +1,188 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradlew.bat b/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradlew.bat new file mode 100644 index 0000000000..15e1ee37a7 --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem http://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/settings.gradle b/org.eclipse.jdt.ls.tests/projects/gradle/existing/settings.gradle new file mode 100644 index 0000000000..4a2c783910 --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/settings.gradle @@ -0,0 +1,10 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/5.4/userguide/multi_project_builds.html + */ + +rootProject.name = 'existing' diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/src/main/java/test/Library.java b/org.eclipse.jdt.ls.tests/projects/gradle/existing/src/main/java/test/Library.java new file mode 100644 index 0000000000..5beb75c5c1 --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/src/main/java/test/Library.java @@ -0,0 +1,10 @@ +/* + * This Java source file was generated by the Gradle 'init' task. + */ +package test; + +public class Library { + public boolean someLibraryMethod() { + return true; + } +} diff --git a/org.eclipse.jdt.ls.tests/projects/gradle/existing/src/test/java/test/LibraryTest.java b/org.eclipse.jdt.ls.tests/projects/gradle/existing/src/test/java/test/LibraryTest.java new file mode 100644 index 0000000000..a697dd6f62 --- /dev/null +++ b/org.eclipse.jdt.ls.tests/projects/gradle/existing/src/test/java/test/LibraryTest.java @@ -0,0 +1,14 @@ +/* + * This Java source file was generated by the Gradle 'init' task. + */ +package test; + +import org.junit.Test; +import static org.junit.Assert.*; + +public class LibraryTest { + @Test public void testSomeLibraryMethod() { + Library classUnderTest = new Library(); + assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod()); + } +} diff --git a/org.eclipse.jdt.ls.tests/src/org/eclipse/jdt/ls/core/internal/managers/EclipseProjectImporterTest.java b/org.eclipse.jdt.ls.tests/src/org/eclipse/jdt/ls/core/internal/managers/EclipseProjectImporterTest.java index ae2d415c47..f7257d925f 100644 --- a/org.eclipse.jdt.ls.tests/src/org/eclipse/jdt/ls/core/internal/managers/EclipseProjectImporterTest.java +++ b/org.eclipse.jdt.ls.tests/src/org/eclipse/jdt/ls/core/internal/managers/EclipseProjectImporterTest.java @@ -131,7 +131,7 @@ public void testFindUniqueProject() throws Exception { IProject p0 = mockProject(root, "project", false); //when - IProject p = importer.findUniqueProject(workspace, name); + IProject p = ProjectUtils.findUniqueProject(workspace, name); //then assertSame(p0, p); @@ -141,7 +141,7 @@ public void testFindUniqueProject() throws Exception { IProject p2 = mockProject(root, "project (2)", false); //when - p = importer.findUniqueProject(workspace, name); + p = ProjectUtils.findUniqueProject(workspace, name); //then assertSame(p2, p); @@ -152,7 +152,7 @@ public void testFindUniqueProject() throws Exception { IProject p3 = mockProject(root, "project (3)", false); //when - p = importer.findUniqueProject(workspace, name); + p = ProjectUtils.findUniqueProject(workspace, name); //then assertSame(p3, p); diff --git a/org.eclipse.jdt.ls.tests/src/org/eclipse/jdt/ls/core/internal/managers/GradleProjectImporterTest.java b/org.eclipse.jdt.ls.tests/src/org/eclipse/jdt/ls/core/internal/managers/GradleProjectImporterTest.java index 53ad657a16..e8a3d513a8 100644 --- a/org.eclipse.jdt.ls.tests/src/org/eclipse/jdt/ls/core/internal/managers/GradleProjectImporterTest.java +++ b/org.eclipse.jdt.ls.tests/src/org/eclipse/jdt/ls/core/internal/managers/GradleProjectImporterTest.java @@ -23,13 +23,18 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Properties; import org.eclipse.buildship.core.FixedVersionGradleDistribution; +import org.eclipse.buildship.core.GradleBuild; +import org.eclipse.buildship.core.GradleCore; import org.eclipse.buildship.core.GradleDistribution; import org.eclipse.buildship.core.LocalGradleDistribution; import org.eclipse.buildship.core.WrapperGradleDistribution; import org.eclipse.buildship.core.internal.CorePlugin; +import org.eclipse.buildship.core.internal.configuration.ConfigurationManager; +import org.eclipse.buildship.core.internal.configuration.ProjectConfiguration; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; @@ -105,13 +110,13 @@ public void testDisableGradleWrapper() throws Exception { assertTrue(file.isDirectory()); try { GradleDistribution distribution = GradleProjectImporter.getGradleDistribution(file.toPath()); - assertTrue(distribution instanceof WrapperGradleDistribution); + assertEquals(WrapperGradleDistribution.class, distribution.getClass()); JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setGradleWrapperEnabled(false); distribution = GradleProjectImporter.getGradleDistribution(file.toPath()); if (GradleProjectImporter.getGradleHomeFile() != null) { assertEquals(distribution.getClass(), LocalGradleDistribution.class); } else { - assertSame(distribution, GradleProjectImporter.DEFAULT_DISTRIBUTION); + assertSame(GradleProjectImporter.DEFAULT_DISTRIBUTION, distribution); } String requiredVersion = "5.2.1"; JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setGradleVersion(requiredVersion); @@ -129,6 +134,41 @@ public void testDisableGradleWrapper() throws Exception { } } + @Test + public void testBuildshipPreferences() throws Exception { + IProject project = importSimpleJavaProject(); + Optional gradleBuild = GradleCore.getWorkspace().getBuild(project); + assertTrue(gradleBuild.isPresent()); + ConfigurationManager manager = CorePlugin.configurationManager(); + org.eclipse.buildship.core.internal.configuration.BuildConfiguration currentConfig = manager.loadProjectConfiguration(project).getBuildConfiguration(); + assertFalse(currentConfig.isAutoSync()); + // @formatter:off + org.eclipse.buildship.core.internal.configuration.BuildConfiguration updatedConfig = manager.createBuildConfiguration(currentConfig.getRootProjectDirectory(), + true, // overrideWorkspaceSettings + currentConfig.getGradleDistribution(), + currentConfig.getGradleUserHome(), + currentConfig.getJavaHome(), + currentConfig.isBuildScansEnabled(), + currentConfig.isOfflineMode(), + true, // autoAsync + currentConfig.getArguments(), + currentConfig.getJvmArguments(), + currentConfig.isShowConsoleView(), + currentConfig.isShowExecutionsView()); + // @formatter:on + ProjectConfiguration projectConfig = manager.createProjectConfiguration(updatedConfig, project.getLocation().toFile()); + manager.saveProjectConfiguration(projectConfig); + IFile file = project.getFile("/build.gradle"); + // touch file + file.setLocalTimeStamp(System.currentTimeMillis()); + List projects = importExistingProjects("gradle/simple-gradle"); + project = getProject("simple-gradle"); + gradleBuild = GradleCore.getWorkspace().getBuild(project); + assertTrue(gradleBuild.isPresent()); + currentConfig = manager.loadProjectConfiguration(project).getBuildConfiguration(); + assertTrue(currentConfig.isAutoSync()); + } + @Test public void testDisableImportGradle() throws Exception { boolean enabled = JavaLanguageServerPlugin.getPreferencesManager().getPreferences().isImportGradleEnabled(); @@ -225,4 +265,17 @@ public void testJava12Project() throws Exception { assertEquals(JavaCore.DISABLED, javaProject.getOption(JavaCore.COMPILER_PB_ENABLE_PREVIEW_FEATURES, true)); assertEquals(JavaCore.WARNING, javaProject.getOption(JavaCore.COMPILER_PB_REPORT_PREVIEW_FEATURES, true)); } + + @Test + public void testImportExistingEclipseProject() throws Exception { + IProject project = importGradleProject("existing"); + Job.getJobManager().join(GradleProjectImporter.JAVALS_GRADLE_FAMILY, null); + assertTrue(ProjectUtils.isGradleProject(project)); + ConfigurationManager manager = CorePlugin.configurationManager(); + ProjectConfiguration configuration = manager.loadProjectConfiguration(project); + assertTrue(configuration.getBuildConfiguration().isAutoSync()); + assertTrue(configuration.getBuildConfiguration().isOverrideWorkspaceSettings()); + GradleDistribution distribution = configuration.getBuildConfiguration().getGradleDistribution(); + assertEquals(WrapperGradleDistribution.class, distribution.getClass()); + } }