IDEA-229955 PlatformProjectOpenProcessor should use a new unified API to open project (part 2)

GitOrigin-RevId: 964d320293c5738f37e56e07ba4b128ab9c0947e
This commit is contained in:
Vladimir Krivosheev
2020-06-04 21:39:22 +03:00
committed by intellij-monorepo-bot
parent febdcab3b6
commit e4e49abdd9
49 changed files with 410 additions and 446 deletions
@@ -111,10 +111,7 @@ public final class NewProjectUtil {
if (projectBuilder == null || !projectBuilder.isUpdate()) {
String name = wizard.getProjectName();
if (projectBuilder == null) {
OpenProjectTask options = new OpenProjectTask();
options.useDefaultProjectAsTemplate = true;
options.isNewProject = true;
newProject = projectManager.newProject(projectFile, name, options);
newProject = projectManager.newProject(projectFile, OpenProjectTask.newProject().withProjectName(name));
}
else {
newProject = projectBuilder.createProject(name, projectFilePath);
@@ -169,7 +166,7 @@ public final class NewProjectUtil {
if (newProject != projectToClose) {
ProjectUtil.updateLastProjectLocation(projectFile);
ProjectManagerEx.getInstanceEx().loadAndOpenProject(projectDir, OpenProjectTask.withCreatedProject(newProject, projectFile));
ProjectManagerEx.getInstanceEx().openProject(projectDir, OpenProjectTask.withCreatedProject(newProject).withProjectName(projectFile.getFileName().toString()));
}
if (!ApplicationManager.getApplication().isUnitTestMode()) {
@@ -2,7 +2,6 @@
package com.intellij.projectImport;
import com.intellij.CommonBundle;
import com.intellij.ide.GeneralSettings;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.JavaUiBundle;
import com.intellij.ide.highlighter.ProjectFileType;
@@ -12,6 +11,7 @@ import com.intellij.ide.impl.ProjectUtil;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.StorageScheme;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.project.ex.ProjectManagerEx;
@@ -177,49 +177,29 @@ public abstract class ProjectOpenProcessorBase<T extends ProjectImportBuilder<?>
JavaUiBundle.message("project.import.open.existing.reimport"),
CommonBundle.getCancelButtonText(),
Messages.getQuestionIcon());
if (result == Messages.CANCEL) return null;
if (result == Messages.CANCEL) {
return null;
}
shouldOpenExisting = result == Messages.YES;
importToProject = !shouldOpenExisting;
}
}
ProjectUtil.updateLastProjectLocation(pathToOpen);
OpenProjectTask options = shouldOpenExisting ? new OpenProjectTask(forceOpenInNewFrame, projectToClose) : OpenProjectTask.newProject(true)
.withProjectName(wizardContext.getProjectName());
OpenProjectTask options = shouldOpenExisting ? OpenProjectTask.withProjectToClose(projectToClose, forceOpenInNewFrame) : OpenProjectTask.newProject();
if (importToProject) {
options.withBeforeProjectCallback((project, module) -> importToProject(projectToClose, wizardContext, project));
options.withBeforeProjectCallback(project -> importToProject(projectToClose, wizardContext, project));
}
options.withProjectName(wizardContext.getProjectName());
Project projectToOpen;
if (shouldOpenExisting) {
try {
projectToOpen = ProjectManagerEx.getInstanceEx().loadAndOpenProject(pathToOpen, options);
}
catch (Exception e) {
return null;
}
try {
Project project = ProjectManagerEx.getInstanceEx().openProject(pathToOpen, options);
ProjectUtil.updateLastProjectLocation(pathToOpen);
return project;
}
else {
projectToOpen = ProjectManagerEx.getInstanceEx().newProject(pathToOpen, options);
if (projectToOpen == null || !importToProject(projectToClose, wizardContext, projectToOpen)) {
return null;
}
if (!forceOpenInNewFrame) {
Project[] openProjects = ProjectUtil.getOpenProjects();
if (openProjects.length > 0) {
int exitCode = ProjectUtil.confirmOpenNewProject(true);
if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
Project project = projectToClose != null ? projectToClose : openProjects[openProjects.length - 1];
ProjectManagerEx.getInstanceEx().closeAndDispose(project);
}
}
}
ProjectManagerEx.getInstanceEx().openProject(projectToOpen);
catch (Exception e) {
Logger.getInstance(ProjectOpenProcessorBase.class).warn(e);
return null;
}
return projectToOpen;
}
finally {
getBuilder().cleanup();
@@ -233,21 +213,23 @@ public abstract class ProjectOpenProcessorBase<T extends ProjectImportBuilder<?>
projectToOpen.save();
ApplicationManager.getApplication().runWriteAction(() -> {
Sdk jdk1 = wizardContext.getProjectJdk();
if (jdk1 != null) {
NewProjectUtil.applyJdkToProject(projectToOpen, jdk1);
}
ApplicationManager.getApplication().invokeAndWait(() -> {
ApplicationManager.getApplication().runWriteAction(() -> {
Sdk jdk1 = wizardContext.getProjectJdk();
if (jdk1 != null) {
NewProjectUtil.applyJdkToProject(projectToOpen, jdk1);
}
String projectDirPath = wizardContext.getProjectFileDirectory();
String path = projectDirPath + (StringUtil.endsWithChar(projectDirPath, '/') ? "classes" : "/classes");
CompilerProjectExtension extension = CompilerProjectExtension.getInstance(projectToOpen);
if (extension != null) {
extension.setCompilerOutputUrl(getUrl(path));
}
String projectDirPath = wizardContext.getProjectFileDirectory();
String path = projectDirPath + (StringUtil.endsWithChar(projectDirPath, '/') ? "classes" : "/classes");
CompilerProjectExtension extension = CompilerProjectExtension.getInstance(projectToOpen);
if (extension != null) {
extension.setCompilerOutputUrl(getUrl(path));
}
});
getBuilder().commit(projectToOpen, null, ModulesProvider.EMPTY_MODULES_PROVIDER);
});
getBuilder().commit(projectToOpen, null, ModulesProvider.EMPTY_MODULES_PROVIDER);
return true;
}
@@ -1,4 +1,4 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.projectWizard;
import com.intellij.execution.RunManager;
@@ -20,7 +20,6 @@ import com.intellij.openapi.roots.LanguageLevelProjectExtension;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.util.EmptyConsumer;
import java.util.List;
@@ -68,7 +67,7 @@ public class NewProjectWizardTest extends NewProjectWizardTestCase {
}
public void testChangeSdk() throws Exception {
Project project = createProject(EmptyConsumer.getInstance());
Project project = createProject(step -> {});
Sdk jdk17 = IdeaTestUtil.getMockJdk17();
addSdk(jdk17);
setProjectSdk(project, jdk17);
@@ -86,7 +85,7 @@ public class NewProjectWizardTest extends NewProjectWizardTestCase {
defaultExt.setLanguageLevel(LanguageLevel.JDK_1_4);
defaultExt.setDefault(null); // emulate migration from previous build
Project project = createProject(EmptyConsumer.getInstance());
Project project = createProject(step -> {});
LanguageLevelProjectExtension extension = LanguageLevelProjectExtension.getInstance(project);
Sdk sdk = ProjectRootManager.getInstance(project).getProjectSdk();
JavaSdkVersion version = JavaSdk.getInstance().getVersion(sdk);
@@ -116,7 +115,7 @@ public class NewProjectWizardTest extends NewProjectWizardTestCase {
try {
LanguageLevelProjectExtension.getInstance(defaultProject).setLanguageLevel(languageLevel);
LanguageLevelProjectExtension.getInstance(defaultProject).setDefault(detect);
Project project = createProject(EmptyConsumer.getInstance());
Project project = createProject(step -> {});
assertEquals(languageLevel, LanguageLevelProjectExtension.getInstance(project).getLanguageLevel());
return project;
}
@@ -7,12 +7,10 @@ import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.StdModuleTypes
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.testFramework.*
import com.intellij.testFramework.UsefulTestCase.assertSameElements
@@ -24,6 +22,7 @@ import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
@RunsInEdt
@@ -148,21 +147,21 @@ class AutomaticModuleUnloaderTest {
}
private fun createProject(): Project {
return ProjectManager.getInstance().createProject(null, tempDir.newPath("automaticReloaderTest").systemIndependentPath)!!
return ProjectManagerEx.getInstanceEx().newProject(tempDir.newPath("automaticReloaderTest"), createTestOpenProjectOptions())!!
}
private fun createModule(project: Project, moduleName: String): Module {
return runWriteAction { ModuleManager.getInstance(project).newModule("${project.basePath}/$moduleName.iml", "JAVA") }
}
private fun createNewModuleFiles(moduleNames: List<String>, setup: (Map<String, Module>) -> Unit): List<File> {
val newModulesProjectDir = tempDir.newPath("newModules").toFile()
val moduleFiles = moduleNames.map { File(newModulesProjectDir, "$it.iml") }
val project = ProjectManager.getInstance().createProject("newModules", newModulesProjectDir.absolutePath)!!
private fun createNewModuleFiles(moduleNames: List<String>, setup: (Map<String, Module>) -> Unit): List<Path> {
val newModulesProjectDir = tempDir.newPath("newModules")
val moduleFiles = moduleNames.map { newModulesProjectDir.resolve("$it.iml") }
val project = ProjectManagerEx.getInstanceEx().newProject(newModulesProjectDir, createTestOpenProjectOptions())!!
try {
runWriteAction {
moduleFiles.map {
ModuleManager.getInstance(project).newModule(it.absolutePath, StdModuleTypes.JAVA.id)
ModuleManager.getInstance(project).newModule(it.toAbsolutePath().toString(), StdModuleTypes.JAVA.id)
}
}
setup(ModuleManager.getInstance(project).modules.associateBy { it.name })
@@ -178,7 +177,7 @@ class AutomaticModuleUnloaderTest {
ProjectManagerEx.getInstanceEx().forceCloseProject(project)
}
private fun reloadProjectWithNewModules(project: Project, moduleFiles: List<File>, beforeReload: () -> Unit = {}): Project {
private fun reloadProjectWithNewModules(project: Project, moduleFiles: List<Path>, beforeReload: () -> Unit = {}): Project {
saveAndCloseProject(project)
val modulesXmlFile = File(project.basePath, ".idea/modules.xml")
val rootElement = JDOMUtil.load(modulesXmlFile)
@@ -1,4 +1,4 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.projectWizard;
import com.intellij.ide.actions.ImportModuleAction;
@@ -157,13 +157,14 @@ public abstract class ProjectWizardTestCase<T extends AbstractProjectWizard> ext
private static class CancelWizardException extends RuntimeException {
}
private void runWizard(@Nullable Consumer<? super Step> adjuster) {
private void runWizard(@Nullable java.util.function.Consumer<? super Step> adjuster) {
while (true) {
ModuleWizardStep currentStep = myWizard.getCurrentStepObject();
if (adjuster != null) {
try {
adjuster.consume(currentStep);
} catch (CancelWizardException e) {
adjuster.accept(currentStep);
}
catch (CancelWizardException e) {
myWizard.doCancelAction();
return;
}
@@ -190,7 +191,7 @@ public abstract class ProjectWizardTestCase<T extends AbstractProjectWizard> ext
UIUtil.dispatchAllInvocationEvents(); // to make default selection applied
}
protected Project createProject(Consumer<? super Step> adjuster) throws IOException {
protected Project createProject(java.util.function.Consumer<? super Step> adjuster) throws IOException {
createWizard(null);
runWizard(adjuster);
myCreatedProject = NewProjectUtil.createFromWizard(myWizard);
@@ -219,7 +220,7 @@ public abstract class ProjectWizardTestCase<T extends AbstractProjectWizard> ext
return importFrom(path, getProject(), null, provider);
}
protected Module importProjectFrom(String path, Consumer<? super Step> adjuster, ProjectImportProvider... providers) {
protected Module importProjectFrom(String path, java.util.function.Consumer<? super Step> adjuster, ProjectImportProvider... providers) {
Module module = importFrom(path, null, adjuster, providers);
if (module != null) {
myCreatedProject = module.getProject();
@@ -228,12 +229,13 @@ public abstract class ProjectWizardTestCase<T extends AbstractProjectWizard> ext
}
private Module importFrom(String path,
@Nullable Project project, Consumer<? super Step> adjuster,
final ProjectImportProvider... providers) {
@Nullable Project project,
java.util.function.Consumer<? super Step> adjuster,
ProjectImportProvider... providers) {
return computeInWriteSafeContext(() -> doImportModule(path, project, adjuster, providers));
}
private Module doImportModule(String path, @Nullable Project project, Consumer<? super Step> adjuster, ProjectImportProvider[] providers) {
private Module doImportModule(String path, @Nullable Project project, java.util.function.Consumer<? super Step> adjuster, ProjectImportProvider[] providers) {
VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(path);
assertNotNull("Can't find " + path, file);
assertTrue(providers[0].canImport(file, project));
@@ -365,6 +365,6 @@ private fun doReloadProject(project: Project) {
return@submit
}
ProjectManagerEx.getInstanceEx().loadAndOpenProject(Paths.get(presentableUrl), OpenProjectTask())
ProjectManagerEx.getInstanceEx().openProject(Paths.get(presentableUrl), OpenProjectTask())
}
}
@@ -2,6 +2,7 @@
package com.intellij.configurationStore
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
@@ -17,7 +18,6 @@ import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.util.PathUtil
import com.intellij.util.io.readChars
import com.intellij.util.io.readText
import com.intellij.util.io.systemIndependentPath
import com.intellij.util.io.write
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@@ -246,7 +246,7 @@ internal class ProjectStoreTest {
(projectManager.defaultProject as ComponentManager).stateStore.initComponent(testComponent, null, null)
val newProjectPath = tempDirManager.newPath()
val newProject = projectManager.newProject("foo", newProjectPath.systemIndependentPath, true, false)!!
val newProject = projectManager.openProject(newProjectPath, OpenProjectTask(isNewProject = true, isRefreshVfsNeeded = false))!!
try {
val miscXml = newProjectPath.resolve(".idea/misc.xml").readChars()
assertThat(miscXml).contains("AATestComponent")
@@ -16,6 +16,7 @@ import com.intellij.util.io.exists
import org.jetbrains.annotations.ApiStatus
import java.nio.file.InvalidPathException
import java.nio.file.Paths
import java.util.function.Predicate
@ApiStatus.Experimental
abstract class AbstractOpenProjectProvider : OpenProjectProvider {
@@ -34,16 +35,21 @@ abstract class AbstractOpenProjectProvider : OpenProjectProvider {
if (focusOnOpenedSameProject(projectDirectory.path)) {
return null
}
if (canOpenPlatformProject(projectDirectory)) {
else if (canOpenPlatformProject(projectDirectory)) {
return openPlatformProject(projectDirectory, projectToClose, forceOpenInNewFrame)
}
val project = createProject(projectDirectory) ?: return null
linkAndRefreshProject(projectDirectory.path, project)
val path = projectDirectory.toNioPath()
updateLastProjectLocation(path)
ProjectManagerEx.getInstanceEx().loadAndOpenProject(path, OpenProjectTask(forceOpenInNewFrame = forceOpenInNewFrame, projectToClose = projectToClose, project = project))
return project
val options = OpenProjectTask(isNewProject = true,
forceOpenInNewFrame = forceOpenInNewFrame,
projectToClose = projectToClose,
runConfigurators = false,
beforeProjectOpen = Predicate { project ->
project.putUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT, true)
linkAndRefreshProject(projectDirectory.path, project)
updateLastProjectLocation(projectDirectory.toNioPath())
true
})
return ProjectManagerEx.getInstanceEx().openProject(projectDirectory.toNioPath(), options)
}
override fun linkToExistingProject(projectFile: VirtualFile, project: Project) {
@@ -96,13 +102,6 @@ abstract class AbstractOpenProjectProvider : OpenProjectProvider {
return file
}
private fun createProject(projectDirectory: VirtualFile): Project? {
val projectManager = ProjectManagerEx.getInstanceEx()
val project = projectManager.createProject(projectDirectory.name, projectDirectory.path)
project?.putUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT, true)
return project
}
companion object {
protected val LOG = Logger.getInstance(AbstractOpenProjectProvider::class.java)
}
@@ -1,11 +1,9 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.importing
import com.intellij.openapi.externalSystem.util.use
import org.junit.Test
interface ExternalSystemSetupProjectTest : ExternalSystemSetupProjectTestCase {
@Test
fun `test project open`() {
val projectInfo = generateProject("A")
@@ -1,8 +1,8 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.importing
import com.intellij.openapi.externalSystem.util.use as utilUse
import com.intellij.ide.actions.ImportModuleAction
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtil
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.CommonDataKeys
@@ -17,17 +17,17 @@ import com.intellij.openapi.fileChooser.impl.FileChooserFactoryImpl
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.use
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.testFramework.TestActionEvent
import com.intellij.testFramework.replaceService
import org.junit.Assert.assertEquals
import java.awt.Component
import com.intellij.openapi.externalSystem.util.use as utilUse
interface ExternalSystemSetupProjectTestCase {
data class ProjectInfo(val projectFile: VirtualFile, val modules: List<String>) {
constructor(projectFile: VirtualFile, vararg modules: String) : this(projectFile, modules.toList())
}
@@ -53,10 +53,9 @@ interface ExternalSystemSetupProjectTestCase {
fun waitForImportCompletion(project: Project)
fun openPlatformProjectFrom(projectDirectory: VirtualFile): Project {
return invokeAndWaitIfNeeded {
val openProcessor = PlatformProjectOpenProcessor.getInstance()
openProcessor.doOpenProject(projectDirectory, null, true)!!
}
return ProjectManagerEx.getInstanceEx().openProject(projectDirectory.toNioPath(), OpenProjectTask(forceOpenInNewFrame = true,
useDefaultProjectAsTemplate = false,
isRefreshVfsNeeded = false))!!
}
fun openProjectFrom(projectFile: VirtualFile): Project {
@@ -204,7 +204,7 @@ public final class InspectionApplication implements CommandLineInspectionProgres
}
}
Project project = ProjectUtil.openOrImport(projectPath, null, false);
Project project = ProjectUtil.openOrImport(projectPath);
if (project == null) {
reportError("Unable to open project");
gracefulExit();
@@ -1,19 +1,4 @@
/*
* Copyright 2000-2019 JetBrains s.r.o.
*
* 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.
*/
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.util.projectWizard;
import com.intellij.openapi.module.ModifiableModuleModel;
@@ -30,7 +15,6 @@ import org.jetbrains.annotations.Nullable;
import java.util.List;
public abstract class ProjectBuilder {
public boolean isUpdate() {
return false;
}
@@ -71,8 +55,7 @@ public abstract class ProjectBuilder {
return true;
}
@Nullable
public Project createProject(String name, String path) {
public @Nullable Project createProject(String name, String path) {
return ProjectManager.getInstance().createProject(name, path);
}
}
@@ -58,10 +58,8 @@ public final class FileSetFormatter extends FileSetProcessor {
}
private void createProject() throws IOException {
ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
myProject = projectManager.newProject(createProjectDir(), myProjectUID, OpenProjectTask.newProject(true));
myProject = ProjectManagerEx.getInstanceEx().openProject(createProjectDir(), OpenProjectTask.newProject());
if (myProject != null) {
projectManager.openProject(myProject);
CodeStyle.setMainProjectSettings(myProject, mySettings);
}
}
@@ -12,6 +12,7 @@ import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectManagerEx;
@@ -26,7 +27,6 @@ import com.intellij.platform.*;
import com.intellij.platform.templates.ArchivedTemplatesFactory;
import com.intellij.platform.templates.LocalArchivedTemplate;
import com.intellij.platform.templates.TemplateProjectDirectoryGenerator;
import com.intellij.projectImport.ProjectOpenedCallback;
import com.intellij.util.PairConsumer;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -203,17 +203,15 @@ public abstract class AbstractNewProjectStep<T> extends DefaultActionGroup imple
RecentProjectsManager.getInstance().setLastProjectCreationLocation(location.getParent());
ProjectOpenedCallback callback = null;
if (generator instanceof TemplateProjectDirectoryGenerator) {
((TemplateProjectDirectoryGenerator<?>)generator).generateProject(baseDir.getName(), locationString);
}
else if (generator != null) {
callback = (p, module) -> {
generator.generateProject(p, baseDir, settings, module);
};
}
OpenProjectTask options = OpenProjectTask.newProjectWithCallback(projectToClose, callback, /* isRefreshVfsNeeded = */ false);
return ProjectManagerEx.getInstanceEx().loadAndOpenProject(location, options);
OpenProjectTask options = OpenProjectTask.newProjectAndRunConfigurators(projectToClose, /* isRefreshVfsNeeded = */ false);
Project project = ProjectManagerEx.getInstanceEx().openProject(location, options);
if (project != null && generator != null) {
generator.generateProject(project, baseDir, settings, ModuleManager.getInstance(project).getModules()[0]);
}
return project;
}
}
@@ -30,6 +30,6 @@ public class ProjectAttachProcessor {
public void beforeDetach(@NotNull Module module) {}
public static boolean canAttachToProject() {
return EP_NAME.getPoint().size() != 0;
return EP_NAME.hasAnyExtensions();
}
}
@@ -304,7 +304,7 @@ open class RecentProjectsManagerBase : RecentProjectsManager(), PersistentStateC
return when {
existing != null -> existing
ProjectUtil.isValidProjectPath(projectFile) -> {
ProjectManagerEx.getInstanceEx().loadAndOpenProject(projectFile, openProjectOptions)
ProjectManagerEx.getInstanceEx().openProject(projectFile, openProjectOptions)
}
else -> {
// If .idea is missing in the recent project's dir; this might mean, for instance, that 'git clean' was called.
@@ -59,7 +59,7 @@ public class ReopenProjectAction extends AnAction implements DumbAware {
boolean forceOpenInNewFrame = BitUtil.isSet(modifiers, InputEvent.CTRL_MASK)
|| BitUtil.isSet(modifiers, InputEvent.SHIFT_MASK)
|| e.getPlace() == ActionPlaces.WELCOME_SCREEN;
RecentProjectsManagerBase.getInstanceEx().openProject(file, new OpenProjectTask(forceOpenInNewFrame, project));
RecentProjectsManagerBase.getInstanceEx().openProject(file, OpenProjectTask.withProjectToClose(project, forceOpenInNewFrame));
}
@SystemIndependent
@@ -1,25 +1,19 @@
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions;
import com.intellij.ide.impl.OpenProjectTask;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectManagerEx;
import com.intellij.util.PlatformUtils;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class NewDummyProjectAction extends AnAction implements DumbAware {
final class NewDummyProjectAction extends AnAction implements DumbAware {
@Override
public void actionPerformed(@NotNull final AnActionEvent e) {
final ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
Project project = projectManager.newProject("dummy", PathManager.getConfigPath() + "/dummy.ipr", true, false);
if (project == null) return;
projectManager.openProject(project);
public void actionPerformed(@NotNull AnActionEvent e) {
ProjectManagerEx.getInstanceEx().openProject(PathManager.getConfigDir().resolve("dummy.ipr"), OpenProjectTask.newProject());
}
@Override
@@ -55,7 +55,7 @@ public final class SaveAsDirectoryBasedFormatAction extends AnAction implements
// closeAndDispose will also force save project
ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
projectManager.closeAndDispose(project);
projectManager.loadAndOpenProject(ideaDir.getParent(), new OpenProjectTask());
projectManager.openProject(ideaDir.getParent(), new OpenProjectTask());
}
catch (IOException e) {
Messages.showErrorDialog(project, String.format("Unable to create '.idea' directory (%s): " + e.getMessage(), ideaDir),
@@ -1,19 +1,20 @@
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.impl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.impl.FrameInfo
import com.intellij.projectImport.ProjectOpenedCallback
import org.jetbrains.annotations.ApiStatus
import java.nio.file.Path
import java.util.function.BiPredicate
import java.util.function.Predicate
data class OpenProjectTask(@JvmField val forceOpenInNewFrame: Boolean = false,
@JvmField val projectToClose: Project? = null,
@JvmField var useDefaultProjectAsTemplate: Boolean = true,
@JvmField var isNewProject: Boolean = false,
data class OpenProjectTask(val forceOpenInNewFrame: Boolean = false,
val projectToClose: Project? = null,
val isNewProject: Boolean = false,
/**
* Ignored if isNewProject is set to false.
*/
val useDefaultProjectAsTemplate: Boolean = isNewProject,
/**
* Prepared project to open. If you just need to open newly created and prepared project (e.g. used by a new project action).
*/
@@ -26,48 +27,51 @@ data class OpenProjectTask(@JvmField val forceOpenInNewFrame: Boolean = false,
val showWelcomeScreen: Boolean = true,
@set:Deprecated(message = "Pass to constructor", level = DeprecationLevel.ERROR)
var callback: ProjectOpenedCallback? = null,
val beforeProjectOpen: BiPredicate<Project, Module?>? = null,
/**
* Ignored if project is explicitly set.
*/
internal val beforeProjectOpen: Predicate<Project>? = null,
internal val preparedToOpen: ((Module) -> Unit)? = null,
val frame: FrameInfo? = null,
val projectWorkspaceId: String? = null,
val line: Int = -1,
val column: Int = -1,
val isRefreshVfsNeeded: Boolean = true,
/**
* Used to build presentable name of project or as content root for a dummy project.
* Whether to run DirectoryProjectConfigurator if a new project or no modules.
*/
val contentRoot: Path? = null,
/**
* Ignored if isNewProject is set to true.
*/
val runConfiguratorsIfNoModules: Boolean = !(ApplicationManager.getApplication()?.isUnitTestMode ?: false),
val runConfigurators: Boolean = false,
val runConversionBeforeOpen: Boolean = true) {
constructor(forceOpenInNewFrame: Boolean, projectToClose: Project?) : this(forceOpenInNewFrame = forceOpenInNewFrame, projectToClose = projectToClose, useDefaultProjectAsTemplate = true)
@ApiStatus.Internal
fun withBeforeProjectCallback(callback: BiPredicate<Project, Module?>) = copy(beforeProjectOpen = callback)
fun withBeforeProjectCallback(callback: Predicate<Project>) = copy(beforeProjectOpen = callback)
@ApiStatus.Internal
fun withProjectName(value: String?) = copy(projectName = value)
@ApiStatus.Internal
fun withNewProject(value: Boolean) = copy(isNewProject = value)
companion object {
@JvmStatic
fun newProject(useDefaultProjectAsTemplate: Boolean): OpenProjectTask {
return OpenProjectTask(useDefaultProjectAsTemplate = useDefaultProjectAsTemplate, isNewProject = true)
@JvmOverloads
fun newProject(runConfigurators: Boolean = false): OpenProjectTask {
return OpenProjectTask(isNewProject = true, runConfigurators = runConfigurators)
}
@JvmStatic
fun newProjectWithCallback(projectToClose: Project?, callback: ProjectOpenedCallback?, isRefreshVfsNeeded: Boolean): OpenProjectTask {
return OpenProjectTask(projectToClose = projectToClose, isNewProject = true, callback = callback, isRefreshVfsNeeded = isRefreshVfsNeeded)
fun newProjectAndRunConfigurators(projectToClose: Project?, isRefreshVfsNeeded: Boolean): OpenProjectTask {
return OpenProjectTask(isNewProject = true, projectToClose = projectToClose, runConfigurators = true, isRefreshVfsNeeded = isRefreshVfsNeeded)
}
@JvmStatic
fun withProjectToClose(projectToClose: Project?): OpenProjectTask {
return OpenProjectTask(projectToClose = projectToClose, project = null)
@JvmOverloads
fun withProjectToClose(projectToClose: Project?, forceOpenInNewFrame: Boolean = false): OpenProjectTask {
return OpenProjectTask(projectToClose = projectToClose, project = null, forceOpenInNewFrame = forceOpenInNewFrame)
}
@JvmStatic
fun withCreatedProject(project: Project?, contentRoot: Path?): OpenProjectTask {
return OpenProjectTask(project = project, contentRoot = contentRoot)
fun withCreatedProject(project: Project?): OpenProjectTask {
return OpenProjectTask(project = project)
}
}
@@ -111,7 +111,11 @@ public final class ProjectUtil {
}
public static Project openOrImport(@NotNull Path path, Project projectToClose, boolean forceOpenInNewFrame) {
return openOrImport(path, new OpenProjectTask(forceOpenInNewFrame, projectToClose));
return openOrImport(path, OpenProjectTask.withProjectToClose(projectToClose, forceOpenInNewFrame));
}
public static Project openOrImport(@NotNull Path path) {
return openOrImport(path, new OpenProjectTask());
}
/**
@@ -122,8 +126,8 @@ public final class ProjectUtil {
* installed importers (regardless of opening/import result)
* null otherwise
*/
public static @Nullable Project openOrImport(@NotNull String path, Project projectToClose, boolean forceOpenInNewFrame) {
return openOrImport(Paths.get(path), new OpenProjectTask(forceOpenInNewFrame, projectToClose));
public static @Nullable Project openOrImport(@NotNull String path, @Nullable Project projectToClose, boolean forceOpenInNewFrame) {
return openOrImport(Paths.get(path), OpenProjectTask.withProjectToClose(projectToClose, forceOpenInNewFrame));
}
public static @Nullable Project openOrImport(@NotNull Path file, @NotNull OpenProjectTask options) {
@@ -151,7 +155,7 @@ public final class ProjectUtil {
}
if (isValidProjectPath(file)) {
return ProjectManagerEx.getInstanceEx().loadAndOpenProject(file, options);
return ProjectManagerEx.getInstanceEx().openProject(file, options);
}
if (options.checkDirectoryForFileBasedProjects && Files.isDirectory(file)) {
@@ -206,8 +210,7 @@ public final class ProjectUtil {
@NotNull Path file,
@NotNull OpenProjectTask options) {
if (processors.size() == 1 && processors.get(0) instanceof PlatformProjectOpenProcessor) {
options.isNewProject = !isValidProjectPath(file);
Project project = PlatformProjectOpenProcessor.doOpenProject(file, options);
Project project = PlatformProjectOpenProcessor.doOpenProject(file, options.withNewProject(!isValidProjectPath(file)));
if (project != null) {
project.putUserData(PlatformProjectOpenProcessor.PROJECT_OPENED_BY_PLATFORM_PROCESSOR, Boolean.TRUE);
}
@@ -223,7 +226,7 @@ public final class ProjectUtil {
ApplicationManager.getApplication().invokeAndWait(() -> {
ProjectOpenProcessor processor = selectOpenProcessor(processors, virtualFile);
if (processor != null) {
Project project = processor.doOpenProject(virtualFile, options.projectToClose, options.forceOpenInNewFrame);
Project project = processor.doOpenProject(virtualFile, options.getProjectToClose(), options.getForceOpenInNewFrame());
if (project != null && processor instanceof PlatformProjectOpenProcessor) {
project.putUserData(PlatformProjectOpenProcessor.PROJECT_OPENED_BY_PLATFORM_PROCESSOR, Boolean.TRUE);
}
@@ -259,7 +262,7 @@ public final class ProjectUtil {
}
public static @Nullable Project openProject(@NotNull String path, @Nullable Project projectToClose, boolean forceOpenInNewFrame) {
return openProject(Paths.get(path), new OpenProjectTask(forceOpenInNewFrame, projectToClose));
return openProject(Paths.get(path), OpenProjectTask.withProjectToClose(projectToClose, forceOpenInNewFrame));
}
public static @Nullable Project openProject(@NotNull Path file, @NotNull OpenProjectTask options) {
@@ -289,7 +292,7 @@ public final class ProjectUtil {
}
try {
return ProjectManagerEx.getInstanceEx().loadAndOpenProject(file, options);
return ProjectManagerEx.getInstanceEx().openProject(file, options);
}
catch (Exception e) {
Messages.showMessageDialog(IdeBundle.message("error.cannot.load.project", e.getMessage()),
@@ -490,7 +493,7 @@ public final class ProjectUtil {
Project result = null;
for (File file : list) {
result = openOrImport(file.toPath().toAbsolutePath(), project, true);
result = openOrImport(file.toPath().toAbsolutePath(), OpenProjectTask.withProjectToClose(project, true));
if (result != null) {
LOG.debug(location + ": load project from ", file);
return result;
@@ -24,8 +24,9 @@ public abstract class ProjectManagerEx extends ProjectManager {
}
/**
* @param filePath path to .ipr file or directory where .idea directory is located
* @deprecated Use {@link #newProject(Path, OpenProjectTask)}
*/
@Deprecated
public abstract @Nullable Project newProject(@Nullable String projectName, @NotNull String filePath, boolean useDefaultProjectSettings, boolean isDummy);
/**
@@ -46,8 +47,7 @@ public abstract class ProjectManagerEx extends ProjectManager {
return loadProject(Paths.get(filePath).toAbsolutePath());
}
@ApiStatus.Internal
public abstract @Nullable Project loadAndOpenProject(@NotNull Path projectStoreBaseDir, @NotNull OpenProjectTask options);
public abstract @Nullable Project openProject(@NotNull Path projectStoreBaseDir, @NotNull OpenProjectTask options);
public abstract @NotNull Project loadProject(@NotNull Path path);
@@ -68,17 +68,6 @@ public abstract class ProjectManagerEx extends ProjectManager {
// return true if successful
public abstract boolean closeAndDisposeAllProjects(boolean checkCanClose);
/**
* Save, close and dispose project. Please note that only the project will be saved, but not the application.
* @return true on success
*/
public abstract boolean closeAndDispose(@NotNull Project project);
@Override
public @Nullable Project createProject(@Nullable String name, @NotNull String path) {
return newProject(name, path, true, false);
}
public abstract @Nullable Project findOpenProjectByHash(@Nullable String locationHash);
@ApiStatus.Internal
@@ -39,7 +39,7 @@ import kotlin.math.min
internal open class ProjectFrameAllocator {
companion object {
internal fun getPresentableName(options: OpenProjectTask, projectStoreBaseDir: Path): String {
return options.projectName ?: (options.contentRoot ?: projectStoreBaseDir).fileName.toString()
return options.projectName ?: projectStoreBaseDir.fileName.toString()
}
}
@@ -26,7 +26,6 @@ import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.platform.PlatformProjectOpenProcessor
@@ -42,13 +41,20 @@ import java.util.concurrent.Future
@ApiStatus.Internal
open class ProjectManagerExImpl : ProjectManagerImpl() {
override fun loadAndOpenProject(originalFilePath: String): Project? {
val projectStoreBaseDir = Paths.get(FileUtilRt.toSystemIndependentName(toCanonicalName(originalFilePath)))
return loadAndOpenProject(projectStoreBaseDir, OpenProjectTask())
final override fun createProject(name: String?, path: String): Project? {
return newProject(Paths.get(toCanonicalName(path)), OpenProjectTask(isNewProject = true, runConfigurators = false).withProjectName(name))
}
override fun loadAndOpenProject(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
return openExistingProject(projectStoreBaseDir, options, this)
final override fun newProject(projectName: String?, path: String, useDefaultProjectAsTemplate: Boolean, isDummy: Boolean): Project? {
return newProject(Paths.get(toCanonicalName(path)), OpenProjectTask(isNewProject = true, useDefaultProjectAsTemplate = useDefaultProjectAsTemplate, projectName = projectName))
}
final override fun loadAndOpenProject(originalFilePath: String): Project? {
return openProject(Paths.get(toCanonicalName(originalFilePath)), OpenProjectTask())
}
final override fun openProject(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
return doOpenProject(projectStoreBaseDir, options, this)
}
@ApiStatus.Internal
@@ -77,7 +83,7 @@ open class ProjectManagerExImpl : ProjectManagerImpl() {
}
}
private fun openExistingProject(projectStoreBaseDir: Path, options: OpenProjectTask, projectManager: ProjectManagerExImpl): Project? {
private fun doOpenProject(projectStoreBaseDir: Path, options: OpenProjectTask, projectManager: ProjectManagerExImpl): Project? {
if (options.project != null && projectManager.isProjectOpened(options.project)) {
return null
}
@@ -115,7 +121,7 @@ private fun openExistingProject(projectStoreBaseDir: Path, options: OpenProjectT
val project = result.project
frameAllocator.projectLoaded(project)
if ((options.beforeProjectOpen == null || options.beforeProjectOpen.test(project, result.module)) && projectManager.doOpenProject(project)) {
if (projectManager.doOpenProject(project)) {
frameAllocator.projectOpened(project)
result
}
@@ -152,12 +158,13 @@ private fun prepareProject(options: OpenProjectTask, projectStoreBaseDir: Path,
indicator?.text = ""
}
if (project == null) {
if (project == null || (options.beforeProjectOpen != null && !options.beforeProjectOpen.test(project))) {
return null
}
if (options.isNewProject || (options.runConfiguratorsIfNoModules && ModuleManager.getInstance(project).modules.isEmpty())) {
if (options.runConfigurators && (options.isNewProject || ModuleManager.getInstance(project).modules.isEmpty())) {
val module = PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(projectStoreBaseDir, project, options.isNewProject)
options.preparedToOpen?.invoke(module)
return PrepareProjectResult(project, module)
}
else {
@@ -165,7 +172,32 @@ private fun prepareProject(options: OpenProjectTask, projectStoreBaseDir: Path,
}
}
private fun checkExistingProjectOnOpen(projectToClose: Project, callback: ProjectOpenedCallback?, projectDir: Path?, projectManager: ProjectManagerExImpl): Boolean {
private fun convertAndLoadProject(path: Path, options: OpenProjectTask): Project? {
var conversionResult: ConversionResult? = null
if (options.runConversionBeforeOpen) {
conversionResult = runMainActivity("project conversion") {
ConversionService.getInstance().convert(path)
}
if (conversionResult.openingIsCanceled()) {
return null
}
}
val project = ProjectManagerImpl.instantiateProject(path, options.projectName)
// template as null because convertAndLoadProject method is called only for an existing project
ProjectManagerImpl.initProject(path, project, options.isRefreshVfsNeeded, null, ProgressManager.getInstance().progressIndicator)
if (conversionResult != null && !conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).runAfterOpened {
conversionResult.postStartupActivity(project)
}
}
return project
}
private fun checkExistingProjectOnOpen(projectToClose: Project,
callback: ProjectOpenedCallback?,
projectDir: Path?,
projectManager: ProjectManagerExImpl): Boolean {
val settings = GeneralSettings.getInstance()
val isValidProject = projectDir != null && ProjectUtil.isValidProjectPath(projectDir)
if (projectDir != null && ProjectAttachProcessor.canAttachToProject() &&
@@ -203,27 +235,6 @@ private fun checkExistingProjectOnOpen(projectToClose: Project, callback: Projec
return false
}
private fun convertAndLoadProject(path: Path, options: OpenProjectTask): Project? {
var conversionResult: ConversionResult? = null
if (options.runConversionBeforeOpen) {
conversionResult = runMainActivity("project conversion") {
ConversionService.getInstance().convert(path)
}
if (conversionResult.openingIsCanceled()) {
return null
}
}
val project = ProjectManagerImpl.instantiateProject(path, options.projectName)
ProjectManagerImpl.initProject(path, project, options.isRefreshVfsNeeded, null, ProgressManager.getInstance().progressIndicator)
if (conversionResult != null && !conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).registerPostStartupActivity {
conversionResult.postStartupActivity(project)
}
}
return project
}
private fun openProject(project: Project, indicator: ProgressIndicator?): Future<*> {
val waitEdtActivity = StartUpMeasurer.startMainActivity("placing calling projectOpened on event queue")
if (indicator != null) {
@@ -51,7 +51,6 @@ import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
@@ -163,10 +162,6 @@ public abstract class ProjectManagerImpl extends ProjectManagerEx implements Dis
private static long CHECK_START = System.currentTimeMillis();
private final Map<Project, String> myProjects = new WeakHashMap<>();
@Override
public @Nullable Project newProject(@Nullable String projectName, @NotNull String filePath, boolean useDefaultProjectSettings, boolean isDummy) {
return newProject(Paths.get(toCanonicalName(filePath)), OpenProjectTask.newProject(useDefaultProjectSettings).withProjectName(projectName));
}
@Override
public @Nullable Project newProject(@NotNull Path projectFile, @NotNull OpenProjectTask options) {
@@ -179,7 +174,7 @@ public abstract class ProjectManagerImpl extends ProjectManagerEx implements Dis
if (Files.isRegularFile(projectFile)) {
try {
FileUtil.delete(projectFile);
Files.deleteIfExists(projectFile);
}
catch (IOException ignored) {
}
@@ -196,7 +191,7 @@ public abstract class ProjectManagerImpl extends ProjectManagerEx implements Dis
ProjectImpl project = instantiateProject(projectFile, options.getProjectName());
try {
Project template = options.useDefaultProjectAsTemplate ? getDefaultProject() : null;
Project template = options.getUseDefaultProjectAsTemplate() ? getDefaultProject() : null;
initProject(projectFile, project, options.isRefreshVfsNeeded(), template, ProgressManager.getInstance().getProgressIndicator());
if (LOG_PROJECT_LEAKAGE_IN_TESTS) {
myProjects.put(project, null);
@@ -29,7 +29,6 @@ import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import java.util.function.BiPredicate
private val LOG = logger<PlatformProjectOpenProcessor>()
private val EP_NAME = ExtensionPointName<DirectoryProjectConfigurator>("com.intellij.directoryProjectConfigurator")
@@ -80,7 +79,11 @@ class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectO
line: Int,
callback: ProjectOpenedCallback?,
options: EnumSet<Option>): Project? {
val openProjectOptions = OpenProjectTask(forceOpenInNewFrame = options.contains(Option.FORCE_NEW_FRAME), projectToClose = projectToClose, callback = callback, line = line)
val openProjectOptions = OpenProjectTask(forceOpenInNewFrame = options.contains(Option.FORCE_NEW_FRAME),
projectToClose = projectToClose,
callback = callback,
runConfigurators = callback != null,
line = line)
return doOpenProject(Paths.get(virtualFile.path), openProjectOptions)
}
@@ -89,9 +92,9 @@ class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectO
fun createTempProjectAndOpenFile(file: Path, options: OpenProjectTask): Project? {
val dummyProjectName = file.fileName.toString()
val baseDir = FileUtilRt.createTempDirectory(dummyProjectName, null, true).toPath()
val copy = options.copy(isNewProject = true, projectName = dummyProjectName, contentRoot = file, beforeProjectOpen = BiPredicate { _, module ->
val copy = options.copy(isNewProject = true, projectName = dummyProjectName, runConfigurators = true, preparedToOpen = { module ->
// add content root for chosen (single) file
ModuleRootModificationUtil.updateModel(module!!) { model ->
ModuleRootModificationUtil.updateModel(module) { model ->
val entries = model.contentEntries
// remove custom content entry created for temp directory
if (entries.size == 1) {
@@ -99,18 +102,18 @@ class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectO
}
model.addContentEntry(VfsUtilCore.pathToUrl(file.toString()))
}
true
})
val project = ProjectManagerEx.getInstanceEx().loadAndOpenProject(baseDir, copy) ?: return null
val project = ProjectManagerEx.getInstanceEx().openProject(baseDir, copy) ?: return null
openFileFromCommandLine(project, file, copy.line, copy.column)
return project
}
@ApiStatus.Internal
@JvmStatic
fun doOpenProject(file: Path, options: OpenProjectTask): Project? {
fun doOpenProject(file: Path, originalOptions: OpenProjectTask): Project? {
LOG.info("Opening $file")
var baseDir = file
var options = originalOptions
if (!Files.isDirectory(file)) {
if (LightEditUtil.openFile(file)) {
return LightEditUtil.getProject()
@@ -129,7 +132,7 @@ class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectO
}
baseDir = file.parent
options.isNewProject = !Files.isDirectory(baseDir.resolve(Project.DIRECTORY_STORE_FOLDER))
options = options.copy(isNewProject = !Files.isDirectory(baseDir.resolve(Project.DIRECTORY_STORE_FOLDER)))
}
else {
baseDir = baseDirCandidate
@@ -137,7 +140,7 @@ class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectO
}
}
val project = ProjectManagerEx.getInstanceEx().loadAndOpenProject(baseDir, if (baseDir == file) options else options.copy(contentRoot = file))
val project = ProjectManagerEx.getInstanceEx().openProject(baseDir, if (baseDir == file) options else options.copy(projectName = file.fileName.toString()))
if (project != null && file != baseDir && !Files.isDirectory(file)) {
openFileFromCommandLine(project, file, options.line, options.column)
}
@@ -149,10 +152,10 @@ class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectO
@Deprecated(message = "If project base dir differs from project store base dir, specify it as contentRoot in the options", level = DeprecationLevel.ERROR)
fun openExistingProject(file: Path, projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
if (file == projectStoreBaseDir) {
return ProjectManagerEx.getInstanceEx().loadAndOpenProject(projectStoreBaseDir, options)
return ProjectManagerEx.getInstanceEx().openProject(projectStoreBaseDir, options)
}
else {
return ProjectManagerEx.getInstanceEx().loadAndOpenProject(projectStoreBaseDir, options.copy(contentRoot = file))
return ProjectManagerEx.getInstanceEx().openProject(projectStoreBaseDir, options.copy(projectName = file.fileName.toString()))
}
}
@@ -191,11 +194,12 @@ class PlatformProjectOpenProcessor : ProjectOpenProcessor(), CommandLineProjectO
override fun lookForProjectsInDirectory() = false
override fun doOpenProject(virtualFile: VirtualFile, projectToClose: Project?, forceOpenInNewFrame: Boolean): Project? {
val baseDir = virtualFile.toNioPath()
// doesn't make sense to use default project in tests for heavy projects
val options = OpenProjectTask(forceOpenInNewFrame = forceOpenInNewFrame, projectToClose = projectToClose, useDefaultProjectAsTemplate = !ApplicationManager.getApplication().isUnitTestMode)
val baseDir = Paths.get(virtualFile.path)
options.isNewProject = !ProjectUtil.isValidProjectPath(baseDir)
return doOpenProject(baseDir, options)
return doOpenProject(baseDir, OpenProjectTask(forceOpenInNewFrame = forceOpenInNewFrame,
projectToClose = projectToClose,
isNewProject = !ProjectUtil.isValidProjectPath(baseDir),
useDefaultProjectAsTemplate = !ApplicationManager.getApplication().isUnitTestMode))
}
override fun openProjectAndFile(virtualFile: VirtualFile, line: Int, column: Int, tempProject: Boolean): Project? {
@@ -26,7 +26,7 @@ final class RecentProjectApplication extends ApplicationStarterBase {
@NotNull
@Override
protected Future<CliResult> processCommand(@NotNull List<String> args, @Nullable String currentDirectory) {
ProjectManagerEx.getInstanceEx().loadAndOpenProject(Paths.get(args.get(1)).normalize(), new OpenProjectTask());
ProjectManagerEx.getInstanceEx().openProject(Paths.get(args.get(1)).normalize(), new OpenProjectTask());
return CompletableFuture.completedFuture(CliResult.OK);
}
}
@@ -18,6 +18,7 @@ import com.intellij.testFramework.LightPlatformTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.util.ArrayUtil;
import org.jdom.Element;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.nio.file.Files;
@@ -92,7 +93,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase {
assertNotNull(myTemplateManager.getTemplate("foo.txt"));
File foo = FileUtilRt.createTempDirectory("foo", null, false);
final Project project = ProjectManager.getInstance().createProject("foo", foo.getPath());
Project project = PlatformTestUtil.loadAndOpenProject(foo.toPath());
try {
assertNotNull(project);
assertNotNull(FileTemplateManager.getInstance(project).getTemplate("foo.txt"));
@@ -106,7 +107,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase {
public void testSurviveOnProjectReopen() throws Exception {
File foo = FileUtilRt.createTempDirectory("foo", null, false);
Project reloaded = null;
final Project project = ProjectManager.getInstance().createProject("foo", foo.getPath());
Project project = PlatformTestUtil.loadAndOpenProject(foo.toPath());
try {
assertThat(project).isNotNull();
FileTemplateManager manager = FileTemplateManager.getInstance(project);
@@ -138,7 +139,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase {
public void testAddRemoveShared() throws Exception {
File foo = FileUtilRt.createTempDirectory("foo", null, false);
final Project project = ProjectManager.getInstance().createProject("foo", foo.getPath());
Project project = PlatformTestUtil.loadAndOpenProject(foo.toPath());
try {
assertThat(project).isNotNull();
FileTemplateManager manager = FileTemplateManager.getInstance(project);
@@ -179,7 +180,7 @@ public class LightFileTemplatesTest extends LightPlatformTestCase {
}
}
private static void closeProject(final Project project) {
private static void closeProject(@Nullable Project project) {
if (project != null && !project.isDisposed()) {
PlatformTestUtil.forceCloseProjectWithoutSaving(project);
}
@@ -1,6 +1,5 @@
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("UsePropertyAccessSyntax")
package com.intellij.openapi.fileEditor.impl
import com.intellij.diagnostic.ThreadDumper
@@ -8,8 +7,8 @@ import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectServiceContainerCustomizer
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.impl.ProjectServiceContainerCustomizer
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.project.stateStore
import com.intellij.testFramework.*
@@ -84,7 +83,7 @@ class EditorHistoryManagerTest {
}
private fun openProjectPerformTaskCloseProject(projectDir: Path, task: (Project) -> Unit) {
val project = ProjectManagerEx.getInstanceEx().loadAndOpenProject(projectDir, createTestOpenProjectOptions())!!
val project = ProjectManagerEx.getInstanceEx().openProject(projectDir, createTestOpenProjectOptions())!!
try {
runInEdtAndWait {
task(project)
@@ -16,8 +16,8 @@ import com.intellij.testFramework.HeavyPlatformTestCase;
import com.intellij.testFramework.PlatformTestUtil;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
@@ -25,17 +25,17 @@ import static org.assertj.core.api.Assertions.assertThat;
public class ModulesConfigurationTest extends HeavyPlatformTestCase {
public void testAddRemoveModule() throws IOException {
Pair<File, File> result = createProjectWithModule();
File projectDir = result.getFirst();
Pair<Path, Path> result = createProjectWithModule();
Path projectDir = result.getFirst();
Project reloaded = PlatformTestUtil.loadAndOpenProject(projectDir.toPath());
Project reloaded = PlatformTestUtil.loadAndOpenProject(projectDir);
closeOnTearDown(reloaded);
ModuleManager moduleManager = ModuleManager.getInstance(reloaded);
Module module = assertOneElement(moduleManager.getModules());
moduleManager.disposeModule(module);
closeProject(reloaded, true);
reloaded = PlatformTestUtil.loadAndOpenProject(projectDir.toPath());
reloaded = PlatformTestUtil.loadAndOpenProject(projectDir);
closeOnTearDown(reloaded);
assertEmpty(ModuleManager.getInstance(reloaded).getModules());
closeProject(reloaded, false);
@@ -43,15 +43,15 @@ public class ModulesConfigurationTest extends HeavyPlatformTestCase {
// because of external storage, imls file can be missed on disk and it is not error
public void testRemoveFailedToLoadModule() throws IOException {
Pair<File, File> result = createProjectWithModule();
File projectDir = result.getFirst();
File moduleFile = result.getSecond();
Pair<Path, Path> result = createProjectWithModule();
Path projectDir = result.getFirst();
Path moduleFile = result.getSecond();
assertThat(moduleFile).exists();
WriteAction.run(() -> LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleFile).delete(this));
WriteAction.run(() -> LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtil.toSystemIndependentName(moduleFile.toString())).delete(this));
List<ConfigurationErrorDescription> errors = new ArrayList<>();
ProjectLoadingErrorsHeadlessNotifier.setErrorHandler(errors::add, getTestRootDisposable());
Project reloaded = PlatformTestUtil.loadAndOpenProject(projectDir.toPath());
Project reloaded = PlatformTestUtil.loadAndOpenProject(projectDir);
closeOnTearDown(reloaded);
ModuleManager moduleManager = ModuleManager.getInstance(reloaded);
assertThat(moduleManager.getModules()).hasSize(1);
@@ -59,21 +59,20 @@ public class ModulesConfigurationTest extends HeavyPlatformTestCase {
closeProject(reloaded, true);
errors.clear();
reloaded = PlatformTestUtil.loadAndOpenProject(projectDir.toPath());
reloaded = PlatformTestUtil.loadAndOpenProject(projectDir);
closeOnTearDown(reloaded);
assertEmpty(errors);
closeProject(reloaded, false);
}
@NotNull
private Pair<File, File> createProjectWithModule() throws IOException {
File projectDir = FileUtil.createTempDirectory("project", null);
Project project = ProjectManager.getInstance().createProject("project", projectDir.getAbsolutePath());
private @NotNull Pair<Path, Path> createProjectWithModule() throws IOException {
Path projectDir = FileUtil.createTempDirectory("project", null).toPath();
Project project = PlatformTestUtil.loadAndOpenProject(projectDir);
closeOnTearDown(project);
File moduleFile = new File(projectDir, "module.iml");
WriteAction.run(() -> ModuleManager.getInstance(project).newModule(moduleFile.getPath(), EmptyModuleType.EMPTY_MODULE));
Path moduleFile = projectDir.resolve("module.iml");
WriteAction.run(() -> ModuleManager.getInstance(project).newModule(moduleFile.toString(), EmptyModuleType.EMPTY_MODULE));
closeProject(project, true);
return Pair.create(projectDir, moduleFile);
return new Pair<>(projectDir, moduleFile);
}
private static void closeProject(@NotNull Project project, boolean isSave) {
@@ -11,7 +11,6 @@ import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
@@ -54,7 +53,7 @@ class ProjectOpeningTest {
val foo = tempDir.newPath()
ProgressManager.getInstance().run(object : Task.Modal(null, "", true) {
override fun run(indicator: ProgressIndicator) {
val project = ProjectManagerEx.getInstanceEx().loadAndOpenProject(foo, createTestOpenProjectOptions())
val project = ProjectManagerEx.getInstanceEx().openProject(foo, createTestOpenProjectOptions())
if (project != null) {
runInEdtAndWait {
PlatformTestUtil.forceCloseProjectWithoutSaving(project)
@@ -86,7 +85,7 @@ class ProjectOpeningTest {
}
})
runModalTask("") {
project = ProjectManagerEx.getInstanceEx().loadAndOpenProject(foo, createTestOpenProjectOptions())!!
project = ProjectManagerEx.getInstanceEx().openProject(foo, createTestOpenProjectOptions())!!
}
assertThat(project.isOpen).isFalse()
assertThat(project.isDisposed).isTrue()
@@ -124,7 +123,7 @@ class ProjectOpeningTest {
projectDir.createDirectories()
val iprFilePath = projectDir.resolve("project.ipr")
val fileBasedProject = ProjectManager.getInstance().createProject(iprFilePath.fileName.toString(), iprFilePath.toAbsolutePath().toString())!!
val fileBasedProject = PlatformTestUtil.loadAndOpenProject(iprFilePath)
Disposer.register(disposableRule.disposable, Disposable {
runInEdtAndWait { closeProject(fileBasedProject) }
})
@@ -10,6 +10,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Path;
/**
* Provides project management.
@@ -99,11 +100,15 @@ public abstract class ProjectManager {
public abstract @Nullable Project loadAndOpenProject(@NotNull String filePath) throws IOException, JDOMException;
/**
* Closes the specified project, but does not dispose it.
*
* @param project the project to close.
* @return true if the project was closed successfully, false if the closing was disallowed by the close listeners.
* Save, close and dispose project. Please note that only the project will be saved, but not the application.
* @return true on success
*/
public abstract boolean closeAndDispose(@NotNull Project project);
/**
* @deprecated Use {@link #closeAndDispose}
*/
@Deprecated
public abstract boolean closeProject(@NotNull Project project);
/**
@@ -115,12 +120,8 @@ public abstract class ProjectManager {
public abstract void reloadProject(@NotNull Project project);
/**
* Create new project in given location.
*
* @param name project name
* @param path project location
*
* @return newly crated project
* @deprecated Use {@link com.intellij.openapi.project.ex.ProjectManagerEx#newProject(Path, com.intellij.ide.impl.OpenProjectTask)}
*/
@Deprecated
public abstract @Nullable Project createProject(@Nullable String name, @NotNull String path);
}
@@ -267,7 +267,7 @@ inline fun <T> Project.runInLoadComponentStateMode(task: () -> T): T {
}
fun createHeavyProject(path: Path, useDefaultProjectAsTemplate: Boolean = false): Project {
return ProjectManagerEx.getInstanceEx().newProject(path, null, OpenProjectTask(useDefaultProjectAsTemplate = useDefaultProjectAsTemplate, isNewProject = true))!!
return ProjectManagerEx.getInstanceEx().newProject(path, OpenProjectTask(useDefaultProjectAsTemplate = useDefaultProjectAsTemplate, isNewProject = true))!!
}
fun createTestOpenProjectOptions(): OpenProjectTask {
@@ -276,7 +276,7 @@ fun createTestOpenProjectOptions(): OpenProjectTask {
return OpenProjectTask(forceOpenInNewFrame = true,
isRefreshVfsNeeded = false,
runConversionBeforeOpen = false,
runConfiguratorsIfNoModules = false,
runConfigurators = false,
showWelcomeScreen = false,
useDefaultProjectAsTemplate = false)
}
@@ -265,7 +265,7 @@ public abstract class HeavyPlatformTestCase extends UsefulTestCase implements Da
public static @NotNull Project createProject(@NotNull Path file) {
try {
return Objects.requireNonNull(ProjectManagerEx.getInstanceEx().newProject(file, null, FixtureRuleKt.createTestOpenProjectOptions()));
return Objects.requireNonNull(ProjectManagerEx.getInstanceEx().newProject(file, FixtureRuleKt.createTestOpenProjectOptions()));
}
catch (TooManyProjectLeakedException e) {
if (ourReportedLeakedProjects) {
@@ -1098,7 +1098,7 @@ public final class PlatformTestUtil {
}
public static @NotNull Project loadAndOpenProject(@NotNull Path path) {
Project project = ProjectManagerEx.getInstanceEx().loadAndOpenProject(path, FixtureRuleKt.createTestOpenProjectOptions());
Project project = ProjectManagerEx.getInstanceEx().openProject(path, FixtureRuleKt.createTestOpenProjectOptions());
if (ApplicationManager.getApplication().isDispatchThread()) {
dispatchAllInvocationEventsInIdeEventQueue();
}
@@ -1,22 +1,7 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* 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.
*/
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util;
public class EmptyConsumer {
public final class EmptyConsumer {
public static <T> Consumer<T> getInstance() {
//noinspection unchecked,deprecation
return (Consumer<T>)Consumer.EMPTY_CONSUMER;
@@ -1,5 +1,4 @@
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes;
import com.intellij.openapi.application.ApplicationManager;
@@ -14,7 +13,6 @@ import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.util.containers.ContainerUtil;
@@ -32,7 +30,7 @@ import static java.util.Objects.hash;
import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toList;
public class ChangesUtil {
public final class ChangesUtil {
private static final Key<Boolean> INTERNAL_OPERATION_KEY = Key.create("internal vcs operation");
public static final TObjectHashingStrategy<FilePath> CASE_SENSITIVE_FILE_PATH_HASHING_STRATEGY = new TObjectHashingStrategy<FilePath>() {
@@ -246,14 +244,18 @@ public class ChangesUtil {
});
}
@Nullable
public static String getProjectRelativePath(@NotNull Project project, @Nullable File fileName) {
if (fileName == null) return null;
VirtualFile baseDir = project.getBaseDir();
if (baseDir == null) return fileName.toString();
String relativePath = FileUtil.getRelativePath(VfsUtilCore.virtualToIoFile(baseDir), fileName);
if (relativePath != null) return relativePath;
return fileName.toString();
public static @Nullable String getProjectRelativePath(@NotNull Project project, @Nullable File fileName) {
if (fileName == null) {
return null;
}
String baseDir = project.getBasePath();
if (baseDir == null) {
return fileName.toString();
}
String relativePath = FileUtil.getRelativePath(new File(baseDir), fileName);
return relativePath == null ? fileName.toString() : relativePath;
}
public static boolean isTextConflictingChange(@NotNull Change change) {
@@ -1,10 +1,11 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.impl;
import com.intellij.conversion.ConversionResult;
import com.intellij.conversion.impl.ConversionRunner;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vcs.AbstractVcsHelper;
@@ -21,7 +22,7 @@ import org.jetbrains.annotations.NotNull;
import java.nio.file.Path;
import java.util.*;
public class ConversionResultImpl implements ConversionResult {
public final class ConversionResultImpl implements ConversionResult {
public static final ConversionResultImpl CONVERSION_NOT_NEEDED = new ConversionResultImpl(false, false, false);
public static final ConversionResultImpl CONVERSION_CANCELED = new ConversionResultImpl(true, true, false);
public static final ConversionResultImpl ERROR_OCCURRED = new ConversionResultImpl(true, false, true);
@@ -57,8 +58,8 @@ public class ConversionResultImpl implements ConversionResult {
@Override
public void postStartupActivity(@NotNull Project project) {
final Application application = ApplicationManager.getApplication();
if (application.isHeadlessEnvironment() || application.isUnitTestMode()) {
Application app = ApplicationManager.getApplication();
if (app.isHeadlessEnvironment() || app.isUnitTestMode()) {
return;
}
@@ -67,20 +68,24 @@ public class ConversionResultImpl implements ConversionResult {
EditAction.editFilesAndShowErrors(project, changedFiles);
}
final List<VirtualFile> createdFiles = findVirtualFiles(myCreatedFiles);
if (containsFilesUnderVcs(createdFiles, project)) {
final Collection<VirtualFile> selected = AbstractVcsHelper.getInstance(project)
List<VirtualFile> createdFiles = findVirtualFiles(myCreatedFiles);
if (!containsFilesUnderVcs(createdFiles, project)) {
return;
}
ApplicationManager.getApplication().invokeLater(() -> {
Collection<VirtualFile> selected = AbstractVcsHelper.getInstance(project)
.selectFilesToProcess(createdFiles, VcsBundle.message("dialog.title.files.created"),
VcsBundle.message("label.select.files.to.be.added.to.version.control"), null, null,
VcsShowConfirmationOption.STATIC_SHOW_CONFIRMATION);
if (selected != null && !selected.isEmpty()) {
final ChangeListManagerImpl changeListManager = ChangeListManagerImpl.getInstanceImpl(project);
ChangeListManagerImpl changeListManager = ChangeListManagerImpl.getInstanceImpl(project);
changeListManager.addUnversionedFiles(changeListManager.getDefaultChangeList(), new ArrayList<>(selected));
}
}
}, ModalityState.NON_MODAL, project.getDisposed());
}
private static boolean containsFilesUnderVcs(List<? extends VirtualFile> files, Project project) {
private static boolean containsFilesUnderVcs(@NotNull List<VirtualFile> files, Project project) {
for (VirtualFile file : files) {
if (ChangesUtil.getVcsForFile(file, project) != null) {
return true;
@@ -89,8 +94,8 @@ public class ConversionResultImpl implements ConversionResult {
return false;
}
private static List<VirtualFile> findVirtualFiles(Collection<? extends Path> ioFiles) {
List<VirtualFile> files = new ArrayList<>();
private static @NotNull List<VirtualFile> findVirtualFiles(@NotNull Collection<Path> ioFiles) {
List<VirtualFile> files = new ArrayList<>(ioFiles.size());
for (Path file : ioFiles) {
ContainerUtil.addIfNotNull(files, LocalFileSystem.getInstance().refreshAndFindFileByPath(FileUtil.toSystemIndependentName(file.toString())));
}
@@ -1,5 +1,4 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.actions;
import com.intellij.openapi.actionSystem.AnActionEvent;
@@ -9,49 +8,56 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.vcs.*;
import com.intellij.openapi.vcs.changes.ChangesUtil;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
public class EditAction extends DumbAwareAction {
public final class EditAction extends DumbAwareAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final Project project = e.getData(CommonDataKeys.PROJECT);
Project project = e.getData(CommonDataKeys.PROJECT);
List<VirtualFile> files = e.getData(VcsDataKeys.MODIFIED_WITHOUT_EDITING_DATA_KEY);
assert project != null;
assert files != null;
editFilesAndShowErrors(project, files);
}
public static void editFilesAndShowErrors(Project project, List<? extends VirtualFile> files) {
final List<VcsException> exceptions = new ArrayList<>();
public static void editFilesAndShowErrors(@NotNull Project project, @NotNull List<? extends VirtualFile> files) {
List<VcsException> exceptions = new ArrayList<>();
editFiles(project, files, exceptions);
if (!exceptions.isEmpty()) {
AbstractVcsHelper.getInstance(project).showErrors(exceptions, VcsBundle.message("edit.errors"));
}
}
public static void editFiles(final Project project, final List<? extends VirtualFile> files, final List<? super VcsException> exceptions) {
public static void editFiles(@NotNull Project project, @NotNull List<? extends VirtualFile> files, List<? super VcsException> exceptions) {
ChangesUtil.processVirtualFilesByVcs(project, files, (vcs, items) -> {
final EditFileProvider provider = vcs.getEditFileProvider();
if (provider != null) {
try {
provider.editFiles(VfsUtil.toVirtualFileArray(items));
}
catch (VcsException e1) {
exceptions.add(e1);
}
for(VirtualFile file: items) {
VcsDirtyScopeManager.getInstance(project).fileDirty(file);
FileStatusManager.getInstance(project).fileStatusChanged(file);
}
EditFileProvider provider = vcs.getEditFileProvider();
if (provider == null) {
return;
}
try {
provider.editFiles(VfsUtilCore.toVirtualFileArray(items));
}
catch (VcsException e1) {
exceptions.add(e1);
}
VcsDirtyScopeManager vcsDirtyScopeManager = VcsDirtyScopeManager.getInstance(project);
FileStatusManager fileStatusManager = FileStatusManager.getInstance(project);
for (VirtualFile file : items) {
vcsDirtyScopeManager.fileDirty(file);
fileStatusManager.fileStatusChanged(file);
}
});
}
@Override
public void update(@NotNull final AnActionEvent e) {
public void update(@NotNull AnActionEvent e) {
List<VirtualFile> files = e.getData(VcsDataKeys.MODIFIED_WITHOUT_EDITING_DATA_KEY);
boolean enabled = files != null && !files.isEmpty();
e.getPresentation().setEnabledAndVisible(enabled);
@@ -21,7 +21,7 @@ final class ProjectDirCheckoutListener implements CheckoutListener {
return false;
}
ProjectManagerEx.getInstanceEx().loadAndOpenProject(directory, OpenProjectTask.withProjectToClose(project));
ProjectManagerEx.getInstanceEx().openProject(directory, OpenProjectTask.withProjectToClose(project));
return true;
}
}
@@ -3,6 +3,7 @@ package com.intellij.workspaceModel.ide
import com.intellij.ProjectTopics.PROJECT_ROOTS
import com.intellij.configurationStore.StoreUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runWriteActionAndWait
@@ -12,13 +13,13 @@ import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.rd.attach
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.OrderEntryUtil
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
@@ -29,15 +30,15 @@ import com.intellij.testFramework.TemporaryDirectory
import com.intellij.testFramework.UsefulTestCase.assertEmpty
import com.intellij.testFramework.UsefulTestCase.assertSameElements
import com.intellij.util.ui.UIUtil
import com.intellij.workspaceModel.ide.impl.jps.serialization.asConfigLocation
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.VirtualFileUrlManager
import com.intellij.workspaceModel.storage.toVirtualFileUrl
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl
import com.intellij.workspaceModel.ide.impl.WorkspaceModelInitialTestContent
import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectEntitiesLoader
import com.intellij.workspaceModel.ide.impl.jps.serialization.toConfigLocation
import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.VirtualFileUrlManager
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.*
import com.intellij.workspaceModel.storage.toVirtualFileUrl
import org.jetbrains.jps.model.java.LanguageLevel
import org.jetbrains.jps.model.module.UnknownSourceRootType
import org.jetbrains.jps.model.module.UnknownSourceRootTypeProperties
@@ -238,7 +239,7 @@ class ModuleBridgesTest {
moduleManager.disposeModule(module)
}
val moduleDirUrl = File(project.basePath).toVirtualFileUrl(virtualFileManager)
val moduleDirUrl = virtualFileManager.fromPath(project.basePath!!)
val projectModel = WorkspaceModel.getInstance(project)
projectModel.updateProjectModel {
@@ -316,7 +317,7 @@ class ModuleBridgesTest {
val moduleManager = ModuleManager.getInstance(project)
val dir = File(project.basePath, "dir")
val moduleDirUrl = File(project.basePath).toVirtualFileUrl(virtualFileManager)
val moduleDirUrl = virtualFileManager.fromPath(project.basePath!!)
val projectModel = WorkspaceModel.getInstance(project)
val projectLocation = project.configLocation!!
@@ -392,10 +393,10 @@ class ModuleBridgesTest {
fun `test module libraries loaded from cache`() {
val builder = WorkspaceEntityStorageBuilder.create()
val tempDir = temporaryDirectoryRule.newPath().toFile()
val tempDir = temporaryDirectoryRule.newPath()
val iprFile = File(tempDir, "testProject.ipr")
val configLocation = iprFile.asConfigLocation(virtualFileManager)
val iprFile = tempDir.resolve("testProject.ipr")
val configLocation = toConfigLocation(iprFile, virtualFileManager)
val source = JpsFileEntitySource.FileInDirectory(configLocation.baseDirectoryUrl, configLocation)
val moduleEntity = builder.addModuleEntity(name = "test", dependencies = emptyList(), source = source)
val moduleLibraryEntity = builder.addLibraryEntity(
@@ -412,9 +413,10 @@ class ModuleBridgesTest {
}
WorkspaceModelInitialTestContent.withInitialContent(builder.toStorage()) {
val project = ProjectManager.getInstance().createProject("testProject", iprFile.path)!!
invokeAndWaitIfNeeded { PlatformTestUtil.openProject(project) }
disposableRule.disposable.attach { invokeAndWaitIfNeeded { ProjectManagerEx.getInstanceEx().forceCloseProject(project) } }
val project = PlatformTestUtil.loadAndOpenProject(iprFile)
Disposer.register(disposableRule.disposable, Disposable {
invokeAndWaitIfNeeded { ProjectManagerEx.getInstanceEx().forceCloseProject(project) }
})
val module = ModuleManager.getInstance(project).findModuleByName("test")
@@ -434,22 +436,23 @@ class ModuleBridgesTest {
fun `test libraries are loaded from cache`() {
val builder = WorkspaceEntityStorageBuilder.create()
val tempDir = temporaryDirectoryRule.newPath().toFile()
val tempDir = temporaryDirectoryRule.newPath()
val iprFile = File(tempDir, "testProject.ipr")
val jarUrl = File(tempDir, "a.jar").toVirtualFileUrl(virtualFileManager)
val iprFile = tempDir.resolve("testProject.ipr")
val jarUrl = tempDir.resolve("a.jar").toVirtualFileUrl(virtualFileManager)
builder.addLibraryEntity(
name = "my_lib",
tableId = LibraryTableId.ProjectLibraryTableId,
roots = listOf(LibraryRoot(jarUrl, LibraryRootTypeId("CLASSES"), LibraryRoot.InclusionOptions.ROOT_ITSELF)),
excludedRoots = emptyList(),
source = JpsProjectEntitiesLoader.createJpsEntitySourceForProjectLibrary(iprFile.asConfigLocation(virtualFileManager))
source = JpsProjectEntitiesLoader.createJpsEntitySourceForProjectLibrary(toConfigLocation(iprFile, virtualFileManager))
)
WorkspaceModelInitialTestContent.withInitialContent(builder.toStorage()) {
val project = ProjectManager.getInstance().createProject("testProject", iprFile.path)!!
invokeAndWaitIfNeeded { PlatformTestUtil.openProject(project) }
disposableRule.disposable.attach { invokeAndWaitIfNeeded { ProjectManagerEx.getInstanceEx().forceCloseProject(project) } }
val project = PlatformTestUtil.loadAndOpenProject(iprFile)
Disposer.register(disposableRule.disposable, Disposable {
invokeAndWaitIfNeeded { ProjectManagerEx.getInstanceEx().forceCloseProject(project) }
})
val projectLibraryTable = LibraryTablesRegistrar.getInstance().getLibraryTable(project)
invokeAndWaitIfNeeded { UIUtil.dispatchAllInvocationEvents() }
@@ -662,9 +665,8 @@ class ModuleBridgesTest {
internal fun createEmptyTestProject(temporaryDirectory: TemporaryDirectory, disposableRule: DisposableRule): Project {
val projectDir = temporaryDirectory.newPath("project")
val project = WorkspaceModelInitialTestContent.withInitialContent(WorkspaceEntityStorageBuilder.create()) {
ProjectManager.getInstance().createProject("testProject", projectDir.resolve("testProject.ipr").toString())!!
PlatformTestUtil.loadAndOpenProject(projectDir.resolve("testProject.ipr"))
}
invokeAndWaitIfNeeded { PlatformTestUtil.openProject(project) }
disposableRule.disposable.attach { invokeAndWaitIfNeeded { ProjectManagerEx.getInstanceEx().forceCloseProject(project) } }
return project
}
@@ -1,3 +1,4 @@
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.jps.serialization
import com.intellij.openapi.application.PathMacros
@@ -15,8 +16,10 @@ import junit.framework.AssertionFailedError
import org.jdom.Element
import org.jetbrains.jps.model.serialization.JDomSerializationUtil
import org.jetbrains.jps.util.JpsPathUtil
import org.junit.Assert.*
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import java.io.File
import java.nio.file.Path
internal val sampleDirBasedProjectFile = File(PathManagerEx.getCommunityHomePath(), "jps/model-serialization/testData/sampleProject")
internal val sampleFileBasedProjectFile = File(PathManagerEx.getCommunityHomePath(),
@@ -40,7 +43,7 @@ internal fun copyAndLoadProject(originalProjectFile: File, virtualFileManager: V
FileUtil.copyDir(originalProjectDir, projectDir)
val originalBuilder = WorkspaceEntityStorageBuilder.create()
val projectFile = if (originalProjectFile.isFile) File(projectDir, originalProjectFile.name) else projectDir
val configLocation = projectFile.asConfigLocation(virtualFileManager)
val configLocation = toConfigLocation(projectFile.toPath(), virtualFileManager)
val serializers = loadProject(configLocation, originalBuilder, virtualFileManager) as JpsProjectSerializersImpl
val loadedProjectData = LoadedProjectData(originalBuilder.toStorage(), serializers, configLocation, originalProjectDir)
serializers.checkConsistency(loadedProjectData.projectDirUrl, loadedProjectData.storage, virtualFileManager)
@@ -157,7 +160,7 @@ internal fun assertDirectoryMatches(actualDir: File, expectedDir: File, filesToI
internal fun createProjectSerializers(projectDir: File, virtualFileManager: VirtualFileUrlManager): JpsProjectSerializersImpl {
val reader = CachingJpsFileContentReader(VfsUtilCore.pathToUrl(projectDir.systemIndependentPath))
val externalStoragePath = projectDir.toPath().resolve("cache")
return JpsProjectEntitiesLoader.createProjectSerializers(projectDir.asConfigLocation(virtualFileManager), reader, externalStoragePath, true, virtualFileManager) as JpsProjectSerializersImpl
return JpsProjectEntitiesLoader.createProjectSerializers(toConfigLocation(projectDir.toPath(), virtualFileManager), reader, externalStoragePath, true, virtualFileManager) as JpsProjectSerializersImpl
}
fun JpsProjectSerializersImpl.checkConsistency(projectBaseDirUrl: String, storage: WorkspaceEntityStorage, virtualFileManager: VirtualFileUrlManager) {
@@ -198,7 +201,7 @@ fun JpsProjectSerializersImpl.checkConsistency(projectBaseDirUrl: String, storag
val allSources = storage.entitiesBySource { true }
val urlsFromSources = allSources.keys.filterIsInstance<JpsFileEntitySource>().mapTo(HashSet()) { getNonNullActualFileUrl(it) }
assertEquals(urlsFromSources.sorted(), fileSerializersByUrl.entrySet().filterNot { it.value.all { isSerializerWithoutEntities(it)} }.map { it.key }.sorted())
assertEquals(urlsFromSources.sorted(), fileSerializersByUrl.entrySet().filterNot { entry -> entry.value.all { isSerializerWithoutEntities(it)} }.map { it.key }.sorted())
val fileIdFromEntities = allSources.keys.filterIsInstance(JpsFileEntitySource.FileInDirectory::class.java).mapTo(HashSet()) { it.fileNameId }
val unregisteredIds = fileIdFromEntities - fileIdToFileName.keys.toSet()
@@ -207,9 +210,16 @@ fun JpsProjectSerializersImpl.checkConsistency(projectBaseDirUrl: String, storag
assertTrue("There are stale mapping for some fileNameId: ${staleIds.joinToString { "$it -> ${fileIdToFileName.get(it)}" }}", staleIds.isEmpty())
}
internal fun File.asConfigLocation(virtualFileManager: VirtualFileUrlManager): JpsProjectConfigLocation =
if (FileUtil.extensionEquals(name, "ipr")) JpsProjectConfigLocation.FileBased(toVirtualFileUrl(virtualFileManager))
else JpsProjectConfigLocation.DirectoryBased(toVirtualFileUrl(virtualFileManager))
internal fun File.asConfigLocation(virtualFileManager: VirtualFileUrlManager): JpsProjectConfigLocation = toConfigLocation(toPath(), virtualFileManager)
internal fun toConfigLocation(file: Path, virtualFileManager: VirtualFileUrlManager): JpsProjectConfigLocation {
if (FileUtil.extensionEquals(file.fileName.toString(), "ipr")) {
return JpsProjectConfigLocation.FileBased(file.toVirtualFileUrl(virtualFileManager))
}
else {
return JpsProjectConfigLocation.DirectoryBased(file.toVirtualFileUrl(virtualFileManager))
}
}
internal class JpsFileContentWriterImpl : JpsFileContentWriter {
val urlToComponents = LinkedHashMap<String, LinkedHashMap<String, Element?>>()
@@ -60,4 +60,5 @@ fun VirtualFileUrl.append(relativePath: String): VirtualFileUrl {
// TODO It's possible to write it without additional string allocations besides absolutePath
fun File.toVirtualFileUrl(virtualFileManager: VirtualFileUrlManager): VirtualFileUrl = virtualFileManager.fromPath(absolutePath)
fun Path.toVirtualFileUrl(virtualFileManager: VirtualFileUrlManager): VirtualFileUrl = toFile().toVirtualFileUrl(virtualFileManager)
fun Path.toVirtualFileUrl(virtualFileManager: VirtualFileUrlManager): VirtualFileUrl = virtualFileManager.fromPath(toAbsolutePath().toString())
@@ -1,4 +1,4 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project.wizard
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys
@@ -20,7 +20,6 @@ import org.jetbrains.plugins.gradle.service.project.open.linkAndRefreshGradlePro
import org.jetbrains.plugins.gradle.util.GradleBundle
import javax.swing.Icon
/**
* Do not use this project import builder directly.
*
@@ -32,8 +31,7 @@ import javax.swing.Icon
* Use [org.jetbrains.plugins.gradle.service.project.open.openGradleProject] to open (import) a new gradle project.
* Use [org.jetbrains.plugins.gradle.service.project.open.linkAndRefreshGradleProject] to attach a gradle project to an opened idea project.
*/
class JavaGradleProjectImportBuilder : ProjectImportBuilder<Any>(), DeprecatedProjectBuilderForImport {
internal class JavaGradleProjectImportBuilder : ProjectImportBuilder<Any>(), DeprecatedProjectBuilderForImport {
override fun getName(): String = GradleBundle.message("gradle.name")
override fun getIcon(): Icon = GradleIcons.Gradle
@@ -1,4 +1,4 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.importing;
import com.intellij.ide.projectWizard.NewProjectWizardTestCase;
@@ -32,7 +32,6 @@ import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.RunAll;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.Consumer;
import com.intellij.util.SmartList;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.ui.UIUtil;
@@ -45,6 +44,7 @@ import org.jetbrains.plugins.gradle.util.GradleConstants;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.function.Consumer;
import static com.intellij.openapi.externalSystem.test.ExternalSystemTestCase.collectRootsInside;
@@ -52,25 +52,26 @@ import static com.intellij.openapi.externalSystem.test.ExternalSystemTestCase.co
* @author Dmitry Avdeev
*/
public class GradleProjectWizardTest extends NewProjectWizardTestCase {
protected static final String GRADLE_JDK_NAME = "Gradle JDK";
private static final String GRADLE_JDK_NAME = "Gradle JDK";
private final List<Sdk> removedSdks = new SmartList<>();
private String myJdkHome;
public void testGradleProject() throws Exception {
final String projectName = "testProject";
Project project = GradleCreateProjectTestCase.waitForProjectReload(true, () -> createProject(step -> {
if (step instanceof ProjectTypeStep) {
assertTrue(((ProjectTypeStep)step).setSelectedTemplate("Gradle", null));
List<ModuleWizardStep> steps = myWizard.getSequence().getSelectedSteps();
assertEquals(3, steps.size());
final ProjectBuilder projectBuilder = myWizard.getProjectBuilder();
assertInstanceOf(projectBuilder, AbstractGradleModuleBuilder.class);
AbstractGradleModuleBuilder gradleProjectBuilder = (AbstractGradleModuleBuilder)projectBuilder;
gradleProjectBuilder.setName(projectName);
gradleProjectBuilder.setProjectId(new ProjectId("", null, null));
}
}));
Project project = GradleCreateProjectTestCase.waitForProjectReload(true, () -> {
return createProject(step -> {
if (step instanceof ProjectTypeStep) {
assertTrue(((ProjectTypeStep)step).setSelectedTemplate("Gradle", null));
List<ModuleWizardStep> steps = myWizard.getSequence().getSelectedSteps();
assertEquals(3, steps.size());
final ProjectBuilder projectBuilder = myWizard.getProjectBuilder();
assertInstanceOf(projectBuilder, AbstractGradleModuleBuilder.class);
AbstractGradleModuleBuilder gradleProjectBuilder = (AbstractGradleModuleBuilder)projectBuilder;
gradleProjectBuilder.setName(projectName);
gradleProjectBuilder.setProjectId(new ProjectId("", null, null));
}
});
});
assertEquals(projectName, project.getName());
assertModules(project, projectName, projectName + ".main", projectName + ".test");
@@ -131,15 +132,16 @@ public class GradleProjectWizardTest extends NewProjectWizardTestCase {
@Override
protected Project createProject(Consumer adjuster) throws IOException {
@SuppressWarnings("unchecked") Project project = super.createProject(adjuster);
@SuppressWarnings("unchecked")
Project project = super.createProject(adjuster);
myFilesToDelete.add(ProjectUtil.getExternalConfigurationDir(project).toFile());
return project;
}
@Override
protected void createWizard(@Nullable Project project) throws IOException {
Collection linkedProjectsSettings = project == null
? ContainerUtil.emptyList()
Collection<?> linkedProjectsSettings = project == null
? Collections.emptyList()
: ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID).getLinkedProjectsSettings();
assertTrue(linkedProjectsSettings.size() <= 1);
File directory;
@@ -160,7 +162,7 @@ public class GradleProjectWizardTest extends NewProjectWizardTestCase {
PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue();
}
protected void collectAllowedRoots(final List<String> roots) {
private void collectAllowedRoots(final List<String> roots) {
roots.add(myJdkHome);
roots.addAll(collectRootsInside(myJdkHome));
roots.add(PathManager.getConfigPath());
@@ -1,7 +1,8 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project;
import com.intellij.ide.GeneralSettings;
import com.intellij.ide.impl.OpenProjectTask;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.util.projectWizard.WizardContext;
@@ -9,7 +10,6 @@ import com.intellij.ide.wizard.AbstractWizard;
import com.intellij.ide.wizard.CommitStepException;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager;
import com.intellij.openapi.externalSystem.importing.ImportSpec;
import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder;
import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys;
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil;
@@ -68,8 +68,7 @@ import java.util.Collection;
* @author Vladislav.Soroka
*/
@Deprecated
public class GradleProjectOpenProcessor extends ProjectOpenProcessor {
public final class GradleProjectOpenProcessor extends ProjectOpenProcessor {
public static final String @NotNull [] BUILD_FILE_EXTENSIONS = {GradleConstants.EXTENSION, GradleConstants.KOTLIN_DSL_SCRIPT_EXTENSION};
@NotNull
@@ -78,9 +77,8 @@ public class GradleProjectOpenProcessor extends ProjectOpenProcessor {
return GradleBundle.message("gradle.name");
}
@Nullable
@Override
public Icon getIcon() {
public @NotNull Icon getIcon() {
return GradleIcons.Gradle;
}
@@ -137,7 +135,7 @@ public class GradleProjectOpenProcessor extends ProjectOpenProcessor {
}
if (jvmFound || DialogWrapper.OK_EXIT_CODE == wizard.getExitCode()) {
if (projectToOpen == null) {
projectToOpen = ProjectManagerEx.getInstanceEx().newProject(wizardContext.getProjectName(), pathToOpen, true, false);
projectToOpen = ProjectManagerEx.getInstanceEx().newProject(Paths.get(pathToOpen).normalize(), OpenProjectTask.newProject().withProjectName(wizardContext.getProjectName()));
}
if (projectToOpen == null) return null;
@@ -1,4 +1,4 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.wizards
import com.intellij.openapi.externalSystem.importing.AbstractOpenProjectProvider
@@ -9,13 +9,15 @@ import com.intellij.projectImport.ProjectImportBuilder
import org.jetbrains.idea.maven.utils.MavenUtil
internal class MavenOpenProjectProvider : AbstractOpenProjectProvider() {
val builder get() = ProjectImportBuilder.EXTENSIONS_POINT_NAME.findExtensionOrFail(MavenProjectBuilder::class.java)
val builder: MavenProjectBuilder
get() = ProjectImportBuilder.EXTENSIONS_POINT_NAME.findExtensionOrFail(MavenProjectBuilder::class.java)
override fun isProjectFile(file: VirtualFile): Boolean {
return MavenUtil.isPomFile(file)
}
override fun linkAndRefreshProject(projectDirectory: String, project: Project) {
val builder = builder
try {
builder.isUpdate = false
builder.fileToImport = projectDirectory
@@ -117,10 +117,14 @@ public final class MavenProjectBuilder extends ProjectImportBuilder<MavenProject
}
private void setupProjectName(@NotNull Project project) {
if (!(project instanceof ProjectEx)) return;
if (!(project instanceof ProjectEx)) {
return;
}
String projectName = getSuggestedProjectName();
if (projectName == null) return;
((ProjectEx)project).setProjectName(projectName);
if (projectName != null) {
((ProjectEx)project).setProjectName(projectName);
}
}
@Nullable
@@ -356,12 +360,9 @@ public final class MavenProjectBuilder extends ProjectImportBuilder<MavenProject
return getParameters().myImportRoot;
}
public String getSuggestedProjectName() {
final List<MavenProject> list = getParameters().myMavenProjectTree.getRootProjects();
if (list.size() == 1) {
return list.get(0).getMavenId().getArtifactId();
}
return null;
public @Nullable String getSuggestedProjectName() {
List<MavenProject> list = getParameters().myMavenProjectTree.getRootProjects();
return list.size() == 1 ? list.get(0).getMavenId().getArtifactId() : null;
}
@Override
@@ -1,21 +1,20 @@
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.wizards;
import com.intellij.ide.projectWizard.ProjectWizardTestCase;
import com.intellij.ide.util.newProjectWizard.AbstractProjectWizard;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.maven.MavenTestCase;
import org.jetbrains.idea.maven.server.MavenServerManager;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Dmitry Avdeev
*/
public class MavenImportWizardTest extends ProjectWizardTestCase {
public class MavenImportWizardTest extends ProjectWizardTestCase<AbstractProjectWizard> {
@Override
public void tearDown() throws Exception {
try {
@@ -31,20 +30,20 @@ public class MavenImportWizardTest extends ProjectWizardTestCase {
}
public void testImportModule() throws Exception {
File pom = createPom();
Module module = importModuleFrom(new MavenProjectImportProvider(), pom.getPath());
Path pom = createPom();
Module module = importModuleFrom(new MavenProjectImportProvider(), pom.toString());
assertEquals("project", module.getName());
}
public void testImportProject() throws Exception {
File pom = createPom();
Module module = importProjectFrom(pom.getPath(), null, new MavenProjectImportProvider());
Path pom = createPom();
Module module = importProjectFrom(pom.toString(), null, new MavenProjectImportProvider());
assertThat(module.getName()).isEqualTo("project");
}
private File createPom() throws IOException {
private @NotNull Path createPom() throws IOException {
return createTempFile("pom.xml", MavenTestCase.createPomXml("<groupId>test</groupId>" +
"<artifactId>project</artifactId>" +
"<version>1</version>"));
"<version>1</version>")).toPath();
}
}