Java Code Examples for com.intellij.psi.search.FilenameIndex#getFilesByName()

The following examples show how to use com.intellij.psi.search.FilenameIndex#getFilesByName() . 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: PsiPatchBaseDirectoryDetector.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public Result detectBaseDirectory(final String patchFileName) {
  String[] nameComponents = patchFileName.split("/");
  String patchName = nameComponents[nameComponents.length - 1];
  if (patchName.isEmpty()) {
    return null;
  }
  final PsiFile[] psiFiles = FilenameIndex.getFilesByName(myProject, patchName, GlobalSearchScope.projectScope(myProject));
  if (psiFiles.length == 1) {
    PsiDirectory parent = psiFiles [0].getContainingDirectory();
    for(int i=nameComponents.length-2; i >= 0; i--) {
      if (!parent.getName().equals(nameComponents[i]) || Comparing.equal(parent.getVirtualFile(), myProject.getBaseDir())) {
        return new Result(parent.getVirtualFile().getPresentableUrl(), i+1);
      }
      parent = parent.getParentDirectory();
    }
    if (parent == null) return null;
    return new Result(parent.getVirtualFile().getPresentableUrl(), 0);
  }
  return null;
}
 
Example 2
Source File: AbstractUploadCloudActionTest.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * 获取 PSI 的几种方式
 *
 * @param e the e
 */
private void getPsiFile(AnActionEvent e) {
    // 从 action 中获取
    PsiFile psiFileFromAction = e.getData(LangDataKeys.PSI_FILE);
    Project project = e.getProject();
    if (project != null) {
        VirtualFile virtualFile = e.getData(PlatformDataKeys.VIRTUAL_FILE);
        if (virtualFile != null) {
            // 从 VirtualFile 获取
            PsiFile psiFileFromVirtualFile = PsiManager.getInstance(project).findFile(virtualFile);

            // 从 document
            Document documentFromEditor = Objects.requireNonNull(e.getData(PlatformDataKeys.EDITOR)).getDocument();
            PsiFile psiFileFromDocument = PsiDocumentManager.getInstance(project).getPsiFile(documentFromEditor);

            // 在 project 范围内查找特定 PsiFile
            FilenameIndex.getFilesByName(project, "fileName", GlobalSearchScope.projectScope(project));
        }
    }

    // 找到特定 PSI 元素的使用位置
    // ReferencesSearch.search();
}
 
Example 3
Source File: SmartBashFileReference.java    From BashSupport with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public PsiElement resolveInner() {
    final String referencedName = cmd.getReferencedCommandName();
    if (referencedName == null) {
        return null;
    }

    String fileName = PathUtil.getFileName(referencedName);
    GlobalSearchScope scope = BashSearchScopes.moduleScope(cmd.getContainingFile());

    PsiFileSystemItem[] files = FilenameIndex.getFilesByName(cmd.getProject(), fileName, scope, false);
    if (files.length == 0) {
        return null;
    }

    PsiFile currentFile = cmd.getContainingFile();
    return BashPsiFileUtils.findRelativeFile(currentFile, referencedName);
}
 
Example 4
Source File: ORFileManager.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@Nullable
public static PsiFile findCmtFileFromSource(@NotNull Project project, @NotNull String filenameWithoutExtension) {
    if (!DumbService.isDumb(project)) {
        GlobalSearchScope scope = GlobalSearchScope.allScope(project);
        String filename = filenameWithoutExtension + ".cmt";

        PsiFile[] cmtFiles = FilenameIndex.getFilesByName(project, filename, scope);
        if (cmtFiles.length == 0) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("File module for " + filename + " is NOT FOUND, files found: [" + Joiner.join(", ", cmtFiles) + "]");
            }
            return null;
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Found cmt " + filename + " (" + cmtFiles[0].getVirtualFile().getPath() + ")");
        }

        return cmtFiles[0];
    } else {
        LOG.info("Cant find cmt while reindexing");
    }

    return null;
}
 
Example 5
Source File: AndroidUtils.java    From idea-android-studio-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Nullable
public static PsiFile findXmlResource(@Nullable PsiReferenceExpression referenceExpression) {
    if (referenceExpression == null) return null;

    PsiElement firstChild = referenceExpression.getFirstChild();
    if (firstChild == null || !"R.layout".equals(firstChild.getText())) {
        return null;
    }

    PsiElement lastChild = referenceExpression.getLastChild();
    if(lastChild == null) {
        return null;
    }

    String name = String.format("%s.xml", lastChild.getText());
    PsiFile[] foundFiles = FilenameIndex.getFilesByName(referenceExpression.getProject(), name, GlobalSearchScope.allScope(referenceExpression.getProject()));
    if (foundFiles.length <= 0) {
        return null;
    }

    return foundFiles[0];
}
 
Example 6
Source File: AndroidUtils.java    From idea-android-studio-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Nullable
public static PsiFile findXmlResource(Project project, String layoutName) {

    if (!layoutName.startsWith("R.layout.")) {
        return null;
    }

    layoutName = layoutName.substring("R.layout.".length());

    String name = String.format("%s.xml", layoutName);
    PsiFile[] foundFiles = FilenameIndex.getFilesByName(project, name, GlobalSearchScope.allScope(project));
    if (foundFiles.length <= 0) {
        return null;
    }

    return foundFiles[0];
}
 
Example 7
Source File: XQueryModuleReferenceTest.java    From intellij-xquery with Apache License 2.0 6 votes vote down vote up
public void testRenameOfTheFileWithReference() {
    myFixture.configureByFiles("ModuleReference.xq", "ModuleReference_ReferencedModule.xq");
    PsiFile[] files = FilenameIndex.getFilesByName(myFixture.getProject(), "ModuleReference_ReferencedModule.xq",
            GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(myFixture.getProject()),
                    XQueryFileType
                            .INSTANCE));

    myFixture.renameElement(files[0], "ModuleReference_RenamedFile.xq");
    myFixture.checkResultByFile("ModuleReference.xq", "ModuleReferenceAfterRenameOfReferencedFile.xq", false);
    PsiFile[] filesAfterRename = FilenameIndex.getFilesByName(myFixture.getProject(),
            "ModuleReference_RenamedFile.xq",
            GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(myFixture.getProject()),
                    XQueryFileType
                            .INSTANCE));
    assertEquals(1, files.length);
    assertNotNull(filesAfterRename[0]);
}
 
Example 8
Source File: DojoModuleFileResolver.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
public Set<String> getDirectoriesForDojoModules(Project project, Set<String> modules)
{
    Set<String> possibleDirectories = new HashSet<String>();

    for(String module : modules)
    {
        String moduleParent = module;

        if(module.contains("/"))
        {
            module = module.substring(module.lastIndexOf("/") + 1);
        }

        PsiFile[] files = FilenameIndex.getFilesByName(project, module + ".js", GlobalSearchScope.projectScope(project));

        for(PsiFile file : files)
        {
            if( file.getVirtualFile().getCanonicalPath().contains(moduleParent))
            {
                possibleDirectories.add(file.getParent().getParent().getName() +  " (" + file.getParent().getParent().getVirtualFile().getCanonicalPath() + ")");
            }
        }
    }

    return possibleDirectories;
}
 
Example 9
Source File: ViewCollector.java    From idea-php-laravel-plugin with MIT License 5 votes vote down vote up
private static void collectIdeJsonBladePaths(@NotNull Project project, @NotNull Collection<TemplatePath> templatePaths) {
    for (PsiFile psiFile : FilenameIndex.getFilesByName(project, "ide-blade.json", GlobalSearchScope.allScope(project))) {
        Collection<TemplatePath> cachedValue = CachedValuesManager.getCachedValue(psiFile, new MyJsonCachedValueProvider(psiFile));
        if(cachedValue != null) {
            templatePaths.addAll(cachedValue);
        }
    }
}
 
Example 10
Source File: TreeFileChooserDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
@Nonnull
public Object[] getElementsByName(final String name, final boolean checkBoxState, final String pattern) {
  GlobalSearchScope scope = myShowLibraryContents ? GlobalSearchScope.allScope(myProject) : GlobalSearchScope.projectScope(myProject);
  final PsiFile[] psiFiles = FilenameIndex.getFilesByName(myProject, name, scope);
  return filterFiles(psiFiles);
}
 
Example 11
Source File: FluidUtil.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@NotNull
public static Collection<FluidFile> findTemplatesForControllerAction(Method method) {
    List<FluidFile> fluidFiles = new ArrayList<>();

    if (!method.getName().endsWith("Action") && !method.getName().equals("Action")) {
        return fluidFiles;
    }

    String fileName = method.getName().substring(0, 1).toUpperCase() + method.getName().substring(1, method.getName().length() - "Action".length());
    PhpClass containingClass = method.getContainingClass();
    if (containingClass == null) {
        return fluidFiles;
    }

    if (!containingClass.getName().endsWith("Controller") && !containingClass.getName().equals("Controller")) {
        return fluidFiles;
    }

    String controllerName = containingClass.getName().substring(0, containingClass.getName().length() - "Controller".length());
    for (PsiFile psiFile : FilenameIndex.getFilesByName(method.getProject(), fileName + ".html", GlobalSearchScope.allScope(method.getProject()))) {
        if (psiFile.getContainingDirectory().getName().equals(controllerName) && psiFile instanceof FluidFile) {
            fluidFiles.add((FluidFile) psiFile);
        }
    }

    return fluidFiles;
}
 
Example 12
Source File: PhpGlobalsNamespaceProvider.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<FluidNamespace> provideForElement(@NotNull PsiElement element) {
    List<FluidNamespace> namespaces = new ArrayList<>();

    Project project = element.getProject();
    for (PsiFile psiFile : FilenameIndex.getFilesByName(project, "ext_localconf.php", GlobalSearchScope.allScope(project))) {
        GlobalsNamespaceVisitor visitor = new GlobalsNamespaceVisitor();
        psiFile.accept(visitor);

        namespaces.addAll(visitor.namespaces);
    }

    return namespaces;
}
 
Example 13
Source File: Utils.java    From android-butterknife-zelezny with Apache License 2.0 5 votes vote down vote up
private static PsiFile resolveLayoutResourceFile(PsiElement element, Project project, String name) {
    // restricting the search to the current module - searching the whole project could return wrong layouts
    Module module = ModuleUtil.findModuleForPsiElement(element);
    PsiFile[] files = null;
    if (module != null) {
        // first omit libraries, it might cause issues like (#103)
        GlobalSearchScope moduleScope = module.getModuleWithDependenciesScope();
        files = FilenameIndex.getFilesByName(project, name, moduleScope);
        if (files == null || files.length <= 0) {
            // now let's do a fallback including the libraries
            moduleScope = module.getModuleWithDependenciesAndLibrariesScope(false);
            files = FilenameIndex.getFilesByName(project, name, moduleScope);
        }
    }
    if (files == null || files.length <= 0) {
        // fallback to search through the whole project
        // useful when the project is not properly configured - when the resource directory is not configured
        files = FilenameIndex.getFilesByName(project, name, new EverythingGlobalScope(project));
        if (files.length <= 0) {
            return null; //no matching files
        }
    }

    // TODO - we have a problem here - we still can have multiple layouts (some coming from a dependency)
    // we need to resolve R class properly and find the proper layout for the R class
    for (PsiFile file : files) {
        log.info("Resolved layout resource file for name [" + name + "]: " + file.getVirtualFile());
    }
    return files[0];
}
 
Example 14
Source File: DeprecationUtility.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
public static Set<String> getDeprecatedGlobalFunctionCalls(@NotNull Project project) {
    Set<String> functionCallNames = new HashSet<>();
    PsiFile[] constantMatcherFiles = FilenameIndex.getFilesByName(project, "FunctionCallMatcher.php", GlobalSearchScope.allScope(project));
    for (PsiFile file : constantMatcherFiles) {

        functionCallNames.addAll(CachedValuesManager.getManager(project).getCachedValue(
            file,
            DEPRECATED_FUNCTION_CALLS,
            () -> CachedValueProvider.Result.create(getDeprecatedGlobalFunctionCallsFromFile(file), PsiModificationTracker.MODIFICATION_COUNT),
            false
        ));
    }

    return functionCallNames;
}
 
Example 15
Source File: DeprecationUtility.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
public static Set<String> getDeprecatedClassConstants(@NotNull Project project) {
    Set<String> constants = new HashSet<>();
    PsiFile[] classConstantMatcherFiles = FilenameIndex.getFilesByName(project, "ClassConstantMatcher.php", GlobalSearchScope.allScope(project));
    for (PsiFile file : classConstantMatcherFiles) {
        constants.addAll(CachedValuesManager.getManager(project).getCachedValue(
            file,
            DEPRECATED_CLASS_CONSTANTS,
            () -> CachedValueProvider.Result.create(getDeprecatedClassConstantsFromFile(file), PsiModificationTracker.MODIFICATION_COUNT),
            false
        ));
    }

    return constants;
}
 
Example 16
Source File: ExtLocalconfNamespaceProvider.java    From idea-php-typo3-plugin with MIT License 5 votes vote down vote up
@NotNull
@Override
public Collection<FluidNamespace> provideForElement(@NotNull PsiElement element) {
    PsiFile[] filesByName = FilenameIndex.getFilesByName(element.getProject(), "ext_localconf.php", GlobalSearchScope.allScope(element.getProject()));

    return ContainerUtil.emptyList();
}
 
Example 17
Source File: ViewCollector.java    From Thinkphp5-Plugin with MIT License 5 votes vote down vote up
private static void collectIdeJsonBladePaths(@NotNull Project project, @NotNull Collection<TemplatePath> templatePaths) {
    for (PsiFile psiFile : FilenameIndex.getFilesByName(project, "ide-blade.json", GlobalSearchScope.allScope(project))) {
        Collection<TemplatePath> cachedValue = CachedValuesManager.getCachedValue(psiFile, new MyJsonCachedValueProvider(psiFile));
        if (cachedValue != null) {
            templatePaths.addAll(cachedValue);
        }
    }
}
 
Example 18
Source File: JsonFileIndexTwigNamespaces.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@NotNull
private static Collection<TwigPath> getNamespacesInner(@NotNull Project project) {
    Collection<TwigPath> twigPaths = new ArrayList<>();

    for (final PsiFile psiFile : FilenameIndex.getFilesByName(project, "ide-twig.json", GlobalSearchScope.allScope(project))) {
        Collection<TwigPath> cachedValue = CachedValuesManager.getCachedValue(psiFile, new MyJsonCachedValueProvider(psiFile));
        if(cachedValue != null) {
            twigPaths.addAll(cachedValue);
        }
    }

    return twigPaths;
}
 
Example 19
Source File: TYPO3DetectionListener.java    From idea-php-typo3-plugin with MIT License 4 votes vote down vote up
private boolean containsPluginRelatedFiles(@NotNull Project project) {
    return (VfsUtil.findRelativeFile(project.getBaseDir(), "vendor", "typo3") != null)
        || FilenameIndex.getFilesByName(project, "ext_emconf.php", GlobalSearchScope.allScope(project)).length > 0;
}
 
Example 20
Source File: OnePojoInfoHelper.java    From codehelper.generator with Apache License 2.0 4 votes vote down vote up
public static void parseIdeaFieldInfo(@NotNull OnePojoInfo onePojoInfo, GenCodeResponse response){
        String pojoName = onePojoInfo.getPojoName();
        String pojoFileShortName = pojoName + ".java";
        Project project = response.getRequest().getProject();
        PsiFile[] psiFile = FilenameIndex
                .getFilesByName(project, pojoFileShortName, GlobalSearchScope.projectScope(project));
        PsiElement firstChild = psiFile[0].getFirstChild();
        LOGGER.info("parseIdeaFieldInfo psiFile[0] path :{}", psiFile[0].getVirtualFile().getPath());
        PsiElement child = null;
        for (PsiFile each: psiFile){
            VirtualFile vf = each.getVirtualFile();
            LOGGER.info("parseIdeaFieldInfo :{}, :{}", vf.getPath(), onePojoInfo.getFullPojoPath());
            if (removeSplit(vf.getPath()).equals(removeSplit(onePojoInfo.getFullPojoPath()))){
                child = firstChild;
            }
        }

        List<PsiElement> elements = Lists.newArrayList();

//        i// Find Psi of class and package
        do {
            if (child instanceof PsiClassImpl) {
                elements.add(child);
            }
            if (child instanceof PsiPackageStatementImpl){
                onePojoInfo.setPojoPackage(((PsiPackageStatementImpl) child).getPackageName());
            }
            child = child.getNextSibling();
        }
        while (child != null);

        PsiClassImpl psiClass = (PsiClassImpl) elements.get(0);
        PsiElement context = psiClass.getContext();
        if(context == null){
            throw new RuntimeException("parse class error");
        }
        String text = context.getText();
        onePojoInfo.setPojoPackage(parsePackage(text));
        PsiField[] allFields = psiClass.getAllFields();
        List<PojoFieldInfo> fieldList = Lists.newArrayList();

        for (PsiField field : allFields) {
            if(isStaticField(field)){
                continue;
            }
            SupportFieldClass fieldClass = SupportFieldClass.fromDesc(field.getType().getCanonicalText());
            LOGGER.info("parseIdeaFieldInfo  canonicalText :{}", field.getType().getCanonicalText());
            if(fieldClass == SupportFieldClass.NONE){
                continue;
            }
            PojoFieldInfo fieldInfo = new PojoFieldInfo();
            fieldInfo.setFieldComment(parseComment(field));
            fieldInfo.setFieldName(field.getName());
            fieldInfo.setFieldClass(fieldClass);
            fieldInfo.setAnnotations(Lists.newArrayList());
            if(!StringUtils.containsIgnoreCase(fieldInfo.getFieldComment(), "IgnoreAutoGenerate")) {
                fieldList.add(fieldInfo);
            }
        }
        onePojoInfo.setPojoFieldInfos(fieldList);
    }