下面列出了怎么用com.intellij.psi.search.GlobalSearchScope的API类实例代码及写法,或者点击链接到github查看源代码。
public static PsiElement[] getDefinitionElements(@NotNull Project project, @NotNull String actionName) {
Set<String> keys = new HashSet<>();
keys.add(actionName);
List<PsiElement> elements = new ArrayList<>();
FileBasedIndex.getInstance().getFilesWithKey(ControllerActionIndex.KEY, keys, virtualFile -> {
FileBasedIndex.getInstance().processValues(ControllerActionIndex.KEY, actionName, virtualFile, (file, value) -> {
PsiFile file1 = PsiManager.getInstance(project).findFile(file);
if (file1 != null) {
PsiElement elementAt = file1.findElementAt(value.getTextRange().getStartOffset());
if (elementAt != null) {
elements.add(elementAt.getParent().getParent());
}
}
return true;
}, GlobalSearchScope.allScope(project));
return true;
}, GlobalSearchScope.allScope(project));
return elements.toArray(new PsiElement[0]);
}
private @NotNull List<PsiElementResolveResult> handleImportReferences(@NotNull HaskellImpdecl haskellImpdecl,
@NotNull PsiNamedElement myElement, int i) {
/**
* Don't use the named element yet to determine which element we're
* talking about, not necessary yet
*/
List<PsiElementResolveResult> modulesFound = new ArrayList<PsiElementResolveResult>();
List<HaskellQconid> qconidList = haskellImpdecl.getQconidList();
if (qconidList.size() > 0){
String moduleName = qconidList.get(0).getText();
GlobalSearchScope globalSearchScope = GlobalSearchScope.projectScope(myElement.getProject());
List<HaskellFile> filesByModuleName = HaskellModuleIndex.getFilesByModuleName(myElement.getProject(), moduleName, globalSearchScope);
for (HaskellFile haskellFile : filesByModuleName) {
HaskellModuledecl[] moduleDecls = PsiTreeUtil.getChildrenOfType(haskellFile, HaskellModuledecl.class);
if (moduleDecls != null && moduleDecls.length > 0){
HaskellQconid qconid = moduleDecls[0].getQconid();
if (qconid != null) {
List<HaskellConid> conidList = moduleDecls[0].getQconid().getConidList();
modulesFound.add(new PsiElementResolveResult(conidList.get(i)));
}
}
}
}
return modulesFound;
}
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;
}
public static List<String> findAllKeys(Project project, GlobalSearchScope scope) {
final List<String> result = new ArrayList<String>();
FileBasedIndex.getInstance().processAllKeys(
THRIFT_DECLARATION_INDEX,
new Processor<String>() {
@Override
public boolean process(String name) {
result.add(name);
return true;
}
},
scope,
null
);
return result;
}
@NotNull
protected UsageInfo[] findUsages() {
PsiReference[] refs = ReferencesSearch.search(myClass, GlobalSearchScope.projectScope(myProject), false).toArray(new PsiReference[0]);
final ArrayList<UsageInfo> result = new ArrayList<UsageInfo>();
detectTurnToSuperRefs(refs, result);
final PsiPackage originalPackage = JavaDirectoryService.getInstance().getPackage(myClass.getContainingFile().getContainingDirectory());
if (Comparing.equal(JavaDirectoryService.getInstance().getPackage(myTargetDirectory), originalPackage)) {
result.clear();
}
for (final PsiReference ref : refs) {
final PsiElement element = ref.getElement();
if (!canTurnToSuper(element) && !RefactoringUtil.inImportStatement(ref, element)) {
result.add(new BindToOldUsageInfo(element, ref, myClass));
}
}
UsageInfo[] usageInfos = result.toArray(new UsageInfo[result.size()]);
return UsageViewUtil.removeDuplicatedUsages(usageInfos);
}
/**
* @param dataHolderKey Main data to cache
* @param dataHolderNames Cache extracted name Set
*/
static public synchronized <T> Map<String, List<T>> getSetDataCache(@NotNull final Project project, @NotNull Key<CachedValue<Map<String, List<T>>>> dataHolderKey, final @NotNull Key<CachedValue<Set<String>>> dataHolderNames, @NotNull final ID<String, T> ID, @NotNull final GlobalSearchScope scope) {
return CachedValuesManager.getManager(project).getCachedValue(
project,
dataHolderKey,
() -> {
Map<String, List<T>> items = new HashMap<>();
final FileBasedIndex fileBasedIndex = FileBasedIndex.getInstance();
getIndexKeysCache(project, dataHolderNames, ID).forEach(service ->
items.put(service, fileBasedIndex.getValues(ID, service, scope))
);
return CachedValueProvider.Result.create(items, getModificationTrackerForIndexId(project, ID));
},
false
);
}
private static List<SoyParamSpecificationIdentifier> getReferencingParamSpecificationIdentifiers(
SoyParamDefinitionIdentifier paramDefinitionIdentifier) {
Project project = paramDefinitionIdentifier.getProject();
final ImmutableList.Builder<SoyParamSpecificationIdentifier> result = ImmutableList.builder();
Collection<VirtualFile> virtualFiles =
FileTypeIndex.getFiles(SoyFileType.INSTANCE, GlobalSearchScope.allScope(project));
for (VirtualFile virtualFile : virtualFiles) {
SoyFile soyFile = (SoyFile) PsiManager.getInstance(project).findFile(virtualFile);
if (soyFile != null) {
soyFile.accept(new SoyRecursiveElementVisitor() {
@Override
public void visitParamSpecificationIdentifier(
@NotNull SoyParamSpecificationIdentifier identifier) {
super.visitParamSpecificationIdentifier(identifier);
PsiReference reference = identifier.getReference();
if (reference != null && paramDefinitionIdentifier.equals(reference.resolve())) {
result.add(identifier);
}
}
});
}
}
return result.build();
}
/**
* @param project project
* @param key environment variable key
* @return All key usages, like getenv('KEY')
*/
@NotNull
public static PsiElement[] getKeyUsages(Project project, String key) {
List<PsiElement> targets = new ArrayList<>();
PsiSearchHelper searchHelper = PsiSearchHelper.getInstance(project);
Processor<PsiFile> psiFileProcessor = psiFile -> {
for (EnvironmentVariablesUsagesProvider provider : EnvironmentVariablesProviderUtil.USAGES_PROVIDERS) {
targets.addAll(EnvironmentVariablesUtil.getUsagesElementsByKey(key, provider.getUsages(psiFile)));
}
return true;
};
searchHelper.processAllFilesWithWord(key, GlobalSearchScope.allScope(project), psiFileProcessor, true);
searchHelper.processAllFilesWithWordInLiterals(key, GlobalSearchScope.allScope(project), psiFileProcessor);
return targets.toArray(PsiElement.EMPTY_ARRAY);
}
@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;
}
@Nullable
public static VirtualFile findResourceFileInScope(final String resourceName,
final Project project,
final GlobalSearchScope scope) {
int index = resourceName.lastIndexOf('/');
String packageName = index >= 0 ? resourceName.substring(0, index).replace('/', '.') : "";
final String fileName = index >= 0 ? resourceName.substring(index+1) : resourceName;
Query<VirtualFile> directoriesByPackageName = DirectoryIndex.getInstance(project).getDirectoriesByPackageName(packageName, true);
for (VirtualFile virtualFile : directoriesByPackageName) {
final VirtualFile child = virtualFile.findChild(fileName);
if(child != null && scope.contains(child)) {
return child;
}
}
return null;
}
@Override
public List<Location> getLocation(
String protocol, String path, Project project, GlobalSearchScope scope) {
if (protocol.equals(SmRunnerUtils.GENERIC_SUITE_PROTOCOL)) {
return findTestClass(project, scope, path);
}
if (protocol.equals(SmRunnerUtils.GENERIC_TEST_PROTOCOL)) {
path = StringUtil.trimStart(path, PY_TESTCASE_PREFIX);
String[] components = path.split("\\.|::");
if (components.length < 2) {
return ImmutableList.of();
}
return findTestMethod(
project, scope, components[components.length - 2], components[components.length - 1]);
}
return ImmutableList.of();
}
@NotNull
public static Collection<Route> getRoute(@NotNull Project project, @NotNull String routeName) {
Map<String, Route> compiledRoutes = RouteHelper.getCompiledRoutes(project);
if(compiledRoutes.containsKey(routeName)) {
return Collections.singletonList(compiledRoutes.get(routeName));
}
Collection<Route> routes = new ArrayList<>();
Collection<VirtualFile> routeFiles = FileBasedIndex.getInstance().getContainingFiles(RoutesStubIndex.KEY, routeName, GlobalSearchScope.allScope(project));
for(StubIndexedRoute route: FileBasedIndex.getInstance().getValues(RoutesStubIndex.KEY, routeName, GlobalSearchScope.filesScope(project, routeFiles))) {
routes.add(new Route(route));
}
return routes;
}
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]);
}
@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;
}
private static List<Location> findTestMethod(
Project project, GlobalSearchScope scope, String className, @Nullable String methodName) {
List<Location> results = new ArrayList<>();
if (methodName == null) {
return findTestClass(project, scope, className);
}
for (PyClass pyClass : PyClassNameIndex.find(className, project, scope)) {
ProgressManager.checkCanceled();
if (PyTestUtils.isTestClass(pyClass)) {
PyFunction method = findMethod(pyClass, methodName);
if (method != null && PyTestUtils.isTestFunction(method)) {
results.add(new PsiLocation<>(project, method));
}
results.add(new PsiLocation<>(project, pyClass));
}
}
return results;
}
@NotNull
public Set<String> getResult() {
return stringSet.stream()
.filter(
s -> FileBasedIndex.getInstance().getContainingFiles(id, s, GlobalSearchScope.allScope(project)).size() > 0)
.collect(Collectors.toSet()
);
}
/**
* @return read-only iterator of all valid PSI files that can have T.O.D.O items
* and which are located under specified <code>psiDirctory</code>.
*/
public Iterator<PsiFile> getFiles(PackageElement packageElement) {
ArrayList<PsiFile> psiFileList = new ArrayList<PsiFile>();
GlobalSearchScope scope = packageElement.getModule() != null ? GlobalSearchScope.moduleScope(packageElement.getModule()) :
GlobalSearchScope.projectScope(myProject);
final PsiDirectory[] directories = packageElement.getPackage().getDirectories(scope);
for (PsiDirectory directory : directories) {
Iterator<PsiFile> files = myBuilder.getFiles(directory, false);
for (;files.hasNext();) {
psiFileList.add(files.next());
}
}
return psiFileList.iterator();
}
/**
* Find a target translation key based on all supported formats
*/
public static Collection<PsiElement> getTranslationKeyTargetInsideFile(@NotNull PsiFile psiFile, @NotNull String domain, @NotNull String translationKey) {
Set<PsiElement> elements = new HashSet<>();
if(psiFile instanceof YAMLFile) {
// collect on yaml keys
YamlTranslationVisitor.collectFileTranslations((YAMLFile) psiFile, (keyName, yamlKeyValue) -> {
if (keyName.equals(translationKey)) {
// multiline "line values" are not resolve properly on psiElements use key as fallback target
PsiElement valuePsiElement = yamlKeyValue.getValue();
elements.add(valuePsiElement != null ? valuePsiElement : yamlKeyValue);
return false;
}
return true;
});
} else if(TranslationUtil.isSupportedXlfFile(psiFile)) {
// fine: xlf registered as XML file. try to find source value
elements.addAll(TranslationUtil.getTargetForXlfAsXmlFile((XmlFile) psiFile, translationKey));
} else if(("xlf".equalsIgnoreCase(psiFile.getVirtualFile().getExtension()) || "xliff".equalsIgnoreCase(psiFile.getVirtualFile().getExtension()))) {
// xlf are plain text because not supported by jetbrains
// for now we can only set file target
Project project = psiFile.getProject();
elements.addAll(FileBasedIndex.getInstance()
.getValues(TranslationStubIndex.KEY, domain, GlobalSearchScope.filesScope(project, Collections.singletonList(psiFile.getVirtualFile()))).stream()
.filter(string -> string.contains(translationKey)).map(string -> psiFile)
.collect(Collectors.toList())
);
}
return elements;
}
public void collect() {
List<VirtualFile> conceptFiles = FileManager.getConceptFiles(project);
List<VirtualFile> files = FileManager.getAllSpecFiles(project);
files.addAll(conceptFiles);
for (VirtualFile file : files) {
List<Set<Integer>> values = FileBasedIndex.getInstance().getValues(FileStub.NAME, file.getPath(), GlobalSearchScope.allScope(project));
PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
if (values.size() > 0) getSteps(psiFile, new HashSet<>(values.get(0)));
}
}
/**
* Create a search pattern for the given <code>className</code> class name.
*
* @param annotationName the class name to search.
* @return a search pattern for the given <code>className</code> class name.
*/
protected static Query<PsiModifierListOwner> createAnnotationTypeDeclarationSearchPattern(SearchContext context, String annotationName) {
JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(context.getModule().getProject());
PsiClass annotationClass = javaPsiFacade.findClass(annotationName, GlobalSearchScope.allScope(context.getModule().getProject()));
if (annotationClass != null) {
return new ArrayQuery<>(annotationClass);
} else {
return new EmptyQuery<>();
}
}
@NotNull
@Override
public List<Location> getLocation(@NotNull String protocol,
@NotNull String path,
@NotNull Project project,
@NotNull GlobalSearchScope scope) {
// see DartTestEventsConverterZ.addLocationHint()
// path is like /Users/x/projects/foo/test/foo_test.dart,35,12,["main tests","calculate_fail"]
final int commaIdx1 = path.indexOf(',');
final int commaIdx2 = path.indexOf(',', commaIdx1 + 1);
final int commaIdx3 = path.indexOf(',', commaIdx2 + 1);
if (commaIdx3 < 0) return NONE;
final String filePath = path.substring(0, commaIdx1);
final int line = Integer.parseInt(path.substring(commaIdx1 + 1, commaIdx2));
final int column = Integer.parseInt(path.substring(commaIdx2 + 1, commaIdx3));
final String names = path.substring(commaIdx3 + 1);
final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(filePath);
final PsiFile psiFile = file == null ? null : PsiManager.getInstance(project).findFile(file);
if (!(psiFile instanceof DartFile)) return NONE;
if (line >= 0 && column >= 0) {
final Location<PsiElement> location = getLocationByLineAndColumn(psiFile, line, column);
if (location != null) {
return Collections.singletonList(location);
}
}
final List<String> nodes = pathToNodes(names);
if (nodes.isEmpty()) {
return Collections.singletonList(new PsiLocation<PsiElement>(psiFile));
}
return getLocationByGroupAndTestNames(psiFile, nodes);
}
/**
* @deprecated use {@link #getElements(StubIndexKey, Object, Project, GlobalSearchScope, Class)}
*/
@Deprecated
public <Key, Psi extends PsiElement> Collection<Psi> get(@Nonnull StubIndexKey<Key, Psi> indexKey, @Nonnull Key key, @Nonnull Project project, @Nullable final GlobalSearchScope scope) {
List<Psi> result = new SmartList<>();
processElements(indexKey, key, project, scope, (Class<Psi>)PsiElement.class, Processors.cancelableCollectProcessor(result));
return result;
}
@Nonnull
@Override
public String[] getNames(Project project, boolean includeNonProjectItems)
{
CommonProcessors.CollectProcessor<String> processor = new CommonProcessors.CollectProcessor<String>(ContainerUtil.<String>newTroveSet());
processNames(processor, GlobalSearchScope.allScope(project), IdFilter.getProjectIdFilter(project, includeNonProjectItems));
return processor.toArray(ArrayUtil.STRING_ARRAY_FACTORY);
}
@Before
public void setUp() {
initMocks(this);
mockStatic(ID.class);
when(ID.create(any())).thenReturn(null);
mockStatic(EsyPackageJson.class);
mockStatic(FilenameIndex.class);
mockStatic(GlobalSearchScope.class);
when(GlobalSearchScope.allScope(mockProject)).thenReturn(mockScope);
}
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];
}
private static GlobalSearchScope evaluateScopesAndUnite(final Module[] modules, final ScopeForModuleEvaluator evaluator) {
GlobalSearchScope scope = evaluator.evaluate(modules[0]);
for (int i = 1; i < modules.length; i++) {
final Module module = modules[i];
final GlobalSearchScope otherscope = evaluator.evaluate(module);
scope = scope.uniteWith(otherscope);
}
return scope;
}
@Nonnull
private static GlobalSearchScope getScopeToShow(@Nonnull Project project, @Nullable Module module, boolean forLibraries) {
if (module == null) {
if (forLibraries) {
return new ProjectLibrariesSearchScope(project);
}
return GlobalSearchScope.projectScope(project);
}
else {
if (forLibraries) {
return new ModuleLibrariesSearchScope(module);
}
return GlobalSearchScope.moduleScope(module);
}
}
public <Psi extends PsiElement> boolean processStubsInFile(@Nonnull Project project,
@Nonnull VirtualFile file,
@Nonnull StubIdList value,
@Nonnull Processor<? super Psi> processor,
@Nullable GlobalSearchScope scope,
@Nonnull Class<Psi> requiredClass) {
PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
if (psiFile == null) {
LOG.error("Stub index points to a file without PSI: " + file.getFileType() + ", used scope " + scope);
onInternalError(file);
return true;
}
if (value.size() == 1 && value.get(0) == 0) {
//noinspection unchecked
return !checkType(requiredClass, psiFile, psiFile) || processor.process((Psi)psiFile);
}
List<StubbedSpine> spines = getAllSpines(psiFile);
if (spines.isEmpty()) {
return handleNonPsiStubs(file, processor, requiredClass, psiFile);
}
for (int i = 0, size = value.size(); i < size; i++) {
PsiElement psi = getStubPsi(spines, value.get(i));
if (!checkType(requiredClass, psiFile, psi)) break;
//noinspection unchecked
if (!processor.process((Psi)psi)) return false;
}
return true;
}
/**
* @param searchContext Search context.
* @return {@code GenericSideEffect} class given the search context. {@code null} if not found.
* @since 0.1
*/
@Nullable
public static PsiClass getGenericSideEffectClass( @NotNull PsiElement searchContext )
{
Project project = searchContext.getProject();
GlobalSearchScope searchScope = determineSearchScope( searchContext );
return getGenericSideEffectClass( project, searchScope );
}
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;
}