下面列出了com.intellij.psi.PsiManager#findDirectory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@NotNull
public Collection<PsiFileSystemItem> getRoots(@Nullable final Module module, ProtoPsiFileRoot psiFileRoot) {
if (module == null) {
return Collections.emptyList();
}
Set<PsiFileSystemItem> result = ContainerUtil.newLinkedHashSet();
PsiManager psiManager = PsiManager.getInstance(module.getProject());
for (SourceRootsProvider sourceRootsProvider : sourceRootsProviders) {
VirtualFile[] sourceRoots = sourceRootsProvider.getSourceRoots(module, psiFileRoot);
for (VirtualFile root : sourceRoots) {
if (root != null) {
final PsiDirectory directory = psiManager.findDirectory(root);
if (directory != null) {
result.add(directory);
}
}
}
}
return result;
}
private void setupResourceDirectoryCombo() {
Project project = myModule.getProject();
if (myContextFile != null) {
// Try to figure out res/ dir from context
// (e.g., while refactoring an xml file that's a child of a res/ directory).
// We currently take the parent and hide the combo box.
PsiManager manager = PsiManager.getInstance(project);
VirtualFile virtualDirectory =
BlazeCreateResourceUtils.getResDirFromDataContext(myContextFile);
PsiDirectory directory =
virtualDirectory != null ? manager.findDirectory(virtualDirectory) : null;
if (directory != null) {
myResDirectory = directory.getVirtualFile();
} else {
// As a last resort, if we have poor context,
// e.g., quick fix from within a .java file, set up the UI
// based on the deps of the .java file.
BlazeCreateResourceUtils.setupResDirectoryChoices(
project, myContextFile, myResDirLabel, myResDirCombo);
}
} else {
// As a last resort, if we have no context at all, set up some UI.
BlazeCreateResourceUtils.setupResDirectoryChoices(
project, null, myResDirLabel, myResDirCombo);
}
}
@Nullable
@Override
public PsiElement resolve() {
Optional<VirtualFile> virtualFile = findFile();
if (!virtualFile.isPresent()) {
return null;
}
VirtualFile buildFileOrDirectory = PantsUtil.findBUILDFiles(virtualFile.get())
.stream()
.findFirst()
.orElse(virtualFile.get());
final PsiManager psiManager = PsiManager.getInstance(getElement().getProject());
final PsiFile buildFile = psiManager.findFile(buildFileOrDirectory);
return buildFile != null ? buildFile : psiManager.findDirectory(buildFileOrDirectory);
}
static Collection<PsiFileSystemItem> getContextsForModule(@Nonnull Module module, @Nonnull String packageName, @Nullable GlobalSearchScope scope) {
List<PsiFileSystemItem> result = null;
Query<VirtualFile> query = DirectoryIndex.getInstance(module.getProject()).getDirectoriesByPackageName(packageName, false);
PsiManager manager = null;
for (VirtualFile file : query) {
if (scope != null && !scope.contains(file)) continue;
if (result == null) {
result = new ArrayList<>();
manager = PsiManager.getInstance(module.getProject());
}
PsiDirectory psiDirectory = manager.findDirectory(file);
if (psiDirectory != null) result.add(psiDirectory);
}
return result != null ? result : Collections.emptyList();
}
@Override
@Nonnull
@RequiredReadAction
public Collection<AbstractTreeNode> getChildren() {
Module module = getValue();
if (module == null || module.isDisposed()) {
return Collections.emptyList();
}
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
ModuleFileIndex moduleFileIndex = rootManager.getFileIndex();
final VirtualFile[] contentRoots = rootManager.getContentRoots();
final List<AbstractTreeNode> children = new ArrayList<>(contentRoots.length + 1);
final PsiManager psiManager = PsiManager.getInstance(module.getProject());
for (final VirtualFile contentRoot : contentRoots) {
if (!moduleFileIndex.isInContent(contentRoot)) continue;
if (contentRoot.isDirectory()) {
PsiDirectory directory = psiManager.findDirectory(contentRoot);
if(directory != null) {
children.add(new PsiDirectoryNode(getProject(), directory, getSettings()));
}
}
else {
PsiFile file = psiManager.findFile(contentRoot);
if(file != null) {
children.add(new PsiFileNode(getProject(), file, getSettings()));
}
}
}
return children;
}
@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);
}
@Nullable
private static PsiDirectory getWritableModuleDirectory(@Nonnull Query<VirtualFile> vFiles,
GlobalSearchScope scope,
PsiManager manager) {
for (VirtualFile vFile : vFiles) {
if (!scope.contains(vFile)) continue;
PsiDirectory directory = manager.findDirectory(vFile);
if (directory != null && directory.isValid() && directory.isWritable()) {
return directory;
}
}
return null;
}
@Nullable
private static PsiFileSystemItem resolveFile(Project project, @Nullable File file) {
if (file == null) {
return null;
}
PsiManager manager = PsiManager.getInstance(project);
VirtualFile vf =
VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath());
if (vf == null) {
return null;
}
return vf.isDirectory() ? manager.findDirectory(vf) : manager.findFile(vf);
}
@Nullable
public static PsiFileSystemItem resolveFile(PsiManager manager, File file) {
VirtualFile vf =
VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath());
if (vf != null) {
return vf.isDirectory() ? manager.findDirectory(vf) : manager.findFile(vf);
}
vf = VirtualFileSystemProvider.getInstance().getSystem().findFileByPath(file.getPath() + ".py");
return vf != null ? manager.findFile(vf) : null;
}
private PsiElement findPsi(@Nonnull VirtualFile vFile) {
if (!vFile.isValid()) {
return null;
}
PsiManager psiManager = PsiManager.getInstance(myProject);
return vFile.isDirectory() ? psiManager.findDirectory(vFile) : psiManager.findFile(vFile);
}
@Override
public void actionPerformed(AnActionEvent e) {
Project project = getEventProject(e);
VirtualFile file = e.getDataContext().getData(CommonDataKeys.VIRTUAL_FILE);
if (project != null && file != null && file.is(VFileProperty.SYMLINK)) {
VirtualFile target = file.getCanonicalFile();
if (target != null) {
PsiManager psiManager = PsiManager.getInstance(project);
PsiFileSystemItem psiFile = target.isDirectory() ? psiManager.findDirectory(target) : psiManager.findFile(target);
if (psiFile != null) {
ProjectView.getInstance(project).select(psiFile, target, false);
}
}
}
}
@Nonnull
public static Collection<AbstractTreeNode> createPackageViewChildrenOnFiles(@Nonnull List<VirtualFile> sourceRoots,
@Nonnull Project project,
@Nonnull ViewSettings settings,
@Nullable Module module,
final boolean inLibrary) {
final PsiManager psiManager = PsiManager.getInstance(project);
final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>();
final Set<PsiPackage> topLevelPackages = new HashSet<PsiPackage>();
for (final VirtualFile root : sourceRoots) {
final PsiDirectory directory = psiManager.findDirectory(root);
if (directory == null) {
continue;
}
final PsiPackage directoryPackage = PsiPackageManager.getInstance(project).findAnyPackage(directory);
if (directoryPackage == null || isPackageDefault(directoryPackage)) {
// add subpackages
final PsiDirectory[] subdirectories = directory.getSubdirectories();
for (PsiDirectory subdirectory : subdirectories) {
final PsiPackage aPackage = PsiPackageManager.getInstance(project).findAnyPackage(subdirectory);
if (aPackage != null && !isPackageDefault(aPackage)) {
topLevelPackages.add(aPackage);
}
}
// add non-dir items
children.addAll(BaseProjectViewDirectoryHelper.getDirectoryChildren(directory, settings, false));
}
else {
topLevelPackages.add(directoryPackage);
}
}
for (final PsiPackage topLevelPackage : topLevelPackages) {
addPackageAsChild(children, topLevelPackage, module, settings, inLibrary);
}
return children;
}
private static VirtualFile[] getCompilableFiles(Project project, VirtualFile[] files) {
if (files == null || files.length == 0) {
return VirtualFile.EMPTY_ARRAY;
}
final PsiManager psiManager = PsiManager.getInstance(project);
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
final CompilerManager compilerManager = CompilerManager.getInstance(project);
final List<VirtualFile> filesToCompile = new ArrayList<VirtualFile>();
for (final VirtualFile file : files) {
if (!fileIndex.isInSourceContent(file)) {
continue;
}
if (!file.isInLocalFileSystem()) {
continue;
}
if (file.isDirectory()) {
final PsiDirectory directory = psiManager.findDirectory(file);
if (directory == null || PsiPackageManager.getInstance(project).findAnyPackage(directory) == null) {
continue;
}
}
else {
FileType fileType = file.getFileType();
if (!(compilerManager.isCompilableFileType(fileType) || isCompilableResourceFile(project, file))) {
continue;
}
}
filesToCompile.add(file);
}
return VfsUtil.toVirtualFileArray(filesToCompile);
}
/**
* a directory is considered "empty" if it has at least one child and all its children are only directories
*
* @param strictlyEmpty if true, the package is considered empty if it has only 1 child and this child is a directory
* otherwise the package is considered as empty if all direct children that it has are directories
*/
public static boolean isEmptyMiddlePackage(@Nonnull PsiDirectory dir,
@Nullable Class<? extends ModuleExtension> moduleExtensionClass,
boolean strictlyEmpty) {
final VirtualFile[] files = dir.getVirtualFile().getChildren();
if (files.length == 0) {
return false;
}
PsiManager manager = dir.getManager();
int subpackagesCount = 0;
int directoriesCount = 0;
for (VirtualFile file : files) {
if (FileTypeManager.getInstance().isFileIgnored(file)) continue;
if (!file.isDirectory()) return false;
PsiDirectory childDir = manager.findDirectory(file);
if (childDir != null) {
directoriesCount++;
if (strictlyEmpty && directoriesCount > 1) return false;
final PsiPackageManager psiPackageManager = PsiPackageManager.getInstance(dir.getProject());
PsiPackage tempPackage = moduleExtensionClass == null
? psiPackageManager.findAnyPackage(childDir)
: psiPackageManager.findPackage(dir, moduleExtensionClass);
if (tempPackage != null) {
subpackagesCount++;
}
}
}
if (strictlyEmpty) {
return directoriesCount == subpackagesCount && directoriesCount == 1;
}
return directoriesCount == subpackagesCount && directoriesCount > 0;
}
public static boolean processFilesByName(@Nonnull final String name,
boolean directories,
boolean caseSensitively,
@Nonnull Processor<? super PsiFileSystemItem> processor,
@Nonnull final GlobalSearchScope scope,
@Nonnull final Project project,
@Nullable IdFilter idFilter) {
final Collection<VirtualFile> files;
if (caseSensitively) {
files = getService().getVirtualFilesByName(project, name, scope, idFilter);
}
else {
files = getVirtualFilesByNameIgnoringCase(name, scope, project, idFilter);
}
if (files.isEmpty()) return false;
PsiManager psiManager = PsiManager.getInstance(project);
int processedFiles = 0;
for (VirtualFile file : files) {
if (!file.isValid()) continue;
if (!directories && !file.isDirectory()) {
PsiFile psiFile = psiManager.findFile(file);
if (psiFile != null) {
if (!processor.process(psiFile)) return true;
++processedFiles;
}
}
else if (directories && file.isDirectory()) {
PsiDirectory dir = psiManager.findDirectory(file);
if (dir != null) {
if (!processor.process(dir)) return true;
++processedFiles;
}
}
}
return processedFiles > 0;
}
public static void setupRenderer(SimpleColoredComponent renderer, Project project, Bookmark bookmark, boolean selected) {
VirtualFile file = bookmark.getFile();
if (!file.isValid()) {
return;
}
PsiManager psiManager = PsiManager.getInstance(project);
PsiElement fileOrDir = file.isDirectory() ? psiManager.findDirectory(file) : psiManager.findFile(file);
if (fileOrDir != null) {
renderer.setIcon(IconDescriptorUpdaters.getIcon(fileOrDir, 0));
}
String description = bookmark.getDescription();
if (description != null) {
renderer.append(description + " ", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
}
FileStatus fileStatus = FileStatusManager.getInstance(project).getStatus(file);
TextAttributes attributes = new TextAttributes(fileStatus.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN);
renderer.append(file.getName(), SimpleTextAttributes.fromTextAttributes(attributes));
if (bookmark.getLine() >= 0) {
renderer.append(":", SimpleTextAttributes.GRAYED_ATTRIBUTES);
renderer.append(String.valueOf(bookmark.getLine() + 1), SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
if (!selected) {
FileColorManager colorManager = FileColorManager.getInstance(project);
if (fileOrDir instanceof PsiFile) {
Color color = colorManager.getRendererBackground((PsiFile)fileOrDir);
if (color != null) {
renderer.setBackground(color);
}
}
}
}
private static void addPackagesToChildren0(Project project, ArrayList<AbstractTreeNode> children, Module module, TodoTreeBuilder builder) {
final List<VirtualFile> roots = new ArrayList<VirtualFile>();
final List<VirtualFile> sourceRoots = new ArrayList<VirtualFile>();
final PsiManager psiManager = PsiManager.getInstance(project);
if (module == null) {
final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project);
ContainerUtil.addAll(roots, projectRootManager.getContentRoots());
ContainerUtil.addAll(sourceRoots, projectRootManager.getContentSourceRoots());
}
else {
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
ContainerUtil.addAll(roots, moduleRootManager.getContentRoots());
ContainerUtil.addAll(sourceRoots, moduleRootManager.getContentFolderFiles(ContentFolderScopes.productionAndTest()));
}
roots.removeAll(sourceRoots);
for (VirtualFile dir : roots) {
final PsiDirectory directory = psiManager.findDirectory(dir);
if (directory == null) {
continue;
}
final Iterator<PsiFile> files = builder.getFiles(directory);
if (!files.hasNext()) continue;
TodoDirNode dirNode = new TodoDirNode(project, directory, builder);
if (!children.contains(dirNode)) {
children.add(dirNode);
}
}
}
/**
* 写入文件
*
* @param saveFile 需要保存的文件对象
*/
public void write(SaveFile saveFile) {
// 校验目录是否存在
PsiManager psiManager = PsiManager.getInstance(saveFile.getProject());
PsiDirectory psiDirectory;
VirtualFile directory = LocalFileSystem.getInstance().findFileByPath(saveFile.getPath());
if (directory == null) {
// 尝试创建目录
if (saveFile.isOperateTitle() && !MessageDialogBuilder.yesNo(MsgValue.TITLE_INFO, "Directory " + saveFile.getPath() + " Not Found, Confirm Create?").isYes()) {
return;
}
psiDirectory = WriteCommandAction.runWriteCommandAction(saveFile.getProject(), (Computable<PsiDirectory>) () -> {
try {
VirtualFile dir = VfsUtil.createDirectoryIfMissing(saveFile.getPath());
LOG.assertTrue(dir != null);
// 重载文件,防止发生IndexNotReadyException异常
FileDocumentManager.getInstance().reloadFiles(dir);
return psiManager.findDirectory(dir);
} catch (IOException e) {
LOG.error("path " + saveFile.getPath() + " error");
ExceptionUtil.rethrow(e);
return null;
}
});
} else {
psiDirectory = psiManager.findDirectory(directory);
}
if (psiDirectory == null) {
return;
}
// 保存或替换文件
PsiFile oldFile = psiDirectory.findFile(saveFile.getFile().getName());
PsiDocumentManager psiDocumentManager = PsiDocumentManager.getInstance(saveFile.getProject());
FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
if (saveFile.isOperateTitle() && oldFile != null) {
MessageDialogBuilder.YesNoCancel yesNoCancel = MessageDialogBuilder.yesNoCancel(MsgValue.TITLE_INFO, "File " + saveFile.getFile().getName() + " Exists, Select Operate Mode?");
yesNoCancel.yesText("Cover");
yesNoCancel.noText("Compare");
yesNoCancel.cancelText("Cancel");
int result = yesNoCancel.show();
switch (result) {
case Messages.YES:
break;
case Messages.NO:
// 对比代码时也格式化代码
if (saveFile.isReformat()) {
// 保留旧文件内容,用新文件覆盖旧文件执行格式化,然后再还原旧文件内容
String oldText = oldFile.getText();
WriteCommandAction.runWriteCommandAction(saveFile.getProject(), () -> psiDocumentManager.getDocument(oldFile).setText(saveFile.getFile().getText()));
// 提交所有改动,并非VCS中的提交文件
PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
reformatFile(saveFile.getProject(), Collections.singletonList(oldFile));
// 提交所有改动,并非VCS中的提交文件
PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
String newText = oldFile.getText();
WriteCommandAction.runWriteCommandAction(saveFile.getProject(), () -> psiDocumentManager.getDocument(oldFile).setText(oldText));
// 提交所有改动,并非VCS中的提交文件
PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
saveFile.setVirtualFile(new LightVirtualFile(saveFile.getFile().getName(), saveFile.getFile().getFileType(), newText));
}
CompareFileUtils.showCompareWindow(saveFile.getProject(), fileDocumentManager.getFile(psiDocumentManager.getDocument(oldFile)), saveFile.getVirtualFile());
return;
case Messages.CANCEL:
default:
return;
}
}
PsiDirectory finalPsiDirectory = psiDirectory;
PsiFile finalFile = WriteCommandAction.runWriteCommandAction(saveFile.getProject(), (Computable<PsiFile>) () -> {
if (oldFile == null) {
// 提交所有改动,并非VCS中的提交文件
PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
return (PsiFile) finalPsiDirectory.add(saveFile.getFile());
} else {
// 对旧文件进行替换操作
Document document = psiDocumentManager.getDocument(oldFile);
LOG.assertTrue(document != null);
document.setText(saveFile.getFile().getText());
return oldFile;
}
});
// 判断是否需要进行代码格式化操作
if (saveFile.isReformat()) {
reformatFile(saveFile.getProject(), Collections.singletonList(finalFile));
}
// 提交所有改动,并非VCS中的提交文件
PsiDocumentManager.getInstance(saveFile.getProject()).commitAllDocuments();
}
/**
* Creates the directory with the given path via PSI, including any
* necessary but nonexistent parent directories. Must be run in write action.
* @param path directory path in the local file system; separators must be '/'
* @return true if path exists or has been created as the result of this method call; false otherwise
*/
public static PsiDirectory mkdirs(PsiManager manager, String path) throws IncorrectOperationException{
if (File.separatorChar != '/') {
if (path.indexOf(File.separatorChar) != -1) {
throw new IllegalArgumentException("separators must be '/'; path is " + path);
}
}
String existingPath = path;
PsiDirectory directory = null;
// find longest existing path
while (existingPath.length() > 0) {
VirtualFile file = LocalFileSystem.getInstance().findFileByPath(existingPath);
if (file != null) {
directory = manager.findDirectory(file);
if (directory == null) {
return null;
}
break;
}
if (StringUtil.endsWithChar(existingPath, '/')) {
existingPath = existingPath.substring(0, existingPath.length() - 1);
if (SystemInfo.isWindows && existingPath.length() == 2 && existingPath.charAt(1) == ':') {
return null;
}
}
int index = existingPath.lastIndexOf('/');
if (index == -1) {
// nothing to do more
return null;
}
existingPath = existingPath.substring(0, index);
}
if (directory == null) {
return null;
}
if (existingPath.equals(path)) {
return directory;
}
String postfix = path.substring(existingPath.length() + 1, path.length());
StringTokenizer tokenizer = new StringTokenizer(postfix, "/");
while (tokenizer.hasMoreTokens()) {
String name = tokenizer.nextToken();
PsiDirectory subdirectory = directory.createSubdirectory(name);
if (subdirectory == null) {
return null;
}
directory = subdirectory;
}
return directory;
}
@Nonnull
@Override
public Collection<? extends AbstractTreeNode> getChildren() {
final ArrayList<AbstractTreeNode> result = new ArrayList<AbstractTreeNode>();
final PsiManager psiManager = PsiManager.getInstance(getProject());
for (final Module m : ModuleManager.getInstance(myProject).getModules()) {
final VirtualFile knowledgeFolder = IdeaUtils.findKnowledgeFolderForModule(m, false);
if (knowledgeFolder != null) {
final String moduleName = m.getName();
final PsiDirectory dir = psiManager.findDirectory(knowledgeFolder);
final PsiDirectoryNode node = new PsiDirectoryNode(myProject, dir, getSettings()) {
protected Icon patchIcon(final Icon original, final VirtualFile file) {
return AllIcons.File.FOLDER;
}
@Override
public String getTitle() {
return moduleName;
}
@Override
public String toString() {
return moduleName;
}
@Override
public boolean isFQNameShown() {
return false;
}
@Override
public VirtualFile getVirtualFile() {
return knowledgeFolder;
}
@Nullable
@Override
protected String calcTooltip() {
return "The Knowledge folder for " + m.getName();
}
@Override
protected boolean shouldShowModuleName() {
return false;
}
};
result.add(node);
}
}
return result;
}