Java Code Examples for com.intellij.psi.PsiDirectory#findFile()
The following examples show how to use
com.intellij.psi.PsiDirectory#findFile() .
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: PsiFinder.java From reasonml-idea-plugin with MIT License | 6 votes |
@Nullable public FileBase findRelatedFile(@NotNull FileBase file) { PsiDirectory directory = file.getParent(); if (directory != null) { String filename = file.getVirtualFile().getNameWithoutExtension(); String relatedExtension; if (FileHelper.isReason(file.getFileType())) { relatedExtension = file.isInterface() ? RmlFileType.INSTANCE.getDefaultExtension() : RmlInterfaceFileType.INSTANCE.getDefaultExtension(); } else { relatedExtension = file.isInterface() ? OclFileType.INSTANCE.getDefaultExtension() : OclInterfaceFileType.INSTANCE.getDefaultExtension(); } PsiFile relatedPsiFile = directory.findFile(filename + "." + relatedExtension); return relatedPsiFile instanceof FileBase ? (FileBase) relatedPsiFile : null; } return null; }
Example 2
Source File: ExtraModulesUtil.java From weex-language-support with MIT License | 6 votes |
private static String getHomePage(PsiDirectory directory) { PsiFile pkg = directory.findFile("package.json"); if (pkg != null && pkg instanceof JsonFile) { if (((JsonFile) pkg).getTopLevelValue() instanceof JsonObject) { JsonObject object = (JsonObject) ((JsonFile) pkg).getTopLevelValue(); if (object != null) { JsonProperty homePage = object.findProperty("homepage"); if (homePage != null && homePage.getValue() != null && homePage.getValue() instanceof JsonStringLiteral) { JsonStringLiteral propValue = (JsonStringLiteral) homePage.getValue(); return propValue.getValue(); } } } } return null; }
Example 3
Source File: ExtraModulesUtil.java From weex-language-support with MIT License | 6 votes |
private static PsiFile getMain(PsiDirectory moduleRoot) { PsiFile pkg = moduleRoot.findFile("package.json"); if (pkg != null && pkg instanceof JsonFile) { if (((JsonFile) pkg).getTopLevelValue() instanceof JsonObject) { JsonObject object = (JsonObject) ((JsonFile) pkg).getTopLevelValue(); if (object != null) { JsonProperty property = object.findProperty("main"); if (property != null && property.getValue() != null && property.getValue() instanceof JsonStringLiteral) { JsonStringLiteral propValue = (JsonStringLiteral) property.getValue(); String value = propValue.getValue(); PsiFile psiFile = moduleRoot.findFile(value.replace("./", "")); return psiFile; } } } } return null; }
Example 4
Source File: ExtraModulesUtil.java From weex-language-support with MIT License | 6 votes |
public static String getModuleName(PsiDirectory dir) { PsiFile pkg = dir.findFile("package.json"); String name = dir.getName(); if (pkg != null && pkg instanceof JsonFile) { if (((JsonFile) pkg).getTopLevelValue() instanceof JsonObject) { JsonObject object = (JsonObject) ((JsonFile) pkg).getTopLevelValue(); if (object != null) { JsonProperty property = object.findProperty("name"); JsonProperty property1 = object.findProperty("version"); if (property != null && property.getValue() != null && property.getValue() instanceof JsonStringLiteral) { JsonStringLiteral propValue = (JsonStringLiteral) property.getValue(); name = propValue.getValue(); if (property1 != null && property1.getValue() != null && property1.getValue() instanceof JsonStringLiteral) { JsonStringLiteral propValue1 = (JsonStringLiteral) property1.getValue(); name = name + ":" + propValue1.getValue(); } } } } } return name; }
Example 5
Source File: CSharpTypeRenamePsiElementProcessor.java From consulo-csharp with Apache License 2.0 | 6 votes |
@Override public void findExistingNameConflicts(PsiElement element, String newName, MultiMap<PsiElement, String> conflicts, Map<PsiElement, String> allRenames) { for(Map.Entry<PsiElement, String> entry : allRenames.entrySet()) { if(entry.getKey() instanceof CSharpFile) { CSharpFile key = (CSharpFile) entry.getKey(); PsiDirectory parent = key.getParent(); if(parent == null) { continue; } PsiFile file = parent.findFile(entry.getValue()); if(file != null) { conflicts.putValue(file, entry.getValue() + " already exists in parent directory"); } } } }
Example 6
Source File: IgnoreTemplatesFactory.java From idea-gitignore with MIT License | 6 votes |
/** * Creates new Gitignore file or uses an existing one. * * @param directory working directory * @return file */ @Nullable public PsiFile createFromTemplate(final PsiDirectory directory) throws IncorrectOperationException { final String filename = fileType.getIgnoreLanguage().getFilename(); final PsiFile currentFile = directory.findFile(filename); if (currentFile != null) { return currentFile; } final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject()); final IgnoreLanguage language = fileType.getIgnoreLanguage(); String content = StringUtil.join(TEMPLATE_NOTE, Constants.NEWLINE); if (language.isSyntaxSupported() && !IgnoreBundle.Syntax.GLOB.equals(language.getDefaultSyntax())) { content = StringUtil.join( content, IgnoreBundle.Syntax.GLOB.getPresentation(), Constants.NEWLINE, Constants.NEWLINE ); } final PsiFile file = factory.createFileFromText(filename, fileType, content); return (PsiFile) directory.add(file); }
Example 7
Source File: ExtensionUtility.java From idea-php-typo3-plugin with MIT License | 5 votes |
private static VirtualFile findExtEmConf(@NotNull PsiDirectory extensionRootDirectory) { PsiFile file = extensionRootDirectory.findFile("ext_emconf.php"); if (file == null) { return null; } return file.getVirtualFile(); }
Example 8
Source File: ExtensionUtility.java From idea-php-typo3-plugin with MIT License | 5 votes |
private static VirtualFile findComposerManifest(@NotNull PsiDirectory extensionRootDirectory) { PsiFile file = extensionRootDirectory.findFile("composer.json"); if (file == null) { return null; } return file.getVirtualFile(); }
Example 9
Source File: ExtraModulesUtil.java From weex-language-support with MIT License | 5 votes |
private static List<PsiFile> getComponents(PsiDirectory root, PsiFile file) { List<PsiFile> results = new ArrayList<PsiFile>(); if (file != null && file instanceof JSFile) { for (PsiElement element : file.getChildren()) { if (element instanceof JSExpressionStatement) { JSExpression expression = ((JSExpressionStatement) element).getExpression(); if (expression instanceof JSCallExpression && ((JSCallExpression) expression).getArguments().length == 1 && ((JSCallExpression) expression).getArguments()[0] instanceof JSLiteralExpression) { JSLiteralExpression expression1 = (JSLiteralExpression) ((JSCallExpression) expression).getArguments()[0]; Object val = expression1.getValue(); if (val != null) { String[] temp = val.toString().replace("./", "").split("/"); if (temp != null && temp.length > 0) { String fileName = temp[temp.length - 1]; if (fileName.toLowerCase().endsWith(".we")) { PsiDirectory start = root; for (int i = 0; i < temp.length - 1; i++) { PsiDirectory dir = start.findSubdirectory(temp[i]); if (dir != null) { start = dir; } } PsiFile weexScript = start.findFile(temp[temp.length - 1]); if (weexScript != null) { results.add(weexScript); } } } } } } } } return results; }
Example 10
Source File: TokenVocabResolver.java From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Looks for an ANTLR grammar file named {@code <baseName>}.g4 next to the given {@code sibling} file. */ static PsiFile findRelativeFile(String baseName, PsiFile sibling) { PsiDirectory parentDirectory = sibling.getParent(); if (parentDirectory != null) { PsiFile candidate = parentDirectory.findFile(baseName + ".g4"); if (candidate instanceof ANTLRv4FileRoot) { return candidate; } } return null; }
Example 11
Source File: BlazePyUseScopeEnlarger.java From intellij with Apache License 2.0 | 5 votes |
private static boolean isPyPackageOutsideProject(PsiElement element) { if (!(element instanceof PsiDirectory)) { return false; } PsiDirectory dir = (PsiDirectory) element; return dir.findFile(PyNames.INIT_DOT_PY) != null && !inProjectScope(dir.getProject(), dir.getVirtualFile()); }
Example 12
Source File: BashPsiFileUtils.java From BashSupport with Apache License 2.0 | 5 votes |
/** * Takes an existing psi file and tries to find another file relative to the first. * The file path is given as a relative path. * * @param start The existing psi file * @param relativePath The relative path as a string * @return The psi file or null if nothing has been found */ @Nullable public static PsiFile findRelativeFile(PsiFile start, String relativePath) { PsiDirectory startDirectory = BashPsiUtils.findFileContext(start).getContainingDirectory(); if (startDirectory == null || StringUtil.isEmptyOrSpaces(relativePath)) { return null; } //fixme handle escaped / chars! PsiDirectory currentDir = startDirectory; List<String> parts = StringUtil.split(relativePath, "/"); String filePart = parts.size() > 0 ? parts.get(parts.size() - 1) : ""; for (int i = 0, partsLength = parts.size() - 1; (i < partsLength) && (currentDir != null); i++) { String part = parts.get(i); if (".".equals(part)) { //ignore this } else if ("..".equals(part)) { currentDir = currentDir.getParentDirectory(); } else { currentDir = currentDir.findSubdirectory(part); } } if (currentDir != null) { return currentDir.findFile(filePart); } return null; }
Example 13
Source File: HaxePackageModel.java From intellij-haxe with Apache License 2.0 | 5 votes |
protected HaxeFile getFile(String fileName) { PsiDirectory directory = root.access(path); if (directory != null && directory.isValid()) { PsiFile file = directory.findFile(fileName + ".hx"); if (file != null && file.isValid() && file instanceof HaxeFile) { return (HaxeFile)file; } } return null; }
Example 14
Source File: MarkdownDocumentationProvider.java From markdown-doclet with GNU General Public License v3.0 | 4 votes |
@Nullable @Override public String generateDoc(PsiElement element, @Nullable PsiElement originalElement) { boolean process = false; for ( Class supported: SUPPORTED_ELEMENT_TYPES ) { if ( supported.isInstance(element) ) { process = true; break; } } if ( !process ) { return null; } PsiFile file = null; if ( element instanceof PsiDirectory ) { // let's see whether we can map the directory to a package; if so, change the // element to the package and continue PsiPackage pkg = JavaDirectoryService.getInstance().getPackage((PsiDirectory)element); if ( pkg != null ) { element = pkg; } else { return null; } } if ( element instanceof PsiPackage ) { for ( PsiDirectory dir : ((PsiPackage)element).getDirectories() ) { PsiFile info = dir.findFile(PsiPackage.PACKAGE_INFO_FILE); if ( info != null ) { ASTNode node = info.getNode(); if ( node != null ) { ASTNode docCommentNode = node.findChildByType(JavaDocElementType.DOC_COMMENT); if ( docCommentNode != null ) { // the default implementation will now use this file // we're going to take over below, if Markdown is enabled in // the corresponding module // see JavaDocInfoGenerator.generatePackageJavaDoc() file = info; break; } } } if ( dir.findFile("package.html") != null ) { // leave that to the default return null; } } } else { if ( JavaLanguage.INSTANCE.equals(element.getLanguage()) ) { element = element.getNavigationElement(); if ( element.getContainingFile() != null ) { file = element.getContainingFile(); } } } if ( file != null ) { DocCommentProcessor processor = new DocCommentProcessor(file); if ( processor.isEnabled() ) { String docHtml; if ( element instanceof PsiMethod ) { docHtml = super.generateDoc(PsiProxy.forMethod((PsiMethod)element), originalElement); } else if ( element instanceof PsiParameter ) { docHtml = super.generateDoc(PsiProxy.forParameter((PsiParameter)element), originalElement); } else { MarkdownJavaDocInfoGenerator javaDocInfoGenerator = new MarkdownJavaDocInfoGenerator(element.getProject(), element, processor); List<String> docURLs = getExternalJavaDocUrl(element); String text = javaDocInfoGenerator.generateDocInfo(docURLs); Plugin.print("Intermediate HTML output", text); docHtml = JavaDocExternalFilter.filterInternalDocInfo(text); } docHtml = extendCss(docHtml); Plugin.print("Final HTML output", docHtml); return docHtml; } else { return null; } } else { return null; } }
Example 15
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(); }
Example 16
Source File: DoctrineOrmRepositoryIntention.java From idea-php-annotation-plugin with MIT License | 4 votes |
@Override public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException { PhpClass phpClass = getScopedPhpClass(element); if(phpClass == null) { return; } String fileName = phpClass.getName() + "Repository.php"; String namespace = DoctrineUtil.trimBlackSlashes(phpClass.getNamespaceName()); PsiDirectory dir = phpClass.getContainingFile().getContainingDirectory(); PsiDirectory repositoryDir = dir; if (dir.getParentDirectory() != null) { PsiDirectory checkDir = dir.getParentDirectory().findSubdirectory("Repository"); if (dir.findFile(fileName) == null && checkDir != null) { repositoryDir = checkDir; } } String repoClass = phpClass.getPresentableFQN() + "Repository"; PhpClass repoPhpClass = PhpElementsUtil.getClass(project, repoClass); if (repoPhpClass == null && dir != repositoryDir) { // Entity/../Repository/ namespace = phpClass.getNamespaceName(); namespace = namespace.substring(0, namespace.lastIndexOf("\\")); namespace = namespace.substring(0, namespace.lastIndexOf("\\")); namespace = namespace + "\\Repository"; namespace = DoctrineUtil.trimBlackSlashes(namespace); repoClass = namespace + "\\" + phpClass.getName() + "Repository"; repoClass = PhpLangUtil.toPresentableFQN(repoClass); repoPhpClass = PhpElementsUtil.getClass(project, repoClass); } if(repoPhpClass == null) { if(repositoryDir.findFile(fileName) == null) { final FileTemplate fileTemplate = FileTemplateManager.getInstance(project).getTemplate("Doctrine Entity Repository"); final Properties defaultProperties = FileTemplateManager.getInstance(project).getDefaultProperties(); Properties properties = new Properties(defaultProperties); properties.setProperty("NAMESPACE", namespace); properties.setProperty("NAME", phpClass.getName() + "Repository"); properties.setProperty("ENTITY_NAMESPACE", DoctrineUtil.trimBlackSlashes(phpClass.getNamespaceName())); properties.setProperty("ENTITY_NAME", phpClass.getName()); try { PsiElement newElement = FileTemplateUtil.createFromTemplate(fileTemplate, fileName, properties, repositoryDir); new OpenFileDescriptor(project, newElement.getContainingFile().getVirtualFile(), 0).navigate(true); } catch (Exception e) { return; } } else { if (!ApplicationManager.getApplication().isHeadlessEnvironment()) { HintManager.getInstance().showErrorHint(editor, "Repository already exists "); } } } PhpDocTagAnnotation ormEntityPhpDocBlock = DoctrineUtil.getOrmEntityPhpDocBlock(phpClass); if(ormEntityPhpDocBlock != null) { PhpDocTag phpDocTag = ormEntityPhpDocBlock.getPhpDocTag(); PhpPsiElement firstPsiChild = phpDocTag.getFirstPsiChild(); insertAttribute(editor, repoClass, phpDocTag, firstPsiChild); } }
Example 17
Source File: NewFileAction.java From idea-gitignore with MIT License | 4 votes |
/** * Creates new Gitignore file if it does not exist or uses an existing one and opens {@link GeneratorDialog}. * * @param e action event */ @Override public void actionPerformed(@NotNull AnActionEvent e) { final Project project = e.getRequiredData(CommonDataKeys.PROJECT); final IdeView view = e.getRequiredData(LangDataKeys.IDE_VIEW); VirtualFile fixedDirectory = fileType.getIgnoreLanguage().getFixedDirectory(project); PsiDirectory directory; if (fixedDirectory != null) { directory = PsiManager.getInstance(project).findDirectory(fixedDirectory); } else { directory = view.getOrChooseDirectory(); } if (directory == null) { return; } GeneratorDialog dialog; String filename = fileType.getIgnoreLanguage().getFilename(); PsiFile file = directory.findFile(filename); VirtualFile virtualFile = file == null ? directory.getVirtualFile().findChild(filename) : file.getVirtualFile(); if (file == null && virtualFile == null) { CreateFileCommandAction action = new CreateFileCommandAction(project, directory, fileType); dialog = new GeneratorDialog(project, action); } else { Notifications.Bus.notify(new Notification( fileType.getLanguageName(), IgnoreBundle.message("action.newFile.exists", fileType.getLanguageName()), IgnoreBundle.message("action.newFile.exists.in", virtualFile.getPath()), NotificationType.INFORMATION ), project); if (file == null) { file = Utils.getPsiFile(project, virtualFile); } dialog = new GeneratorDialog(project, file); } dialog.show(); file = dialog.getFile(); if (file != null) { Utils.openFile(project, file); } }
Example 18
Source File: BxCore.java From bxfs with MIT License | 4 votes |
private PsiFile getPageIncludeFile(PsiDirectory directory, String name, String suffix) { PsiFile file; if ((file = directory.findFile(String.format("%s_%s.php", suffix, name))) == null && suffix.equals("sect") && directory.getParent() != null) file = getPageIncludeFile(directory.getParent(), name, suffix); return file; }
Example 19
Source File: ExtraModulesUtil.java From weex-language-support with MIT License | 4 votes |
public static boolean isNodeModule(PsiDirectory dir) { PsiFile pkg = dir.findFile("package.json"); return pkg != null && pkg instanceof JsonFile; }
Example 20
Source File: ExtensionUtility.java From idea-php-typo3-plugin with MIT License | 4 votes |
private static PsiFile findExtEmConfPsiFile(@NotNull PsiDirectory extensionRootDirectory) { return extensionRootDirectory.findFile("ext_emconf.php"); }