下面列出了com.intellij.psi.impl.cache.CacheManager#com.intellij.util.indexing.FileBasedIndex 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void assertIndex(@NotNull ID<String, ?> id, boolean notCondition, @NotNull String... keys) {
for (String key : keys) {
final Collection<VirtualFile> virtualFiles = new ArrayList<VirtualFile>();
FileBasedIndex.getInstance().getFilesWithKey(id, new HashSet<>(Collections.singletonList(key)), virtualFile -> {
virtualFiles.add(virtualFile);
return true;
}, GlobalSearchScope.allScope(getProject()));
if(notCondition && virtualFiles.size() > 0) {
fail(String.format("Fail that ID '%s' not contains '%s'", id.toString(), key));
} else if(!notCondition && virtualFiles.size() == 0) {
fail(String.format("Fail that ID '%s' contains '%s'", id.toString(), key));
}
}
}
/**
* Find metadata model in which the given repository class is used
* eg "@ORM\Entity(repositoryClass="FOOBAR")", xml or yaml
*/
@NotNull
public static Collection<DoctrineModelInterface> findMetadataModelForRepositoryClass(final @NotNull Project project, @NotNull String repositoryClass) {
repositoryClass = StringUtils.stripStart(repositoryClass,"\\");
Collection<DoctrineModelInterface> models = new ArrayList<>();
for (String key : FileIndexCaches.getIndexKeysCache(project, CLASS_KEYS, DoctrineMetadataFileStubIndex.KEY)) {
for (DoctrineModelInterface repositoryDefinition : FileBasedIndex.getInstance().getValues(DoctrineMetadataFileStubIndex.KEY, key, GlobalSearchScope.allScope(project))) {
String myRepositoryClass = repositoryDefinition.getRepositoryClass();
if(StringUtils.isBlank(myRepositoryClass) ||
!repositoryClass.equalsIgnoreCase(StringUtils.stripStart(myRepositoryClass, "\\"))) {
continue;
}
models.add(repositoryDefinition);
}
}
return models;
}
/**
* 获取提示信息
*
* @return 返回提示集合
*/
@NotNull
@Override
public Collection<LookupElement> getLookupElements() {
final Collection<LookupElement> lookupElements = new ArrayList<>();
CollectProjectUniqueKeys ymlProjectProcessor = new CollectProjectUniqueKeys(getProject(), ConfigKeyStubIndex.KEY);
//扫描文件获取key, 放入ymlProjectProcessor
FileBasedIndex.getInstance().processAllKeys(ConfigKeyStubIndex.KEY, ymlProjectProcessor, getProject());
for (String key : ymlProjectProcessor.getResult()) {
lookupElements.add(LookupElementBuilder.create(key).withIcon(LaravelIcons.CONFIG));
}
return lookupElements;
}
@NotNull
private static Collection<PsiFile> getFilesImplementingAnnotation(@NotNull Project project, @NotNull String phpClassName) {
Collection<VirtualFile> files = new HashSet<>();
FileBasedIndex.getInstance().getFilesWithKey(AnnotationUsageIndex.KEY, new HashSet<>(Collections.singletonList(phpClassName)), virtualFile -> {
files.add(virtualFile);
return true;
}, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(project), PhpFileType.INSTANCE));
Collection<PsiFile> elements = new ArrayList<>();
for (VirtualFile file : files) {
PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
if(psiFile == null) {
continue;
}
elements.add(psiFile);
}
return elements;
}
public static Collection<PsiElement> getTwigMacroTargets(final Project project, final String name) {
final Collection<PsiElement> targets = new ArrayList<>();
FileBasedIndex.getInstance().getFilesWithKey(TwigMacroFunctionStubIndex.KEY, new HashSet<>(Collections.singletonList(name)), virtualFile -> {
PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
if (psiFile != null) {
PsiTreeUtil.processElements(psiFile, psiElement -> {
if (TwigPattern.getTwigMacroNameKnownPattern(name).accepts(psiElement)) {
targets.add(psiElement);
}
return true;
});
}
return true;
}, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(project), TwigFileType.INSTANCE));
return targets;
}
@Override
public boolean isGenerated(VirtualFile file) {
if (myGeneratedSources.contains(FileBasedIndex.getFileId(file))) {
return true;
}
if (isUnderRoots(myRootToModuleMap.keySet(), file)) {
return true;
}
final Module module = getModuleByFile(file);
if (module != null) {
for (AdditionalOutputDirectoriesProvider provider : AdditionalOutputDirectoriesProvider.EP_NAME.getExtensionList()) {
for (String path : provider.getOutputDirectories(getProject(), module)) {
if (path != null && VfsUtilCore.isAncestor(new File(path), new File(file.getPath()), true)) {
return true;
}
}
}
}
return false;
}
@Override
public void collectGotoRelatedItems(ControllerActionGotoRelatedCollectorParameter parameter) {
Method method = parameter.getMethod();
PhpClass containingClass = method.getContainingClass();
if (containingClass == null) {
return;
}
String controllerAction = StringUtils.stripStart(containingClass.getPresentableFQN(), "\\") + "::" + method.getName();
Collection<VirtualFile> targets = new HashSet<>();
FileBasedIndex.getInstance().getFilesWithKey(TwigControllerStubIndex.KEY, new HashSet<>(Collections.singletonList(controllerAction)), virtualFile -> {
targets.add(virtualFile);
return true;
}, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(parameter.getProject()), TwigFileType.INSTANCE));
for (PsiFile psiFile: PsiElementUtils.convertVirtualFilesToPsiFiles(parameter.getProject(), targets)) {
TwigUtil.visitControllerFunctions(psiFile, pair -> {
if (pair.getFirst().equalsIgnoreCase(controllerAction)) {
parameter.add(new RelatedPopupGotoLineMarker.PopupGotoRelatedItem(pair.getSecond()).withIcon(TwigIcons.TwigFileIcon, Symfony2Icons.TWIG_LINE_MARKER));
}
});
}
}
@NotNull
Collection<IndexedFileModule> getFilesForNamespace(@NotNull String namespace, @NotNull GlobalSearchScope scope) {
Collection<IndexedFileModule> result = new ArrayList<>();
FileBasedIndex fileIndex = FileBasedIndex.getInstance();
if (scope.getProject() != null) {
for (String key : fileIndex.getAllKeys(m_index.getName(), scope.getProject())) {
List<FileModuleData> values = fileIndex.getValues(m_index.getName(), key, scope);
int valuesSize = values.size();
if (valuesSize > 2) {
System.out.println("ERROR, size of " + key + " is " + valuesSize);
} else {
for (FileModuleData value : values) {
if (valuesSize == 1 || value.isInterface()) {
if (namespace.equals(value.getNamespace())) {
result.add(value);
}
}
}
}
}
}
return result;
}
@Override
public void projectOpened(@NotNull Project project) {
this.checkProject(project);
TYPO3CMSSettings instance = TYPO3CMSSettings.getInstance(project);
IdeaPluginDescriptor plugin = PluginManager.getPlugin(PluginId.getId("com.cedricziel.idea.typo3"));
if (plugin == null) {
return;
}
String version = instance.getVersion();
if (version == null || !plugin.getVersion().equals(version)) {
instance.setVersion(plugin.getVersion());
FileBasedIndex index = FileBasedIndex.getInstance();
index.scheduleRebuild(CoreServiceMapStubIndex.KEY, new Throwable());
index.scheduleRebuild(ExtensionNameStubIndex.KEY, new Throwable());
index.scheduleRebuild(IconIndex.KEY, new Throwable());
index.scheduleRebuild(ResourcePathIndex.KEY, new Throwable());
index.scheduleRebuild(RouteIndex.KEY, new Throwable());
index.scheduleRebuild(TablenameFileIndex.KEY, new Throwable());
index.scheduleRebuild(LegacyClassesForIDEIndex.KEY, new Throwable());
index.scheduleRebuild(MethodArgumentDroppedIndex.KEY, new Throwable());
index.scheduleRebuild(ControllerActionIndex.KEY, new Throwable());
}
}
public static void reparseProjectFiles(@NotNull final Project project) {
Task.Backgroundable task = new Task.Backgroundable(project, HaxeBundle.message("haxe.project.reparsing"), false) {
public void run(@NotNull ProgressIndicator indicator) {
final Collection<VirtualFile> haxeFiles = new ArrayList<VirtualFile>();
final VirtualFile baseDir = project.getBaseDir();
if (baseDir != null) {
FileBasedIndex.getInstance().iterateIndexableFiles(new ContentIterator() {
public boolean processFile(VirtualFile file) {
if (HaxeFileType.HAXE_FILE_TYPE == file.getFileType()) {
haxeFiles.add(file);
}
return true;
}
}, project, indicator);
}
ApplicationManager.getApplication().invokeAndWait(new Runnable() {
public void run() {
FileContentUtil.reparseFiles(project, haxeFiles, !project.isDefault());
}
}, ModalityState.NON_MODAL);
}
};
ProgressManager.getInstance().run(task);
}
@NotNull
private synchronized static Collection<String> getAllKeys(@NotNull Project project) {
CachedValue<Collection<String>> cachedValue = project.getUserData(TRANSLATION_KEYS);
if (cachedValue != null && cachedValue.hasUpToDateValue()) {
return TRANSLATION_KEYS_LOCAL_CACHE.getOrDefault(project, new ArrayList<>());
}
cachedValue = CachedValuesManager.getManager(project).createCachedValue(() -> {
Collection<String> allKeys = FileBasedIndex.getInstance().getAllKeys(TranslationIndex.KEY, project);
if (TRANSLATION_KEYS_LOCAL_CACHE.containsKey(project)) {
TRANSLATION_KEYS_LOCAL_CACHE.replace(project, allKeys);
} else {
TRANSLATION_KEYS_LOCAL_CACHE.put(project, allKeys);
}
return CachedValueProvider.Result.create(new ArrayList<>(), MODIFICATION_COUNT);
}, false);
project.putUserData(TRANSLATION_KEYS, cachedValue);
return TRANSLATION_KEYS_LOCAL_CACHE.getOrDefault(project, cachedValue.getValue());
}
public static PsiElement[] getTableDefinitionElements(@NotNull String tableName, @NotNull Project project) {
PsiFile[] extTablesSqlFilesInProjectContainingTable = getExtTablesSqlFilesInProjectContainingTable(tableName, project);
Set<PsiElement> elements = new HashSet<>();
PsiManager psiManager = PsiManager.getInstance(project);
for (PsiFile virtualFile : extTablesSqlFilesInProjectContainingTable) {
FileBasedIndex.getInstance().processValues(TablenameFileIndex.KEY, tableName, virtualFile.getVirtualFile(), (file, value) -> {
PsiFile file1 = psiManager.findFile(file);
if (file1 != null) {
PsiElement elementAt = file1.findElementAt(value.getEndOffset() - 2);
if (elementAt != null) {
elements.add(elementAt);
}
}
return true;
}, GlobalSearchScope.allScope(project));
}
return elements.toArray(new PsiElement[0]);
}
public void assertIndex(@NotNull ID<String, ?> id, boolean notCondition, @NotNull String... keys) {
for (String key : keys) {
final Collection<VirtualFile> virtualFiles = new ArrayList<VirtualFile>();
FileBasedIndex.getInstance().getFilesWithKey(id, new HashSet<>(Collections.singletonList(key)), virtualFile -> {
virtualFiles.add(virtualFile);
return true;
}, GlobalSearchScope.allScope(getProject()));
if(notCondition && virtualFiles.size() > 0) {
fail(String.format("Fail that ID '%s' not contains '%s'", id.toString(), key));
} else if(!notCondition && virtualFiles.size() == 0) {
fail(String.format("Fail that ID '%s' contains '%s'", id.toString(), key));
}
}
}
public void assertIndex(@NotNull ID<String, ?> id, boolean notCondition, @NotNull String... keys) {
for (String key : keys) {
final Collection<VirtualFile> virtualFiles = new ArrayList<VirtualFile>();
FileBasedIndex.getInstance().getFilesWithKey(id, new HashSet<String>(Collections.singletonList(key)), new Processor<VirtualFile>() {
@Override
public boolean process(VirtualFile virtualFile) {
virtualFiles.add(virtualFile);
return true;
}
}, GlobalSearchScope.allScope(getProject()));
if(notCondition && virtualFiles.size() > 0) {
fail(String.format("Fail that ID '%s' not contains '%s'", id.toString(), key));
} else if(!notCondition && virtualFiles.size() == 0) {
fail(String.format("Fail that ID '%s' contains '%s'", id.toString(), key));
}
}
}
@NotNull
@Override
public Collection<PsiElement> getTranslationTargets(@NotNull Project project, @NotNull String translationKey, @NotNull String domain) {
Collection<PsiElement> psiFoundElements = new ArrayList<>();
Collection<VirtualFile> files = new HashSet<>();
FileBasedIndex.getInstance().getFilesWithKey(TranslationStubIndex.KEY, new HashSet<>(Collections.singletonList(domain)), virtualFile -> {
files.add(virtualFile);
return true;
}, GlobalSearchScope.allScope(project));
for (PsiFile psiFile : PsiElementUtils.convertVirtualFilesToPsiFiles(project, files)) {
psiFoundElements.addAll(TranslationUtil.getTranslationKeyTargetInsideFile(psiFile, domain, translationKey));
}
return psiFoundElements;
}
@Override
protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) {
Project project = parameters.getPosition().getProject();
Collection<String> contexts = FileBasedIndex.getInstance().getAllKeys(DefaultContextFileIndex.KEY, project);
for (String eelHelper : contexts) {
List<String> helpers = FileBasedIndex.getInstance().getValues(DefaultContextFileIndex.KEY, eelHelper, GlobalSearchScope.allScope(project));
if (!helpers.isEmpty()) {
for (String helper : helpers) {
Collection<PhpClass> classes = PhpIndex.getInstance(project).getClassesByFQN(helper);
for (PhpClass phpClass : classes) {
for (Method method : phpClass.getMethods()) {
if (!method.getAccess().isPublic()) {
continue;
}
if (method.getName().equals("allowsCallOfMethod")) {
continue;
}
String completionText = eelHelper + "." + method.getName() + "()";
result.addElement(LookupElementBuilder.create(completionText).withIcon(PhpIcons.METHOD_ICON));
}
}
}
}
}
}
@Override
public void annotate(@NotNull PsiElement element, @NotNull AnnotationHolder holder) {
if (element instanceof FusionMethodCall) {
FusionMethodCall methodCall = (FusionMethodCall) element;
if (methodCall.getPrevSibling() != null && methodCall.getPrevSibling().getPrevSibling() instanceof FusionCompositeIdentifier) {
FusionCompositeIdentifier compositeId = (FusionCompositeIdentifier) methodCall.getPrevSibling().getPrevSibling();
List<String> helpers = FileBasedIndex.getInstance().getValues(DefaultContextFileIndex.KEY, compositeId.getText(), GlobalSearchScope.allScope(element.getProject()));
if (!helpers.isEmpty()) {
for (String helper : helpers) {
if (PhpElementsUtil.getClassMethod(element.getProject(), helper, methodCall.getMethodName().getText()) != null) {
return;
}
}
holder.createErrorAnnotation(methodCall, "Unresolved EEL helper method");
}
}
}
}
private static void getExtendsImplementations(@NotNull Project project, @NotNull String templateName, @NotNull Set<VirtualFile> virtualFiles, int depth) {
if(depth-- <= 0) {
return;
}
int finalDepth = depth;
FileBasedIndex.getInstance().getFilesWithKey(BladeExtendsStubIndex.KEY, Collections.singleton(templateName), virtualFile -> {
if (!virtualFiles.contains(virtualFile)) {
virtualFiles.add(virtualFile);
for (String nextTpl : BladeTemplateUtil.resolveTemplateName(project, virtualFile)) {
getExtendsImplementations(project, nextTpl, virtualFiles, finalDepth);
}
}
return true;
}, GlobalSearchScope.getScopeRestrictedByFileTypes(GlobalSearchScope.allScope(project), BladeFileType.INSTANCE));
}
/**
* Try to find repository class on models scope on its metadata definition
*/
@Nullable
public static PhpClass getClassRepository(final @NotNull Project project, final @NotNull String className) {
for (VirtualFile virtualFile : FileBasedIndex.getInstance().getContainingFiles(DoctrineMetadataFileStubIndex.KEY, className, GlobalSearchScope.allScope(project))) {
final String[] phpClass = {null};
FileBasedIndex.getInstance().processValues(DoctrineMetadataFileStubIndex.KEY, className, virtualFile, (virtualFile1, model) -> {
if (phpClass[0] != null || model == null || model.getRepositoryClass() == null) {
return true;
}
// piping value out of this index thread
phpClass[0] = model.getRepositoryClass();
return true;
}, GlobalSearchScope.allScope(project));
if(phpClass[0] != null) {
return PhpElementsUtil.getClassInsideNamespaceScope(project, className, phpClass[0]);
}
}
return null;
}
@NotNull
public static Collection<PhpClass> getFormClassForId(@NotNull Project project, @NotNull String id) {
Collection<PhpClass> phpClasses = new ArrayList<>();
for (String key : SymfonyProcessors.createResult(project, ConfigEntityTypeAnnotationIndex.KEY)) {
if(!id.equals(key)) {
continue;
}
for (String value : FileBasedIndex.getInstance().getValues(ConfigEntityTypeAnnotationIndex.KEY, key, GlobalSearchScope.allScope(project))) {
phpClasses.addAll(PhpElementsUtil.getClassesInterface(project, value));
}
}
return phpClasses;
}
/**
* Returns collection of indexed {@link IgnoreEntryOccurrence} for given {@link Project} and {@link IgnoreFileType}.
*
* @param project current project
* @param fileType filetype
* @return {@link IgnoreEntryOccurrence} collection
*/
@NotNull
public static List<IgnoreEntryOccurrence> getEntries(@NotNull Project project, @NotNull IgnoreFileType fileType) {
try {
if (ApplicationManager.getApplication().isReadAccessAllowed()) {
final GlobalSearchScope scope = IgnoreSearchScope.get(project);
return FileBasedIndex.getInstance()
.getValues(IgnoreFilesIndex.KEY, new IgnoreFileTypeKey(fileType), scope);
}
} catch (RuntimeException ignored) {
}
return ContainerUtil.emptyList();
}
public <T> void assertIndexContainsKeyWithValue(@NotNull ID<String, T> id, @NotNull String key, @NotNull IndexValue.Assert<T> tAssert) {
List<T> values = FileBasedIndex.getInstance().getValues(id, key, GlobalSearchScope.allScope(getProject()));
for (T t : values) {
if(tAssert.match(t)) {
return;
}
}
fail(String.format("Fail that Key '%s' matches on of '%s' values", key, values.size()));
}
private Set<String> getNames() {
// use overall map if already generated
if(this.containerParameterMap != null) {
return this.containerParameterMap.keySet();
}
Set<String> parameterNames = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
// local filesystem
parameterNames.addAll(ServiceXmlParserFactory.getInstance(project, ParameterServiceParser.class).getParameterMap().keySet());
// index
parameterNames.addAll(
FileIndexCaches.getIndexKeysCache(project, SERVICE_PARAMETER_INDEX_NAMES, ContainerParameterStubIndex.KEY)
);
// setParameter("foo") for ContainerBuilder
for (ContainerBuilderCall call : FileBasedIndex.getInstance().getValues(ContainerBuilderStubIndex.KEY, "setParameter", GlobalSearchScope.allScope(project))) {
Collection<String> parameter = call.getParameter();
if(parameter != null) {
parameterNames.addAll(parameter);
}
}
return parameterNames;
}
public Set<String> getResult() {
Set<String> set = new HashSet<>();
for (String key : stringSet) {
Collection fileCollection = FileBasedIndex.getInstance().getContainingFiles(id, key, GlobalSearchScope.allScope(project));
if (fileCollection.size() > 0) {
set.add(key);
}
}
return set;
}
public void testInstanceExtractionOfDocComment() {
assertIndexContains(EventAnnotationStubIndex.KEY, "form.pre_bind");
DispatcherEvent event = ContainerUtil.getFirstItem(FileBasedIndex.getInstance().getValues(
EventAnnotationStubIndex.KEY,
"form.pre_bind",
GlobalSearchScope.allScope(getProject()))
);
assertEquals("Symfony\\Component\\Form\\FormEvents.PRE_SUBMIT", event.getFqn());
assertEquals("Symfony\\Component\\Form\\FormEvent", event.getInstance());
}
public void testIndexValue() {
FileResource item = ContainerUtil.getFirstItem(FileBasedIndex.getInstance().getValues(FileResourcesIndex.KEY, "@AppBundle/Controller", GlobalSearchScope.allScope(getProject())));
assertEquals("/foo", item.getPrefix());
item = ContainerUtil.getFirstItem(FileBasedIndex.getInstance().getValues(FileResourcesIndex.KEY, "@AcmeOtherBundle/Resources/config/routing.xml", GlobalSearchScope.allScope(getProject())));
assertEquals("/foo2", item.getPrefix());
}
private boolean isDomainAndKeyInPsi(@NotNull PsiFile psiFile, @NotNull String key, @NotNull String domain) {
List<Set<String>> values = FileBasedIndex.getInstance()
.getValues(TranslationStubIndex.KEY, domain, GlobalSearchScope.fileScope(psiFile));
for (Set<String> value : values) {
if(value.contains(key)) {
return true;
}
}
return false;
}
public <T> void assertIndexContainsKeyWithValue(@NotNull ID<String, T> id, @NotNull String key, @NotNull IndexValue.Assert<T> tAssert) {
List<T> values = FileBasedIndex.getInstance().getValues(id, key, GlobalSearchScope.allScope(getProject()));
for (T t : values) {
if(tAssert.match(t)) {
return;
}
}
fail(String.format("Fail that Key '%s' matches on of '%s' values", key, values.size()));
}
@Override
protected void doSynchronizeRoots() {
if (!myStartupActivityPerformed) return;
if (myDoLogCachesUpdate) {
LOG.debug(new Throwable("sync roots"));
}
else if (!ApplicationManager.getApplication().isUnitTestMode()) LOG.info("project roots have changed");
DumbServiceImpl dumbService = DumbServiceImpl.getInstance(myProject);
if (FileBasedIndex.getInstance() instanceof FileBasedIndexImpl) {
dumbService.queueTask(new UnindexedFilesUpdater(myProject));
}
}
@NotNull
public static Collection<LookupElement> getRoutesLookupElements(@NotNull Project project) {
Collection<LookupElement> routeLookupElements = new ArrayList<>();
Collection<String> routes = FileBasedIndex.getInstance().getAllKeys(RouteIndex.KEY, project);
for (String routeName : routes) {
List<RouteStub> values = FileBasedIndex.getInstance().getValues(RouteIndex.KEY, routeName, GlobalSearchScope.allScope(project));
values.forEach(r -> routeLookupElements.add(new RouteLookupElement(r)));
}
return routeLookupElements;
}