下面列出了怎么用com.intellij.psi.PsiFileSystemItem的API类实例代码及写法,或者点击链接到github查看源代码。
private Iterable<FoundItemDescriptor<PsiFileSystemItem>> matchQualifiers(MinusculeMatcher qualifierMatcher, Iterable<? extends PsiFileSystemItem> iterable) {
List<FoundItemDescriptor<PsiFileSystemItem>> matching = new ArrayList<>();
for (PsiFileSystemItem item : iterable) {
ProgressManager.checkCanceled();
String qualifier = Objects.requireNonNull(getParentPath(item));
FList<TextRange> fragments = qualifierMatcher.matchingFragments(qualifier);
if (fragments != null) {
int gapPenalty = fragments.isEmpty() ? 0 : qualifier.length() - fragments.get(fragments.size() - 1).getEndOffset();
int degree = qualifierMatcher.matchingDegree(qualifier, false, fragments) - gapPenalty;
matching.add(new FoundItemDescriptor<>(item, degree));
}
}
if (matching.size() > 1) {
Comparator<FoundItemDescriptor<PsiFileSystemItem>> comparator = Comparator.comparing((FoundItemDescriptor<PsiFileSystemItem> res) -> res.getWeight()).reversed();
Collections.sort(matching, comparator);
}
return matching;
}
@Nullable
private PsiFileSystemItem resolveFile(String path) {
if (path.startsWith("/") || path.contains(":")) {
return null;
}
BuildReferenceManager manager = BuildReferenceManager.getInstance(getProject());
path = StringUtil.trimStart(path, "-");
File file = manager.resolvePackage(WorkspacePath.createIfValid(path));
if (file == null) {
return null;
}
VirtualFile vf =
VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath());
if (vf == null) {
return null;
}
PsiManager psiManager = PsiManager.getInstance(getProject());
return vf.isDirectory() ? psiManager.findDirectory(vf) : psiManager.findFile(vf);
}
@Nonnull
@Override
public ListCellRenderer<Object> getElementsRenderer() {
//noinspection unchecked
return new SERenderer() {
@Nonnull
@Override
protected ItemMatchers getItemMatchers(@Nonnull JList list, @Nonnull Object value) {
ItemMatchers defaultMatchers = super.getItemMatchers(list, value);
if (!(value instanceof PsiFileSystemItem) || myModelForRenderer == null) {
return defaultMatchers;
}
return GotoFileModel.convertToFileItemMatchers(defaultMatchers, (PsiFileSystemItem)value, myModelForRenderer);
}
};
}
@Nullable
private static BuildFile resolveProjectWorkspaceFile(Project project) {
WorkspaceRoot projectRoot = WorkspaceRoot.fromProjectSafe(project);
if (projectRoot == null) {
return null;
}
for (String workspaceFileName :
Blaze.getBuildSystemProvider(project).possibleWorkspaceFileNames()) {
PsiFileSystemItem workspaceFile =
BuildReferenceManager.getInstance(project)
.resolveFile(projectRoot.fileForPath(new WorkspacePath(workspaceFileName)));
if (workspaceFile != null) {
return ObjectUtils.tryCast(workspaceFile, BuildFile.class);
}
}
return null;
}
@Nullable
@Override
public RunConfigurationContext getTestContext(ConfigurationContext context) {
PsiElement psi = context.getPsiLocation();
if (!(psi instanceof PsiFileSystemItem) || !(psi instanceof FakePsiElement)) {
return null;
}
VirtualFile vf = ((PsiFileSystemItem) psi).getVirtualFile();
if (vf == null) {
return null;
}
WorkspacePath path = getWorkspacePath(context.getProject(), vf);
if (path == null) {
return null;
}
return CachedValuesManager.getCachedValue(
psi,
() ->
CachedValueProvider.Result.create(
doFindTestContext(context, vf, psi, path),
PsiModificationTracker.MODIFICATION_COUNT,
BlazeSyncModificationTracker.getInstance(context.getProject())));
}
private boolean showCoverage(PsiFileSystemItem psiFile) {
if (coverageFilePaths.isEmpty()) {
return false;
}
VirtualFile vf = psiFile.getVirtualFile();
if (vf == null) {
return false;
}
String filePath = normalizeFilePath(vf.getPath());
for (String path : coverageFilePaths) {
if (filePath.startsWith(path)) {
return true;
}
}
return false;
}
@Nullable
private static PyBuiltinCache getBuiltInCache(PyQualifiedExpression element) {
final PsiElement realContext = PyPsiUtils.getRealContext(element);
PsiFileSystemItem psiFile = realContext.getContainingFile();
if (psiFile == null) {
return null;
}
Sdk sdk = PyBuiltinCache.findSdkForFile(psiFile);
if (sdk != null && sdk.getSdkType() instanceof PythonSdkType) {
// this case is already handled by PythonBuiltinReferenceResolveProvider
return null;
}
Sdk pythonSdk = PySdkUtils.getPythonSdk(psiFile.getProject());
return pythonSdk != null
? PythonSdkPathCache.getInstance(psiFile.getProject(), pythonSdk).getBuiltins()
: null;
}
private void doTest(@NotNull String beforeText, String... expectedResolve) {
myFixture.configureByText(GitFileType.INSTANCE, beforeText);
PsiPolyVariantReference reference = ((PsiPolyVariantReference) myFixture.getReferenceAtCaretPosition());
assertNotNull(reference);
final VirtualFile rootFile = myFixture.getFile().getContainingDirectory().getVirtualFile();
ResolveResult[] resolveResults = reference.multiResolve(true);
List<String> actualResolve = ContainerUtil.map(resolveResults, new Function<ResolveResult, String>() {
@Override
public String fun(ResolveResult resolveResult) {
PsiElement resolveResultElement = resolveResult.getElement();
assertNotNull(resolveResultElement);
assertInstanceOf(resolveResultElement, PsiFileSystemItem.class);
PsiFileSystemItem fileSystemItem = (PsiFileSystemItem) resolveResultElement;
return VfsUtilCore.getRelativePath(fileSystemItem.getVirtualFile(), rootFile, '/');
}
});
assertContainsElements(actualResolve, expectedResolve);
}
@Override
public void processIncludingFiles(PsiFile context, Processor<? super Pair<VirtualFile, FileIncludeInfo>> processor) {
context = context.getOriginalFile();
VirtualFile contextFile = context.getVirtualFile();
if (contextFile == null) return;
String originalName = context.getName();
Collection<String> names = getPossibleIncludeNames(context, originalName);
GlobalSearchScope scope = GlobalSearchScope.allScope(myProject);
for (String name : names) {
MultiMap<VirtualFile, FileIncludeInfoImpl> infoList = FileIncludeIndex.getIncludingFileCandidates(name, scope);
for (VirtualFile candidate : infoList.keySet()) {
PsiFile psiFile = myPsiManager.findFile(candidate);
if (psiFile == null || context.equals(psiFile)) continue;
for (FileIncludeInfo info : infoList.get(candidate)) {
PsiFileSystemItem item = resolveFileInclude(info, psiFile);
if (item != null && contextFile.equals(item.getVirtualFile())) {
if (!processor.process(Pair.create(candidate, info))) {
return;
}
}
}
}
}
}
private static boolean fileMatchesPathPrefix(@Nullable final PsiFileSystemItem file, @Nonnull final List<String> pathPrefix) {
if (file == null) return false;
final List<String> contextParts = new ArrayList<>();
PsiFileSystemItem parentFile = file;
PsiFileSystemItem parent;
while ((parent = parentFile.getParent()) != null) {
if (parent.getName().length() > 0) contextParts.add(0, parent.getName().toLowerCase());
parentFile = parent;
}
final String path = StringUtil.join(contextParts, "/");
int nextIndex = 0;
for (@NonNls final String s : pathPrefix) {
if ((nextIndex = path.indexOf(s.toLowerCase(), nextIndex)) == -1) return false;
}
return true;
}
@Nullable
public PackageDependenciesNode findNode(PsiFileSystemItem file, final PsiElement psiElement) {
if (file instanceof PsiDirectory) {
return getModuleDirNode(file.getVirtualFile(), myFileIndex.getModuleForFile(file.getVirtualFile()), null);
}
PackageDependenciesNode parent = getFileParentNode(file.getVirtualFile());
PackageDependenciesNode[] nodes = findNodeForPsiElement(parent, file);
if (nodes == null || nodes.length == 0) {
return null;
}
else {
for (PackageDependenciesNode node : nodes) {
if (node.getPsiElement() == psiElement) return node;
}
return nodes[0];
}
}
@Nullable
private PsiFileSystemItem doResolve(@Nonnull final FileIncludeInfo info, @Nonnull final PsiFile context) {
if (info instanceof FileIncludeInfoImpl) {
String id = ((FileIncludeInfoImpl)info).providerId;
FileIncludeProvider provider = id == null ? null : myProviderMap.get(id);
final PsiFileSystemItem resolvedByProvider = provider == null ? null : provider.resolveIncludedFile(info, context);
if (resolvedByProvider != null) {
return resolvedByProvider;
}
}
PsiFileImpl psiFile = (PsiFileImpl)myPsiFileFactory.createFileFromText("dummy.txt", PlainTextFileType.INSTANCE, info.path);
psiFile.setOriginalFile(context);
return new FileReferenceSet(psiFile) {
@Override
protected boolean useIncludingFileAsContext() {
return false;
}
}.resolve();
}
@Override
public void actionPerformed(AnActionEvent e) {
if (e.getData(LangDataKeys.IDE_VIEW) == null) {
final Project project = e.getData(CommonDataKeys.PROJECT);
final PsiFileSystemItem psiFile = e.getData(LangDataKeys.PSI_FILE).getParent();
ProjectView.getInstance(project).selectCB(psiFile, psiFile.getVirtualFile(), true).doWhenDone(new Runnable() {
@Override
public void run() {
showPopup(DataManager.getInstance().getDataContext());
}
});
}
else {
super.actionPerformed(e);
}
}
@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());
}
}
@Override
public Collection<VirtualFile> getRoots() {
Value value = getValue();
if (value instanceof RootsProvider) {
return ((RootsProvider)value).getRoots();
}
else if (value instanceof PsiFile) {
PsiFile vFile = ((PsiFile)value).getContainingFile();
if (vFile != null && vFile.getVirtualFile() != null) {
return Collections.singleton(vFile.getVirtualFile());
}
}
else if (value instanceof VirtualFile) {
return Collections.singleton(((VirtualFile)value));
}
else if (value instanceof PsiFileSystemItem) {
return Collections.singleton(((PsiFileSystemItem)value).getVirtualFile());
}
return Collections.emptyList();
}
@Nullable
public static String getRelativePath(PsiFileSystemItem src, PsiFileSystemItem dst) {
final PsiFileSystemItem commonAncestor = getCommonAncestor(src, dst);
if (commonAncestor != null) {
StringBuilder buffer = new StringBuilder();
if (!src.equals(commonAncestor)) {
while (!commonAncestor.equals(src.getParent())) {
buffer.append("..").append('/');
src = src.getParent();
assert src != null;
}
}
buffer.append(getRelativePathFromAncestor(dst, commonAncestor));
return buffer.toString();
}
return null;
}
private String getNewPathAndUpdateAffectedPath(final @NotNull PsiElement newElement) {
final String oldPath = fields.getFilePath();
final VirtualFile newFile = newElement instanceof PsiFileSystemItem ? ((PsiFileSystemItem)newElement).getVirtualFile() : null;
if (newFile != null && oldPath != null && oldPath.startsWith(myAffectedPath)) {
final String newPath = newFile.getPath() + oldPath.substring(myAffectedPath.length());
myAffectedPath = newFile.getPath(); // needed if refactoring will be undone
return newPath;
}
return oldPath;
}
private String getNewPathAndUpdateAffectedPath(final @NotNull PsiElement newElement) {
final String oldPath = fields.getFilePath();
final VirtualFile newFile = newElement instanceof PsiFileSystemItem ? ((PsiFileSystemItem)newElement).getVirtualFile() : null;
if (newFile != null && oldPath != null && oldPath.startsWith(myAffectedPath)) {
final String newPath = newFile.getPath() + oldPath.substring(myAffectedPath.length());
myAffectedPath = newFile.getPath(); // needed if refactoring will be undone
return newPath;
}
return oldPath;
}
@Override
public void performPaste(@Nonnull DataContext dataContext) {
final Project project = dataContext.getData(CommonDataKeys.PROJECT);
final IdeView ideView = dataContext.getData(LangDataKeys.IDE_VIEW);
if (project == null || ideView == null) return;
if (!FileCopyPasteUtil.isFileListFlavorAvailable()) return;
final Transferable contents = CopyPasteManager.getInstance().getContents();
if (contents == null) return;
final List<File> fileList = FileCopyPasteUtil.getFileList(contents);
if (fileList == null) return;
final List<PsiElement> elements = new ArrayList<PsiElement>();
for (File file : fileList) {
final VirtualFile vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
if (vFile != null) {
final PsiManager instance = PsiManager.getInstance(project);
PsiFileSystemItem item = vFile.isDirectory() ? instance.findDirectory(vFile) : instance.findFile(vFile);
if (item != null) {
elements.add(item);
}
}
}
if (elements.size() > 0) {
final PsiDirectory dir = ideView.getOrChooseDirectory();
if (dir != null) {
final boolean move = LinuxDragAndDropSupport.isMoveOperation(contents);
if (move) {
new MoveFilesOrDirectoriesHandler().doMove(PsiUtilCore.toPsiElementArray(elements), dir);
}
else {
new CopyFilesOrDirectoriesHandler().doCopy(PsiUtilCore.toPsiElementArray(elements), dir);
}
}
}
}
@Nullable
private PsiFileSystemItem getFileByAbsolutePath(@Nonnull String pattern) {
if (pattern.contains("/") || pattern.contains("\\")) {
String path = FileUtil.toSystemIndependentName(ChooseByNamePopup.getTransformedPattern(pattern, myModel));
VirtualFile vFile = LocalFileSystem.getInstance().findFileByPathIfCached(path);
if (vFile != null) {
ProjectFileIndex index = ProjectFileIndex.getInstance(myProject);
if (index.isInContent(vFile) || index.isInLibrary(vFile)) {
return PsiUtilCore.findFileSystemItem(myProject, vFile);
}
}
}
return null;
}
/**
* Checks if the element we're searching for is represented by a file or directory.<br>
* e.g. a java class PSI element, or an actual PsiFile element.
*/
@Nullable
public static PsiFileSystemItem asFileSystemItemSearch(PsiElement elementToSearch) {
if (elementToSearch instanceof PsiFileSystemItem) {
return (PsiFileSystemItem) elementToSearch;
}
return asFileSearch(elementToSearch);
}
@Nullable
@Override
public GlobalSearchScope getScopeToExclude(PsiElement element) {
if (!enabled.getValue()) {
return null;
}
if (element instanceof PsiFileSystemItem) {
return GlobalSearchScope.getScopeRestrictedByFileTypes(
new EverythingGlobalScope(), BuildFileType.INSTANCE);
}
return null;
}
private static PsiReference globReference(GlobExpression glob, PsiFileSystemItem file) {
return new PsiReferenceBase.Immediate<GlobExpression>(
glob, glob.getReferenceTextRange(), file) {
@Override
public PsiElement bindToElement(@NotNull PsiElement element)
throws IncorrectOperationException {
return glob;
}
};
}
@Nullable
public static BlazePackage getContainingPackage(PsiFileSystemItem file) {
if (file instanceof PsiFile) {
file = ((PsiFile) file).getOriginalFile();
}
if (file instanceof BuildFile
&& Blaze.getBuildSystemProvider(file.getProject()).isBuildFile(file.getName())) {
return new BlazePackage((BuildFile) file);
}
return getContainingPackage(getPsiDirectory(file));
}
@Nullable
private static PsiDirectory getPsiDirectory(PsiFileSystemItem file) {
if (file instanceof PsiDirectory) {
return (PsiDirectory) file;
}
if (file instanceof PsiFile) {
return ((PsiFile) file).getContainingDirectory();
}
if (file instanceof PackagePrefixFileSystemItem) {
return ((PackagePrefixFileSystemItem) file).getDirectory();
}
return null;
}
@Nullable
public PsiFileSystemItem resolveFile(File file) {
VirtualFile vf =
VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath());
if (vf == null) {
return null;
}
PsiManager manager = PsiManager.getInstance(project);
return vf.isDirectory() ? manager.findDirectory(vf) : manager.findFile(vf);
}
private static PsiElement getBlockEndingParent(PsiElement element) {
while (element != null && !(element instanceof PsiFileSystemItem)) {
if (endsBlock(element)) {
return element;
}
element = element.getParent();
}
return null;
}
@Override
public boolean canSelect(PsiFileSystemItem file) {
if (!super.canSelect(file)) return false;
final VirtualFile vFile = PsiUtilBase.getVirtualFile(file);
return canSelect(vFile);
}
@Override
protected void actionPerformedInBlazeProject(Project project, AnActionEvent event) {
IdeView view = event.getData(LangDataKeys.IDE_VIEW);
if (view == null) {
return;
}
PsiDirectory directory = DirectoryChooserUtil.getOrChooseDirectory(view);
if (directory == null) {
return;
}
CreateDirectoryOrPackageHandler validator =
new CreateDirectoryOrPackageHandler(project, directory, false, ".") {
@Override
protected void createDirectories(String subDirName) {
super.createDirectories(subDirName);
PsiFileSystemItem element = getCreatedElement();
if (element instanceof PsiDirectory) {
createBuildFile(project, (PsiDirectory) element);
}
}
};
Messages.showInputDialog(
project,
"Enter new package name:",
String.format("New %s Package", Blaze.buildSystemName(project)),
Messages.getQuestionIcon(),
"",
validator);
PsiDirectory newDir = (PsiDirectory) validator.getCreatedElement();
if (newDir != null) {
PsiFile buildFile = findBuildFile(project, newDir);
if (buildFile != null) {
view.selectElement(buildFile);
OpenFileAction.openFile(buildFile.getViewProvider().getVirtualFile(), project);
}
}
}
/**
* Initial checks for whether this action should be enabled. Returns the relevant action string,
* or null if the action shouldn't be shown.
*/
@Nullable
private static String actionDescription(Project project, @Nullable VirtualFile vf) {
if (vf == null) {
return null;
}
LocationContext context = AddSourceToProjectHelper.getContext(project, vf);
if (context == null) {
return null;
}
boolean addDirectories = !AddSourceToProjectHelper.sourceInProjectDirectories(context);
boolean addTargets =
!AddSourceToProjectHelper.sourceCoveredByProjectViewTargets(context)
&& !AddSourceToProjectHelper.autoDeriveTargets(project);
if (!addDirectories && !addTargets) {
// nothing to do
return null;
}
PsiFileSystemItem psiFile = findFileOrDirectory(PsiManager.getInstance(project), vf);
if (psiFile instanceof PsiDirectory) {
return addDirectories ? "Add directory to project" : null;
}
if (psiFile instanceof BuildFile
&& ((BuildFile) psiFile).getBlazeFileType() == BlazeFileType.BuildPackage) {
return AddSourceToProjectHelper.packageCoveredByProjectTargets(context)
? null
: "Add BUILD package to project";
}
if (!SourceToTargetProvider.hasProvider()) {
return null;
}
if (!addDirectories
&& (AddSourceToProjectHelper.sourceCoveredByProjectViewTargets(context)
|| SyncStatusContributor.getSyncStatus(project, context.file) != SyncStatus.UNSYNCED)) {
return null;
}
return "Add source file to project";
}