Search in sources :

Example 6 with ContentEntry

use of com.intellij.openapi.roots.ContentEntry in project intellij-community by JetBrains.

the class CodeInsightTestCase method configureByFiles.

protected VirtualFile configureByFiles(@Nullable final File rawProjectRoot, @NotNull final VirtualFile... vFiles) throws IOException {
    myFile = null;
    myEditor = null;
    final File toDirIO = createTempDirectory();
    final VirtualFile toDir = getVirtualFile(toDirIO);
    ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule);
            final ModifiableRootModel rootModel = rootManager.getModifiableModel();
            if (clearModelBeforeConfiguring()) {
                rootModel.clear();
            }
            // auxiliary files should be copied first
            VirtualFile[] reversed = ArrayUtil.reverseArray(vFiles);
            Map<VirtualFile, EditorInfo> editorInfos;
            if (rawProjectRoot != null) {
                final File projectRoot = rawProjectRoot.getCanonicalFile();
                FileUtil.copyDir(projectRoot, toDirIO);
                VirtualFile fromDir = getVirtualFile(projectRoot);
                editorInfos = copyFilesFillingEditorInfos(fromDir, toDir, ContainerUtil.map2Array(reversed, String.class, s -> s.getPath().substring(projectRoot.getPath().length())));
                toDir.refresh(false, true);
            } else {
                editorInfos = new LinkedHashMap<>();
                for (final VirtualFile vFile : reversed) {
                    VirtualFile parent = vFile.getParent();
                    assert parent.isDirectory() : parent;
                    editorInfos.putAll(copyFilesFillingEditorInfos(parent, toDir, vFile.getName()));
                }
            }
            boolean sourceRootAdded = false;
            if (isAddDirToContentRoot()) {
                final ContentEntry contentEntry = rootModel.addContentEntry(toDir);
                if (isAddDirToSource()) {
                    sourceRootAdded = true;
                    contentEntry.addSourceFolder(toDir, isAddDirToTests());
                }
            }
            doCommitModel(rootModel);
            if (sourceRootAdded) {
                sourceRootAdded(toDir);
            }
            openEditorsAndActivateLast(editorInfos);
        } catch (IOException e) {
            LOG.error(e);
        }
    });
    return toDir;
}
Also used : ModifiableRootModel(com.intellij.openapi.roots.ModifiableRootModel) ContentEntry(com.intellij.openapi.roots.ContentEntry) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager) IOException(java.io.IOException) PsiFile(com.intellij.psi.PsiFile) File(java.io.File)

Example 7 with ContentEntry

use of com.intellij.openapi.roots.ContentEntry in project intellij-community by JetBrains.

the class ModulesConfigurator method apply.

public void apply() throws ConfigurationException {
    // validate content and source roots 
    final Map<VirtualFile, String> contentRootToModuleNameMap = new HashMap<>();
    final Map<VirtualFile, VirtualFile> srcRootsToContentRootMap = new HashMap<>();
    for (final ModuleEditor moduleEditor : myModuleEditors.values()) {
        final ModifiableRootModel rootModel = moduleEditor.getModifiableRootModel();
        final ContentEntry[] contents = rootModel.getContentEntries();
        final String moduleName = moduleEditor.getName();
        Set<VirtualFile> sourceRoots = new HashSet<>();
        for (ContentEntry content : contents) {
            for (VirtualFile root : content.getSourceFolderFiles()) {
                if (!sourceRoots.add(root)) {
                    throw new ConfigurationException(ProjectBundle.message("module.paths.validation.duplicate.source.root.in.same.module.error", root.getPresentableUrl(), moduleName));
                }
            }
        }
        for (ContentEntry contentEntry : contents) {
            final VirtualFile contentRoot = contentEntry.getFile();
            if (contentRoot == null) {
                continue;
            }
            final String previousName = contentRootToModuleNameMap.put(contentRoot, moduleName);
            if (previousName != null && !previousName.equals(moduleName)) {
                throw new ConfigurationException(ProjectBundle.message("module.paths.validation.duplicate.content.error", contentRoot.getPresentableUrl(), previousName, moduleName));
            }
            for (VirtualFile srcRoot : contentEntry.getSourceFolderFiles()) {
                final VirtualFile anotherContentRoot = srcRootsToContentRootMap.put(srcRoot, contentRoot);
                if (anotherContentRoot != null) {
                    final String problematicModule;
                    final String correctModule;
                    if (VfsUtilCore.isAncestor(anotherContentRoot, contentRoot, true)) {
                        problematicModule = contentRootToModuleNameMap.get(anotherContentRoot);
                        correctModule = contentRootToModuleNameMap.get(contentRoot);
                    } else {
                        problematicModule = contentRootToModuleNameMap.get(contentRoot);
                        correctModule = contentRootToModuleNameMap.get(anotherContentRoot);
                    }
                    throw new ConfigurationException(ProjectBundle.message("module.paths.validation.duplicate.source.root.error", problematicModule, srcRoot.getPresentableUrl(), correctModule));
                }
            }
        }
    }
    // additional validation: directories marked as src roots must belong to the same module as their corresponding content root
    for (Map.Entry<VirtualFile, VirtualFile> entry : srcRootsToContentRootMap.entrySet()) {
        final VirtualFile srcRoot = entry.getKey();
        final VirtualFile correspondingContent = entry.getValue();
        final String expectedModuleName = contentRootToModuleNameMap.get(correspondingContent);
        for (VirtualFile candidateContent = srcRoot; candidateContent != null && !candidateContent.equals(correspondingContent); candidateContent = candidateContent.getParent()) {
            final String moduleName = contentRootToModuleNameMap.get(candidateContent);
            if (moduleName != null && !moduleName.equals(expectedModuleName)) {
                throw new ConfigurationException(ProjectBundle.message("module.paths.validation.source.root.belongs.to.another.module.error", srcRoot.getPresentableUrl(), expectedModuleName, moduleName));
            }
        }
    }
    for (ModuleEditor moduleEditor : myModuleEditors.values()) {
        moduleEditor.canApply();
    }
    final Map<Sdk, Sdk> modifiedToOriginalMap = new THashMap<>();
    final ProjectSdksModel projectJdksModel = ProjectStructureConfigurable.getInstance(myProject).getProjectJdksModel();
    for (Map.Entry<Sdk, Sdk> entry : projectJdksModel.getProjectSdks().entrySet()) {
        modifiedToOriginalMap.put(entry.getValue(), entry.getKey());
    }
    final Ref<ConfigurationException> exceptionRef = Ref.create();
    ApplicationManager.getApplication().runWriteAction(() -> {
        final List<ModifiableRootModel> models = new ArrayList<>(myModuleEditors.size());
        try {
            for (final ModuleEditor moduleEditor : myModuleEditors.values()) {
                final ModifiableRootModel model = moduleEditor.apply();
                if (model != null) {
                    if (!model.isSdkInherited()) {
                        // make sure the sdk is set to original SDK stored in the JDK Table
                        final Sdk modelSdk = model.getSdk();
                        if (modelSdk != null) {
                            final Sdk original = modifiedToOriginalMap.get(modelSdk);
                            if (original != null) {
                                model.setSdk(original);
                            }
                        }
                    }
                    models.add(model);
                }
            }
            myFacetsConfigurator.applyEditors();
        } catch (ConfigurationException e) {
            exceptionRef.set(e);
            return;
        }
        try {
            ModifiableModelCommitter.multiCommit(models, myModuleModel);
            myModuleModelCommitted = true;
            myFacetsConfigurator.commitFacets();
        } finally {
            ModuleStructureConfigurable.getInstance(myProject).getFacetEditorFacade().clearMaps(false);
            myFacetsConfigurator = createFacetsConfigurator();
            myModuleModel = ModuleManager.getInstance(myProject).getModifiableModel();
            myModuleModelCommitted = false;
        }
    });
    if (!exceptionRef.isNull()) {
        throw exceptionRef.get();
    }
    myModified = false;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) ProjectSdksModel(com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel) HashMap(com.intellij.util.containers.HashMap) THashMap(gnu.trove.THashMap) ModifiableRootModel(com.intellij.openapi.roots.ModifiableRootModel) THashMap(gnu.trove.THashMap) ConfigurationException(com.intellij.openapi.options.ConfigurationException) ContentEntry(com.intellij.openapi.roots.ContentEntry) Sdk(com.intellij.openapi.projectRoots.Sdk) HashMap(com.intellij.util.containers.HashMap) THashMap(gnu.trove.THashMap)

Example 8 with ContentEntry

use of com.intellij.openapi.roots.ContentEntry in project intellij-community by JetBrains.

the class ModuleFixtureBuilderImpl method initModule.

protected void initModule(Module module) {
    final ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
    final ModifiableRootModel rootModel = rootManager.getModifiableModel();
    for (String contentRoot : myContentRoots) {
        final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(contentRoot);
        Assert.assertNotNull("cannot find content root: " + contentRoot, virtualFile);
        final ContentEntry contentEntry = rootModel.addContentEntry(virtualFile);
        for (String sourceRoot : mySourceRoots) {
            String s = contentRoot + "/" + sourceRoot;
            VirtualFile vf = LocalFileSystem.getInstance().refreshAndFindFileByPath(s);
            if (vf == null) {
                final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(sourceRoot);
                if (file != null && VfsUtilCore.isAncestor(virtualFile, file, false))
                    vf = file;
            }
            //        assert vf != null : "cannot find source root: " + sourceRoot;
            if (vf != null) {
                contentEntry.addSourceFolder(vf, false);
            } else {
                // files are not created yet
                contentEntry.addSourceFolder(VfsUtilCore.pathToUrl(s), false);
            }
        }
    }
    setupRootModel(rootModel);
    rootModel.commit();
}
Also used : ModifiableRootModel(com.intellij.openapi.roots.ModifiableRootModel) VirtualFile(com.intellij.openapi.vfs.VirtualFile) ContentEntry(com.intellij.openapi.roots.ContentEntry) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager)

Example 9 with ContentEntry

use of com.intellij.openapi.roots.ContentEntry in project intellij-community by JetBrains.

the class IntegrationTestCase method addExcludedDir.

protected void addExcludedDir(final String path) {
    ApplicationManager.getApplication().runWriteAction(() -> {
        ModuleRootManager rm = ModuleRootManager.getInstance(myModule);
        ModifiableRootModel m = rm.getModifiableModel();
        for (ContentEntry e : m.getContentEntries()) {
            if (!Comparing.equal(e.getFile(), myRoot))
                continue;
            e.addExcludeFolder(VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(path)));
        }
        m.commit();
    });
}
Also used : ModifiableRootModel(com.intellij.openapi.roots.ModifiableRootModel) ContentEntry(com.intellij.openapi.roots.ContentEntry) ModuleRootManager(com.intellij.openapi.roots.ModuleRootManager)

Example 10 with ContentEntry

use of com.intellij.openapi.roots.ContentEntry in project intellij-community by JetBrains.

the class PlatformProjectOpenProcessor method doOpenProject.

@Nullable
public static Project doOpenProject(@NotNull VirtualFile virtualFile, @Nullable Project projectToClose, int line, @Nullable ProjectOpenedCallback callback, @NotNull EnumSet<Option> options) {
    VirtualFile baseDir = virtualFile;
    boolean dummyProject = false;
    String dummyProjectName = null;
    boolean forceOpenInNewFrame = options.contains(Option.FORCE_NEW_FRAME);
    boolean isReopen = options.contains(Option.REOPEN);
    boolean tempProject = options.contains(Option.TEMP_PROJECT);
    if (!baseDir.isDirectory()) {
        if (tempProject) {
            baseDir = null;
        } else {
            baseDir = virtualFile.getParent();
            while (baseDir != null && !ProjectKt.isProjectDirectoryExistsUsingIo(baseDir)) {
                baseDir = baseDir.getParent();
            }
        }
        if (baseDir == null) {
            // no reasonable directory -> create new temp one or use parent
            if (tempProject || Registry.is("ide.open.file.in.temp.project.dir")) {
                try {
                    dummyProjectName = virtualFile.getName();
                    File directory = FileUtil.createTempDirectory(dummyProjectName, null, true);
                    baseDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(directory);
                    dummyProject = true;
                } catch (IOException ex) {
                    LOG.error(ex);
                }
            }
            if (baseDir == null) {
                baseDir = virtualFile.getParent();
            }
        }
    }
    final Path projectDir = Paths.get(FileUtil.toSystemDependentName(baseDir.getPath()), Project.DIRECTORY_STORE_FOLDER);
    Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
    if (!forceOpenInNewFrame && openProjects.length > 0) {
        if (projectToClose == null) {
            projectToClose = openProjects[openProjects.length - 1];
        }
        if (ProjectAttachProcessor.canAttachToProject() && GeneralSettings.getInstance().getConfirmOpenNewProject() == GeneralSettings.OPEN_PROJECT_ASK) {
            final OpenOrAttachDialog dialog = new OpenOrAttachDialog(projectToClose, isReopen, isReopen ? "Reopen Project" : "Open Project");
            if (!dialog.showAndGet()) {
                return null;
            }
            if (dialog.isReplace()) {
                if (!ProjectUtil.closeAndDispose(projectToClose)) {
                    return null;
                }
            } else if (dialog.isAttach()) {
                if (attachToProject(projectToClose, Paths.get(FileUtil.toSystemDependentName(baseDir.getPath())), callback)) {
                    return null;
                }
            }
            // process all pending events that can interrupt focus flow
            // todo this can be removed after taming the focus beast
            IdeEventQueue.getInstance().flushQueue();
        } else {
            int exitCode = ProjectUtil.confirmOpenNewProject(false);
            if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
                if (!ProjectUtil.closeAndDispose(projectToClose)) {
                    return null;
                }
            } else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) {
                // not in a new window
                return null;
            }
        }
    }
    boolean runConfigurators = true;
    boolean newProject = false;
    ProjectManagerEx projectManager = ProjectManagerEx.getInstanceEx();
    Project project = null;
    if (PathKt.exists(projectDir)) {
        try {
            File baseDirIo = VfsUtilCore.virtualToIoFile(baseDir);
            for (ProjectOpenProcessor processor : ProjectOpenProcessor.EXTENSION_POINT_NAME.getExtensions()) {
                processor.refreshProjectFiles(baseDirIo);
            }
            project = projectManager.convertAndLoadProject(baseDir.getPath());
            if (project != null) {
                Module[] modules = ModuleManager.getInstance(project).getModules();
                if (modules.length > 0) {
                    runConfigurators = false;
                }
            }
        } catch (Exception e) {
            LOG.error(e);
        }
    } else {
        PathKt.createDirectories(projectDir);
        project = projectManager.newProject(dummyProject ? dummyProjectName : baseDir.getName(), baseDir.getPath(), true, dummyProject);
        newProject = true;
    }
    if (project == null) {
        WelcomeFrame.showIfNoProjectOpened();
        return null;
    }
    ProjectBaseDirectory.getInstance(project).setBaseDir(baseDir);
    Module module = runConfigurators ? runDirectoryProjectConfigurators(baseDir, project) : ModuleManager.getInstance(project).getModules()[0];
    if (runConfigurators && dummyProject) {
        // add content root for chosen (single) file
        ModuleRootModificationUtil.updateModel(module, model -> {
            ContentEntry[] entries = model.getContentEntries();
            if (entries.length == 1)
                model.removeContentEntry(entries[0]);
            model.addContentEntry(virtualFile);
        });
    }
    if (newProject) {
        project.save();
    }
    openFileFromCommandLine(project, virtualFile, line);
    if (!projectManager.openProject(project)) {
        WelcomeFrame.showIfNoProjectOpened();
        final Project finalProject = project;
        ApplicationManager.getApplication().runWriteAction(() -> Disposer.dispose(finalProject));
        return project;
    }
    if (callback != null) {
        callback.projectOpened(project, module);
    }
    return project;
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) Path(java.nio.file.Path) IOException(java.io.IOException) IOException(java.io.IOException) Project(com.intellij.openapi.project.Project) ContentEntry(com.intellij.openapi.roots.ContentEntry) Module(com.intellij.openapi.module.Module) VirtualFile(com.intellij.openapi.vfs.VirtualFile) File(java.io.File) ProjectManagerEx(com.intellij.openapi.project.ex.ProjectManagerEx) ProjectOpenProcessor(com.intellij.projectImport.ProjectOpenProcessor) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

ContentEntry (com.intellij.openapi.roots.ContentEntry)60 ModifiableRootModel (com.intellij.openapi.roots.ModifiableRootModel)27 VirtualFile (com.intellij.openapi.vfs.VirtualFile)27 Module (com.intellij.openapi.module.Module)17 File (java.io.File)16 ModuleRootManager (com.intellij.openapi.roots.ModuleRootManager)11 SourceFolder (com.intellij.openapi.roots.SourceFolder)7 NotNull (org.jetbrains.annotations.NotNull)7 FilePaths.findParentContentEntry (com.android.tools.idea.gradle.util.FilePaths.findParentContentEntry)4 IOException (java.io.IOException)4 Nullable (org.jetbrains.annotations.Nullable)4 AndroidModuleModel (com.android.tools.idea.gradle.project.model.AndroidModuleModel)3 Project (com.intellij.openapi.project.Project)3 JavaModuleContentRoot (com.android.tools.idea.gradle.model.java.JavaModuleContentRoot)2 NodeDescriptor (com.intellij.ide.util.treeView.NodeDescriptor)2 ModifiableFlexBuildConfiguration (com.intellij.lang.javascript.flex.projectStructure.model.ModifiableFlexBuildConfiguration)2 Sdk (com.intellij.openapi.projectRoots.Sdk)2 PsiFile (com.intellij.psi.PsiFile)2 ArrayList (java.util.ArrayList)2 SyncIssue (com.android.builder.model.SyncIssue)1