com.intellij.psi.search.FilenameIndex Java Examples

The following examples show how to use com.intellij.psi.search.FilenameIndex. 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: 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 #2
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 #3
Source File: GodClassDistanceMatrixTest.java    From IntelliJDeodorant with MIT License 6 votes vote down vote up
@Nullable
private ExtractClassCandidateGroup getExractClassCandidateGroup(@NotNull String classFileName) {
    myFixture.setTestDataPath(PATH_TO_TESTDATA);
    myFixture.configureByFile(PATH_TO_TESTS + classFileName);
    Project project = myFixture.getProject();
    PsiFile psiFile = FilenameIndex.getFilesByName(project, classFileName, GlobalSearchScope.allScope(project))[0];
    ProjectInfo projectInfo = new ProjectInfo(new AnalysisScope(project), false);

    Set<ExtractClassCandidateGroup> set = getExtractClassRefactoringOpportunities(projectInfo, new ProgressIndicatorBase());

    if (set.isEmpty()) {
        return null;
    }

    return set.iterator().next();
}
 
Example #4
Source File: PsiViewerDialog.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
private PsiFile getContainingFileForClass(String fqn) {
  String filename = fqn;
  if (fqn.contains(".")) {
    filename = fqn.substring(fqn.lastIndexOf('.') + 1);
  }
  if (filename.contains("$")) {
    filename = filename.substring(0, filename.indexOf('$'));
  }
  filename += ".java";
  final PsiFile[] files = FilenameIndex.getFilesByName(myProject, filename, GlobalSearchScope.allScope(myProject));
  if (files != null && files.length > 0) {
    return files[0];
  }
  return null;
}
 
Example #5
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 #6
Source File: ORProjectManagerTest.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@Test
public void testFindBsConfigurationFiles_sortedByFileDepth() {
    String mockFileName = BsConstants.BS_CONFIG_FILENAME;
    MockVirtualFile mockBsConfigFileParent = new MockVirtualFile(mockFileName);
    MockVirtualFile mockBsConfigFile = new MockVirtualFile(mockFileName);
    MockVirtualFile mockBsConfigFileChild = new MockVirtualFile(mockFileName);
    // set up mock file hierarchy
    mockBsConfigFile.setParent(mockBsConfigFileParent);
    mockBsConfigFileChild.setParent(mockBsConfigFile);

    MockVirtualFile[] mocksUnsorted = { mockBsConfigFile, mockBsConfigFileChild, mockBsConfigFileParent };
    MockVirtualFile[] mocksSorted = { mockBsConfigFileParent, mockBsConfigFile, mockBsConfigFileChild };

    when(FilenameIndex.getVirtualFilesByName(mockProject, mockFileName, mockScope))
            .thenReturn(Arrays.asList(mocksUnsorted));

    LinkedHashSet<VirtualFile> bsConfigurationFiles = ORProjectManager.findBsConfigurationFiles(mockProject);
    assertMocksSorted(bsConfigurationFiles, mocksSorted);
}
 
Example #7
Source File: ORProjectManagerTest.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@Test
public void testFindDuneConfigurationFiles_sortedByFileDepth() {
    String mockFileName = DuneConstants.DUNE_FILENAME;
    MockVirtualFile mockDuneFileParent = new MockVirtualFile(mockFileName);
    MockVirtualFile mockDuneFile = new MockVirtualFile(mockFileName);
    MockVirtualFile mockDuneFileChild = new MockVirtualFile(mockFileName);
    // set up mock file hierarchy
    mockDuneFile.setParent(mockDuneFileParent);
    mockDuneFileChild.setParent(mockDuneFile);

    MockVirtualFile[] mocksUnsorted = { mockDuneFile, mockDuneFileChild, mockDuneFileParent };
    MockVirtualFile[] mocksSorted = { mockDuneFileParent, mockDuneFile, mockDuneFileChild };

    when(FilenameIndex.getVirtualFilesByName(mockProject, mockFileName, mockScope))
            .thenReturn(Arrays.asList(mocksUnsorted));

    LinkedHashSet<VirtualFile> duneConfigurationFiles = ORProjectManager.findDuneConfigurationFiles(mockProject);
    assertMocksSorted(duneConfigurationFiles, mocksSorted);
}
 
Example #8
Source File: ORProjectManagerTest.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@Test
public void testFindEsyConfigurationFiles_sortedByFileDepth() {
    String mockFileName = EsyConstants.ESY_CONFIG_FILENAME;
    MockVirtualFile mockEsyConfigFileParent = new MockVirtualFile(mockFileName);
    MockVirtualFile mockEsyConfigFile = new MockVirtualFile(mockFileName);
    MockVirtualFile mockEsyConfigFileChild = new MockVirtualFile(mockFileName);
    // set up mock file hierarchy
    mockEsyConfigFile.setParent(mockEsyConfigFileParent);
    mockEsyConfigFileChild.setParent(mockEsyConfigFile);

    MockVirtualFile[] mocksUnsorted = { mockEsyConfigFile, mockEsyConfigFileChild, mockEsyConfigFileParent };
    MockVirtualFile[] mocksSorted = { mockEsyConfigFileParent, mockEsyConfigFile, mockEsyConfigFileChild };

    when(FilenameIndex.getVirtualFilesByName(mockProject, mockFileName, mockScope))
            .thenReturn(Arrays.asList(mocksUnsorted));

    when(EsyPackageJson.isEsyPackageJson(any())).thenReturn(true);

    LinkedHashSet<VirtualFile> esyConfigurationFiles = ORProjectManager.findEsyConfigurationFiles(mockProject);
    assertMocksSorted(esyConfigurationFiles, mocksSorted);
}
 
Example #9
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 #10
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 #11
Source File: DeprecationUtility.java    From idea-php-typo3-plugin with MIT License 6 votes vote down vote up
public static Set<String> getDeprecatedConstantNames(@NotNull Project project) {
    Set<String> deprecatedConstants = new HashSet<>();

    PsiFile[] constantMatcherFiles = FilenameIndex.getFilesByName(project, "ConstantMatcher.php", GlobalSearchScope.allScope(project));
    for (PsiFile file : constantMatcherFiles) {

        deprecatedConstants.addAll(CachedValuesManager.getManager(project).getCachedValue(
            file,
            DEPRECATED_CONSTANTS,
            () -> CachedValueProvider.Result.create(getDeprecatedConstantNamesFromFile(file), PsiModificationTracker.MODIFICATION_COUNT),
            false
        ));

    }

    return deprecatedConstants;
}
 
Example #12
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 #13
Source File: DefaultFileNavigationContributor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void processElementsWithName(@Nonnull String name, @Nonnull final Processor<NavigationItem> _processor, @Nonnull FindSymbolParameters parameters) {
  final boolean globalSearch = parameters.getSearchScope().isSearchInLibraries();
  final Processor<PsiFileSystemItem> processor = item -> {
    if (!globalSearch && ProjectCoreUtil.isProjectOrWorkspaceFile(item.getVirtualFile())) {
      return true;
    }
    return _processor.process(item);
  };

  boolean directoriesOnly = isDirectoryOnlyPattern(parameters);
  if (!directoriesOnly) {
    FilenameIndex.processFilesByName(name, false, processor, parameters.getSearchScope(), parameters.getProject(), parameters.getIdFilter());
  }

  if (directoriesOnly || Registry.is("ide.goto.file.include.directories")) {
    FilenameIndex.processFilesByName(name, true, processor, parameters.getSearchScope(), parameters.getProject(), parameters.getIdFilter());
  }
}
 
Example #14
Source File: MuleSchemaProvider.java    From mule-intellij-plugins with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getSchemasFromSpringSchemas(@NotNull Module module) throws Exception {
    Map<String, String> schemasMap = new HashMap<>();

    PsiFile[] psiFiles = FilenameIndex.getFilesByName(module.getProject(), "spring.schemas", GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module));

    for (PsiFile nextSpringS : psiFiles) {
        VirtualFile springSchemasFile = nextSpringS.getVirtualFile();
        if (springSchemasFile != null) {
            String springSchemasContent = new String(springSchemasFile.contentsToByteArray());
            schemasMap.putAll(parseSpringSchemas(springSchemasContent));
        }
    }

    //Fix for HTTP module schema vs old HTTP transport schema
    schemasMap.put("http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd", "META-INF/mule-httpn.xsd");

    return schemasMap;
}
 
Example #15
Source File: ConsoleFlowStackFilter.java    From mule-intellij-plugins with Apache License 2.0 6 votes vote down vote up
@Nullable
@Override
public Result applyFilter(String textLine, int endPoint)
{
    final Matcher matcher = ELEMENT_REGEX.matcher(textLine);
    if (matcher.find())
    {
        final String element = matcher.group(1);
        final String fileName = matcher.group(4);
        final String lineNumber = matcher.group(5);
        final PsiFile[] psiFiles = FilenameIndex.getFilesByName(myProject, fileName, GlobalSearchScope.allScope(myProject));
        if (psiFiles.length == 0)
        {
            logger.debug("File: " + fileName + " not found in project: " + myProject.getName());
            return null;
        }
        else
        {
            HyperlinkInfo info = new OpenFileHyperlinkInfo(myProject, psiFiles[0].getVirtualFile(), Integer.parseInt(lineNumber) - 1);
            return new Result(endPoint - (textLine.length() - element.length()), endPoint, info);
        }
    }
    return null;
}
 
Example #16
Source File: NutzInjectToPropsReferenceContributor.java    From NutzCodeInsight with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext processingContext) {
    PsiLiteralExpression literalExpression = (PsiLiteralExpression) element;
    String value = literalExpression.getValue() instanceof String ? (String) literalExpression.getValue() : null;
    String key = NutzInjectConfUtil.getKey(value);
    if (NutzInjectConfUtil.isInjectConf(literalExpression) && key != null) {
        Project project = element.getProject();
        final Collection<VirtualFile> propertiesFiles = FilenameIndex.getAllFilesByExt(project, "properties", getSearchScope(project, element));
        final List<PsiElement> properties = NutzInjectConfUtil.findPropertiesPsiElement(project, propertiesFiles, key);
        List<PsiReference> psiReferences = new ArrayList<>();
        properties.forEach(psiElement -> psiReferences.add(new PsiJavaInjectReference(element, psiElement)));
        return psiReferences.toArray(new PsiReference[0]);
    } else {
        return PsiReference.EMPTY_ARRAY;
    }
}
 
Example #17
Source File: DrupalUtil.java    From idea-php-drupal-symfony2-bridge with MIT License 6 votes vote down vote up
@NotNull
public static Set<String> getModuleNames(@NotNull Project project) {
    Set<String> allFilesByExt = new HashSet<>();

    for (VirtualFile virtualFile : FilenameIndex.getAllFilesByExt(project, "yml")) {
        if(!virtualFile.getName().endsWith(".info.yml")) {
            continue;
        }

        allFilesByExt.add(StringUtils.stripEnd(virtualFile.getName(), ".info.yml"));
    }

    allFilesByExt.addAll(FilenameIndex.getAllFilesByExt(project, "module").stream()
        .map(virtualFile -> StringUtils.stripEnd(virtualFile.getName(), ".module"))
        .collect(Collectors.toList()));

    return allFilesByExt;
}
 
Example #18
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 #19
Source File: AndroidUtils.java    From idea-android-studio-plugin with GNU General Public License v2.0 6 votes vote down vote up
public static List<PsiFile> getLayoutFiles(Project project) {

        List<PsiFile> psiFileList = new ArrayList<PsiFile>();

        for (VirtualFile virtualFile : FilenameIndex.getAllFilesByExt(project, "xml")) {
            VirtualFile parent = virtualFile.getParent();
            if (parent != null && "layout".equals(parent.getName())) {
                String relative = VfsUtil.getRelativePath(virtualFile, project.getBaseDir(), '/');
                if (relative != null) {
                    PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
                    if (psiFile != null) {
                        psiFileList.add(psiFile);
                    }
                }
            }
        }

        return psiFileList;
    }
 
Example #20
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 #21
Source File: DojoModuleFileResolver.java    From needsmoredojo with Apache License 2.0 6 votes vote down vote up
/**
 * gets a list of all files that are part of your dojo project sources.
 * only retrieves javascript files
 *
 * @param project
 * @return
 */
public Collection<VirtualFile> getAllDojoProjectSourceFiles(Project project)
{
    VirtualFile[] sourceDirectories = SourcesLocator.getProjectSourceDirectories(project, true);
    List<VirtualFile> files = new ArrayList<VirtualFile>();
    for(VirtualFile file : sourceDirectories)
    {
        files.add(file);
    }

    Set<VirtualFile> psiFiles = new HashSet<VirtualFile>();
    Collection<VirtualFile> results = FilenameIndex.getAllFilesByExt(project, "js", GlobalSearchScope.projectScope(project));
    for(VirtualFile result : results)
    {
        for(VirtualFile directory : sourceDirectories)
        {
            if(VfsUtilCore.isAncestor(directory, result, false))
            {
                psiFiles.add(result);
                continue;
            }
        }
    }

    return results;
}
 
Example #22
Source File: ExtensionProviderUtil.java    From idea-php-toolbox with MIT License 5 votes vote down vote up
synchronized public static Collection<JsonConfigFile> getJsonConfigs(final @NotNull Project project, final @NotNull PhpToolboxApplicationService phpToolboxApplicationService) {
    CachedValue<Collection<JsonConfigFile>> cache = project.getUserData(CONFIGS_CACHE);

    if(cache == null) {
        cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getJsonConfigsInner(project, phpToolboxApplicationService), PsiModificationTracker.MODIFICATION_COUNT), false);
        project.putUserData(CONFIGS_CACHE, cache);
    }

    Collection<JsonConfigFile> jsonConfigFiles = new ArrayList<>(cache.getValue());

    // prevent reindex issues
    if (!DumbService.getInstance(project).isDumb()) {
        CachedValue<Collection<JsonConfigFile>> indexCache = project.getUserData(CONFIGS_CACHE_INDEX);

        if (indexCache == null) {
            indexCache = CachedValuesManager.getManager(project).createCachedValue(() -> {
                Collection<JsonConfigFile> jsonConfigFiles1 = new ArrayList<>();

                for (final PsiFile psiFile : FilenameIndex.getFilesByName(project, ".ide-toolbox.metadata.json", GlobalSearchScope.allScope(project))) {
                    JsonConfigFile cachedValue = CachedValuesManager.getCachedValue(psiFile, () -> new CachedValueProvider.Result<>(
                        JsonParseUtil.getDeserializeConfig(psiFile.getText()),
                        psiFile,
                        psiFile.getVirtualFile()
                    ));

                    if(cachedValue != null) {
                        jsonConfigFiles1.add(cachedValue);
                    }
                }

                return CachedValueProvider.Result.create(jsonConfigFiles1, PsiModificationTracker.MODIFICATION_COUNT);
            }, false);
        }

        project.putUserData(CONFIGS_CACHE_INDEX, indexCache);
        jsonConfigFiles.addAll(indexCache.getValue());
    }

    return jsonConfigFiles;
}
 
Example #23
Source File: UploadUtils.java    From markdown-image-kit with MIT License 5 votes vote down vote up
/**
 * Search virtual file by name virtual file.
 *
 * @param project the project
 * @param name    the name
 * @return the virtual file
 */
public static VirtualFile searchVirtualFileByName(Project project, String name) {
    // Read access is allowed from event dispatch thread or inside read-action only (see com.intellij.openapi.application.Application.runReadAction())
    AtomicReference<Collection<VirtualFile>> findedFiles = new AtomicReference<>();
    ApplicationManager.getApplication().runReadAction(() -> {
        findedFiles.set(FilenameIndex.getVirtualFilesByName(project, name, GlobalSearchScope.allScope(project)));
    });

    // 只取第一个图片
    return Iterables.getFirst(findedFiles.get(), null);
}
 
Example #24
Source File: DefaultFileNavigationContributor.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void processNames(@Nonnull final Processor<String> processor, @Nonnull GlobalSearchScope scope, IdFilter filter) {
  long started = System.currentTimeMillis();
  FilenameIndex.processAllFileNames(processor, scope, filter);
  if (LOG.isDebugEnabled()) {
    LOG.debug("All names retrieved:" + (System.currentTimeMillis() - started));
  }
}
 
Example #25
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 #26
Source File: GraphQLRelayModernEnableStartupActivity.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public void runActivity(@NotNull Project project) {
    final GraphQLSettings settings = GraphQLSettings.getSettings(project);
    if (settings.isEnableRelayModernFrameworkSupport()) {
        // already enabled Relay Modern
        return;
    }
    try {
        final GlobalSearchScope scope = GlobalSearchScope.projectScope(project);
        for (VirtualFile virtualFile : FilenameIndex.getVirtualFilesByName(project, "package.json", scope)) {
            if (!virtualFile.isDirectory() && virtualFile.isInLocalFileSystem()) {
                try (InputStream inputStream = virtualFile.getInputStream()) {
                    final String packageJson = IOUtils.toString(inputStream, virtualFile.getCharset());
                    if (packageJson.contains("\"react-relay\"") || packageJson.contains("\"relay-compiler\"")) {
                        final Notification enableRelayModern = new Notification("GraphQL", "Relay Modern project detected", "<a href=\"enable\">Enable Relay Modern</a> GraphQL tooling", NotificationType.INFORMATION, (notification, event) -> {
                            settings.setEnableRelayModernFrameworkSupport(true);
                            ApplicationManager.getApplication().saveSettings();
                            notification.expire();
                            DaemonCodeAnalyzer.getInstance(project).restart();
                            EditorNotifications.getInstance(project).updateAllNotifications();
                        });
                        enableRelayModern.setImportant(true);
                        Notifications.Bus.notify(enableRelayModern);
                        break;
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("Unable to detect Relay Modern", e);
    }
}
 
Example #27
Source File: OSSPantsIntegrationTest.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Find VirtualFile in project by filename.
 */
@NotNull
protected VirtualFile searchForVirtualFileInProject(String filename) {
  Collection<VirtualFile> files = FilenameIndex.getVirtualFilesByName(myProject, filename, GlobalSearchScope.allScope(myProject));
  assertEquals(String.format("%s not found.", filename), 1, files.size());
  return files.iterator().next();
}
 
Example #28
Source File: OSSPantsIntegrationTest.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Find VirtualFile in project by filename.
 */
@NotNull
protected VirtualFile firstMatchingVirtualFileInProject(String filename) {
  Collection<VirtualFile> files = FilenameIndex.getVirtualFilesByName(myProject, filename, GlobalSearchScope.allScope(myProject));
  assertTrue(String.format("Filename %s not found in project", filename), files.size() > 0);
  return files.iterator().next();
}
 
Example #29
Source File: ImagesProjectNode.java    From intellij-sdk-docs with Apache License 2.0 5 votes vote down vote up
private void addAllByExt(Project project, String ext) {
  final Set<VirtualFile> imagesFiles = getImagesFiles(project);
  final VirtualFile projectDir = ProjectUtil.guessProjectDir(project);
  for (VirtualFile file : FilenameIndex.getAllFilesByExt(project, ext)) {
    while (file != null && !file.equals(projectDir)) {
      imagesFiles.add(file);
      file = file.getParent();
    }
  }
}
 
Example #30
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];
}