Java Code Examples for com.intellij.psi.PsiManager#findDirectory()
The following examples show how to use
com.intellij.psi.PsiManager#findDirectory() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FilePathReferenceProvider.java From protobuf-jetbrains-plugin with Apache License 2.0 | 6 votes |
@NotNull public Collection<PsiFileSystemItem> getRoots(@Nullable final Module module, ProtoPsiFileRoot psiFileRoot) { if (module == null) { return Collections.emptyList(); } Set<PsiFileSystemItem> result = ContainerUtil.newLinkedHashSet(); PsiManager psiManager = PsiManager.getInstance(module.getProject()); for (SourceRootsProvider sourceRootsProvider : sourceRootsProviders) { VirtualFile[] sourceRoots = sourceRootsProvider.getSourceRoots(module, psiFileRoot); for (VirtualFile root : sourceRoots) { if (root != null) { final PsiDirectory directory = psiManager.findDirectory(root); if (directory != null) { result.add(directory); } } } } return result; }
Example 2
Source File: BlazeCreateXmlResourcePanel.java From intellij with Apache License 2.0 | 6 votes |
private void setupResourceDirectoryCombo() { Project project = myModule.getProject(); if (myContextFile != null) { // Try to figure out res/ dir from context // (e.g., while refactoring an xml file that's a child of a res/ directory). // We currently take the parent and hide the combo box. PsiManager manager = PsiManager.getInstance(project); VirtualFile virtualDirectory = BlazeCreateResourceUtils.getResDirFromDataContext(myContextFile); PsiDirectory directory = virtualDirectory != null ? manager.findDirectory(virtualDirectory) : null; if (directory != null) { myResDirectory = directory.getVirtualFile(); } else { // As a last resort, if we have poor context, // e.g., quick fix from within a .java file, set up the UI // based on the deps of the .java file. BlazeCreateResourceUtils.setupResDirectoryChoices( project, myContextFile, myResDirLabel, myResDirCombo); } } else { // As a last resort, if we have no context at all, set up some UI. BlazeCreateResourceUtils.setupResDirectoryChoices( project, null, myResDirLabel, myResDirCombo); } }
Example 3
Source File: PsiFileReferenceHelper.java From consulo with Apache License 2.0 | 6 votes |
static Collection<PsiFileSystemItem> getContextsForModule(@Nonnull Module module, @Nonnull String packageName, @Nullable GlobalSearchScope scope) { List<PsiFileSystemItem> result = null; Query<VirtualFile> query = DirectoryIndex.getInstance(module.getProject()).getDirectoriesByPackageName(packageName, false); PsiManager manager = null; for (VirtualFile file : query) { if (scope != null && !scope.contains(file)) continue; if (result == null) { result = new ArrayList<>(); manager = PsiManager.getInstance(module.getProject()); } PsiDirectory psiDirectory = manager.findDirectory(file); if (psiDirectory != null) result.add(psiDirectory); } return result != null ? result : Collections.emptyList(); }
Example 4
Source File: PantsVirtualFileReference.java From intellij-pants-plugin with Apache License 2.0 | 6 votes |
@Nullable @Override public PsiElement resolve() { Optional<VirtualFile> virtualFile = findFile(); if (!virtualFile.isPresent()) { return null; } VirtualFile buildFileOrDirectory = PantsUtil.findBUILDFiles(virtualFile.get()) .stream() .findFirst() .orElse(virtualFile.get()); final PsiManager psiManager = PsiManager.getInstance(getElement().getProject()); final PsiFile buildFile = psiManager.findFile(buildFileOrDirectory); return buildFile != null ? buildFile : psiManager.findDirectory(buildFileOrDirectory); }
Example 5
Source File: TodoTreeHelper.java From consulo with Apache License 2.0 | 5 votes |
private static void addPackagesToChildren0(Project project, ArrayList<AbstractTreeNode> children, Module module, TodoTreeBuilder builder) { final List<VirtualFile> roots = new ArrayList<VirtualFile>(); final List<VirtualFile> sourceRoots = new ArrayList<VirtualFile>(); final PsiManager psiManager = PsiManager.getInstance(project); if (module == null) { final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project); ContainerUtil.addAll(roots, projectRootManager.getContentRoots()); ContainerUtil.addAll(sourceRoots, projectRootManager.getContentSourceRoots()); } else { ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); ContainerUtil.addAll(roots, moduleRootManager.getContentRoots()); ContainerUtil.addAll(sourceRoots, moduleRootManager.getContentFolderFiles(ContentFolderScopes.productionAndTest())); } roots.removeAll(sourceRoots); for (VirtualFile dir : roots) { final PsiDirectory directory = psiManager.findDirectory(dir); if (directory == null) { continue; } final Iterator<PsiFile> files = builder.getFiles(directory); if (!files.hasNext()) continue; TodoDirNode dirNode = new TodoDirNode(project, directory, builder); if (!children.contains(dirNode)) { children.add(dirNode); } } }
Example 6
Source File: BookmarkItem.java From consulo with Apache License 2.0 | 5 votes |
public static void setupRenderer(SimpleColoredComponent renderer, Project project, Bookmark bookmark, boolean selected) { VirtualFile file = bookmark.getFile(); if (!file.isValid()) { return; } PsiManager psiManager = PsiManager.getInstance(project); PsiElement fileOrDir = file.isDirectory() ? psiManager.findDirectory(file) : psiManager.findFile(file); if (fileOrDir != null) { renderer.setIcon(IconDescriptorUpdaters.getIcon(fileOrDir, 0)); } String description = bookmark.getDescription(); if (description != null) { renderer.append(description + " ", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES); } FileStatus fileStatus = FileStatusManager.getInstance(project).getStatus(file); TextAttributes attributes = new TextAttributes(fileStatus.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); renderer.append(file.getName(), SimpleTextAttributes.fromTextAttributes(attributes)); if (bookmark.getLine() >= 0) { renderer.append(":", SimpleTextAttributes.GRAYED_ATTRIBUTES); renderer.append(String.valueOf(bookmark.getLine() + 1), SimpleTextAttributes.GRAYED_ATTRIBUTES); } if (!selected) { FileColorManager colorManager = FileColorManager.getInstance(project); if (fileOrDir instanceof PsiFile) { Color color = colorManager.getRendererBackground((PsiFile)fileOrDir); if (color != null) { renderer.setBackground(color); } } } }
Example 7
Source File: FilenameIndex.java From consulo with Apache License 2.0 | 5 votes |
public static boolean processFilesByName(@Nonnull final String name, boolean directories, boolean caseSensitively, @Nonnull Processor<? super PsiFileSystemItem> processor, @Nonnull final GlobalSearchScope scope, @Nonnull final Project project, @Nullable IdFilter idFilter) { final Collection<VirtualFile> files; if (caseSensitively) { files = getService().getVirtualFilesByName(project, name, scope, idFilter); } else { files = getVirtualFilesByNameIgnoringCase(name, scope, project, idFilter); } if (files.isEmpty()) return false; PsiManager psiManager = PsiManager.getInstance(project); int processedFiles = 0; for (VirtualFile file : files) { if (!file.isValid()) continue; if (!directories && !file.isDirectory()) { PsiFile psiFile = psiManager.findFile(file); if (psiFile != null) { if (!processor.process(psiFile)) return true; ++processedFiles; } } else if (directories && file.isDirectory()) { PsiDirectory dir = psiManager.findDirectory(file); if (dir != null) { if (!processor.process(dir)) return true; ++processedFiles; } } } return processedFiles > 0; }
Example 8
Source File: PackageNodeUtil.java From consulo with Apache License 2.0 | 5 votes |
/** * a directory is considered "empty" if it has at least one child and all its children are only directories * * @param strictlyEmpty if true, the package is considered empty if it has only 1 child and this child is a directory * otherwise the package is considered as empty if all direct children that it has are directories */ public static boolean isEmptyMiddlePackage(@Nonnull PsiDirectory dir, @Nullable Class<? extends ModuleExtension> moduleExtensionClass, boolean strictlyEmpty) { final VirtualFile[] files = dir.getVirtualFile().getChildren(); if (files.length == 0) { return false; } PsiManager manager = dir.getManager(); int subpackagesCount = 0; int directoriesCount = 0; for (VirtualFile file : files) { if (FileTypeManager.getInstance().isFileIgnored(file)) continue; if (!file.isDirectory()) return false; PsiDirectory childDir = manager.findDirectory(file); if (childDir != null) { directoriesCount++; if (strictlyEmpty && directoriesCount > 1) return false; final PsiPackageManager psiPackageManager = PsiPackageManager.getInstance(dir.getProject()); PsiPackage tempPackage = moduleExtensionClass == null ? psiPackageManager.findAnyPackage(childDir) : psiPackageManager.findPackage(dir, moduleExtensionClass); if (tempPackage != null) { subpackagesCount++; } } } if (strictlyEmpty) { return directoriesCount == subpackagesCount && directoriesCount == 1; } return directoriesCount == subpackagesCount && directoriesCount > 0; }
Example 9
Source File: CompileAction.java From consulo with Apache License 2.0 | 5 votes |
private static VirtualFile[] getCompilableFiles(Project project, VirtualFile[] files) { if (files == null || files.length == 0) { return VirtualFile.EMPTY_ARRAY; } final PsiManager psiManager = PsiManager.getInstance(project); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final CompilerManager compilerManager = CompilerManager.getInstance(project); final List<VirtualFile> filesToCompile = new ArrayList<VirtualFile>(); for (final VirtualFile file : files) { if (!fileIndex.isInSourceContent(file)) { continue; } if (!file.isInLocalFileSystem()) { continue; } if (file.isDirectory()) { final PsiDirectory directory = psiManager.findDirectory(file); if (directory == null || PsiPackageManager.getInstance(project).findAnyPackage(directory) == null) { continue; } } else { FileType fileType = file.getFileType(); if (!(compilerManager.isCompilableFileType(fileType) || isCompilableResourceFile(project, file))) { continue; } } filesToCompile.add(file); } return VfsUtil.toVirtualFileArray(filesToCompile); }
Example 10
Source File: PackageNodeUtil.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull public static Collection<AbstractTreeNode> createPackageViewChildrenOnFiles(@Nonnull List<VirtualFile> sourceRoots, @Nonnull Project project, @Nonnull ViewSettings settings, @Nullable Module module, final boolean inLibrary) { final PsiManager psiManager = PsiManager.getInstance(project); final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>(); final Set<PsiPackage> topLevelPackages = new HashSet<PsiPackage>(); for (final VirtualFile root : sourceRoots) { final PsiDirectory directory = psiManager.findDirectory(root); if (directory == null) { continue; } final PsiPackage directoryPackage = PsiPackageManager.getInstance(project).findAnyPackage(directory); if (directoryPackage == null || isPackageDefault(directoryPackage)) { // add subpackages final PsiDirectory[] subdirectories = directory.getSubdirectories(); for (PsiDirectory subdirectory : subdirectories) { final PsiPackage aPackage = PsiPackageManager.getInstance(project).findAnyPackage(subdirectory); if (aPackage != null && !isPackageDefault(aPackage)) { topLevelPackages.add(aPackage); } } // add non-dir items children.addAll(BaseProjectViewDirectoryHelper.getDirectoryChildren(directory, settings, false)); } else { topLevelPackages.add(directoryPackage); } } for (final PsiPackage topLevelPackage : topLevelPackages) { addPackageAsChild(children, topLevelPackage, module, settings, inLibrary); } return children; }
Example 11
Source File: GoToLinkTargetAction.java From consulo with Apache License 2.0 | 5 votes |
@Override public void actionPerformed(AnActionEvent e) { Project project = getEventProject(e); VirtualFile file = e.getDataContext().getData(CommonDataKeys.VIRTUAL_FILE); if (project != null && file != null && file.is(VFileProperty.SYMLINK)) { VirtualFile target = file.getCanonicalFile(); if (target != null) { PsiManager psiManager = PsiManager.getInstance(project); PsiFileSystemItem psiFile = target.isDirectory() ? psiManager.findDirectory(target) : psiManager.findFile(target); if (psiFile != null) { ProjectView.getInstance(project).select(psiFile, target, false); } } } }
Example 12
Source File: KnowledgeViewTreeBuilder.java From netbeans-mmd-plugin with Apache License 2.0 | 5 votes |
private PsiElement findPsi(@Nonnull VirtualFile vFile) { if (!vFile.isValid()) { return null; } PsiManager psiManager = PsiManager.getInstance(myProject); return vFile.isDirectory() ? psiManager.findDirectory(vFile) : psiManager.findFile(vFile); }
Example 13
Source File: BlazePyResolverUtils.java From intellij with Apache License 2.0 | 5 votes |
@Nullable public static PsiFileSystemItem resolveFile(PsiManager manager, File file) { VirtualFile vf = VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath()); if (vf != null) { return vf.isDirectory() ? manager.findDirectory(vf) : manager.findFile(vf); } vf = VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath() + ".py"); return vf != null ? manager.findFile(vf) : null; }
Example 14
Source File: BlazeCoverageEngine.java From intellij with Apache License 2.0 | 5 votes |
@Nullable private static PsiFileSystemItem resolveFile(Project project, @Nullable File file) { if (file == null) { return null; } PsiManager manager = PsiManager.getInstance(project); VirtualFile vf = VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath()); if (vf == null) { return null; } return vf.isDirectory() ? manager.findDirectory(vf) : manager.findFile(vf); }
Example 15
Source File: PlatformPackageUtil.java From consulo with Apache License 2.0 | 5 votes |
@Nullable private static PsiDirectory getWritableModuleDirectory(@Nonnull Query<VirtualFile> vFiles, GlobalSearchScope scope, PsiManager manager) { for (VirtualFile vFile : vFiles) { if (!scope.contains(vFile)) continue; PsiDirectory directory = manager.findDirectory(vFile); if (directory != null && directory.isValid() && directory.isWritable()) { return directory; } } return null; }
Example 16
Source File: BuildReferenceManager.java From intellij with Apache License 2.0 | 5 votes |
@Nullable public PsiFileSystemItem resolveFile(File file) { VirtualFile vf = VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath()); if (vf == null) { return null; } PsiManager manager = PsiManager.getInstance(project); return vf.isDirectory() ? manager.findDirectory(vf) : manager.findFile(vf); }
Example 17
Source File: ProjectViewModuleNode.java From consulo with Apache License 2.0 | 5 votes |
@Override @Nonnull @RequiredReadAction public Collection<AbstractTreeNode> getChildren() { Module module = getValue(); if (module == null || module.isDisposed()) { return Collections.emptyList(); } ModuleRootManager rootManager = ModuleRootManager.getInstance(module); ModuleFileIndex moduleFileIndex = rootManager.getFileIndex(); final VirtualFile[] contentRoots = rootManager.getContentRoots(); final List<AbstractTreeNode> children = new ArrayList<>(contentRoots.length + 1); final PsiManager psiManager = PsiManager.getInstance(module.getProject()); for (final VirtualFile contentRoot : contentRoots) { if (!moduleFileIndex.isInContent(contentRoot)) continue; if (contentRoot.isDirectory()) { PsiDirectory directory = psiManager.findDirectory(contentRoot); if(directory != null) { children.add(new PsiDirectoryNode(getProject(), directory, getSettings())); } } else { PsiFile file = psiManager.findFile(contentRoot); if(file != null) { children.add(new PsiFileNode(getProject(), file, getSettings())); } } } return children; }
Example 18
Source File: KnowledgeViewProjectNode.java From netbeans-mmd-plugin with Apache License 2.0 | 4 votes |
@Nonnull @Override public Collection<? extends AbstractTreeNode> getChildren() { final ArrayList<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>(); final PsiManager psiManager = PsiManager.getInstance(getProject()); for (final Module m : ModuleManager.getInstance(myProject).getModules()) { final VirtualFile knowledgeFolder = IdeaUtils.findKnowledgeFolderForModule(m, false); if (knowledgeFolder != null) { final String moduleName = m.getName(); final PsiDirectory dir = psiManager.findDirectory(knowledgeFolder); final PsiDirectoryNode node = new PsiDirectoryNode(myProject, dir, getSettings()) { protected Icon patchIcon(final Icon original, final VirtualFile file) { return AllIcons.File.FOLDER; } @Override public String getTitle() { return moduleName; } @Override public String toString() { return moduleName; } @Override public boolean isFQNameShown() { return false; } @Override public VirtualFile getVirtualFile() { return knowledgeFolder; } @Nullable @Override protected String calcTooltip() { return "The Knowledge folder for " + m.getName(); } @Override protected boolean shouldShowModuleName() { return false; } }; result.add(node); } } return result; }
Example 19
Source File: DirectoryUtil.java From consulo with Apache License 2.0 | 4 votes |
/** * Creates the directory with the given path via PSI, including any * necessary but nonexistent parent directories. Must be run in write action. * @param path directory path in the local file system; separators must be '/' * @return true if path exists or has been created as the result of this method call; false otherwise */ public static PsiDirectory mkdirs(PsiManager manager, String path) throws IncorrectOperationException{ if (File.separatorChar != '/') { if (path.indexOf(File.separatorChar) != -1) { throw new IllegalArgumentException("separators must be '/'; path is " + path); } } String existingPath = path; PsiDirectory directory = null; // find longest existing path while (existingPath.length() > 0) { VirtualFile file = LocalFileSystem.getInstance().findFileByPath(existingPath); if (file != null) { directory = manager.findDirectory(file); if (directory == null) { return null; } break; } if (StringUtil.endsWithChar(existingPath, '/')) { existingPath = existingPath.substring(0, existingPath.length() - 1); if (SystemInfo.isWindows && existingPath.length() == 2 && existingPath.charAt(1) == ':') { return null; } } int index = existingPath.lastIndexOf('/'); if (index == -1) { // nothing to do more return null; } existingPath = existingPath.substring(0, index); } if (directory == null) { return null; } if (existingPath.equals(path)) { return directory; } String postfix = path.substring(existingPath.length() + 1, path.length()); StringTokenizer tokenizer = new StringTokenizer(postfix, "/"); while (tokenizer.hasMoreTokens()) { String name = tokenizer.nextToken(); PsiDirectory subdirectory = directory.createSubdirectory(name); if (subdirectory == null) { return null; } directory = subdirectory; } return directory; }
Example 20
Source File: FileUtils.java From EasyCode with MIT License | 4 votes |
/** * 写入文件 * * @param saveFile 需要保存的文件对象 */ public void write(SaveFile saveFile) { // 校验目录是否存在 PsiManager psiManager = PsiManager.getInstance(saveFile.getProject()); PsiDirectory psiDirectory; VirtualFile directory = LocalFileSystem.getInstance().findFileByPath(saveFile.getPath()); if (directory == null) { // 尝试创建目录 if (saveFile.isOperateTitle() && !MessageDialogBuilder.yesNo(MsgValue.TITLE_INFO, "Directory " + saveFile.getPath() + " Not Found, Confirm Create?").isYes()) { return; } psiDirectory = WriteCommandAction.runWriteCommandAction(saveFile.getProject(), (Computable<PsiDirectory>) () -> { try { VirtualFile dir = VfsUtil.createDirectoryIfMissing(saveFile.getPath()); LOG.assertTrue(dir != null); // 重载文件,防止发生IndexNotReadyException异常 FileDocumentManager.getInstance().reloadFiles(dir); return psiManager.findDirectory(dir); } catch (IOException e) { LOG.error("path " + saveFile.getPath() + " error"); ExceptionUtil.rethrow(e); return null; } }); } else { psiDirectory = psiManager.findDirectory(directory); } if (psiDirectory == null) { return; } // 保存或替换文件 PsiFile oldFile = psiDirectory.findFile(saveFile.getFile().getName()); PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(saveFile.getProject()); FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance(); if (saveFile.isOperateTitle() && oldFile != null) { MessageDialogBuilder.YesNoCancel yesNoCancel = MessageDialogBuilder.yesNoCancel(MsgValue.TITLE_INFO, "File " + saveFile.getFile().getName() + " Exists, Select Operate Mode?"); yesNoCancel.yesText("Cover"); yesNoCancel.noText("Compare"); yesNoCancel.cancelText("Cancel"); int result = yesNoCancel.show(); switch (result) { case Messages.YES: break; case Messages.NO: // 对比代码时也格式化代码 if (saveFile.isReformat()) { // 保留旧文件内容,用新文件覆盖旧文件执行格式化,然后再还原旧文件内容 String oldText = oldFile.getText(); WriteCommandAction.runWriteCommandAction(saveFile.getProject(), () -> psiDocumentManager.getDocument(oldFile).setText(saveFile.getFile().getText())); // 提交所有改动,并非VCS中的提交文件 PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments(); reformatFile(saveFile.getProject(), Collections.singletonList(oldFile)); // 提交所有改动,并非VCS中的提交文件 PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments(); String newText = oldFile.getText(); WriteCommandAction.runWriteCommandAction(saveFile.getProject(), () -> psiDocumentManager.getDocument(oldFile).setText(oldText)); // 提交所有改动,并非VCS中的提交文件 PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments(); saveFile.setVirtualFile(new LightVirtualFile(saveFile.getFile().getName(), saveFile.getFile().getFileType(), newText)); } CompareFileUtils.showCompareWindow(saveFile.getProject(), fileDocumentManager.getFile(psiDocumentManager.getDocument(oldFile)), saveFile.getVirtualFile()); return; case Messages.CANCEL: default: return; } } PsiDirectory finalPsiDirectory = psiDirectory; PsiFile finalFile = WriteCommandAction.runWriteCommandAction(saveFile.getProject(), (Computable<PsiFile>) () -> { if (oldFile == null) { // 提交所有改动,并非VCS中的提交文件 PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments(); return (PsiFile) finalPsiDirectory.add(saveFile.getFile()); } else { // 对旧文件进行替换操作 Document document = psiDocumentManager.getDocument(oldFile); LOG.assertTrue(document != null); document.setText(saveFile.getFile().getText()); return oldFile; } }); // 判断是否需要进行代码格式化操作 if (saveFile.isReformat()) { reformatFile(saveFile.getProject(), Collections.singletonList(finalFile)); } // 提交所有改动,并非VCS中的提交文件 PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments(); }