Java Code Examples for com.intellij.psi.PsiDirectory#getParentDirectory()

The following examples show how to use com.intellij.psi.PsiDirectory#getParentDirectory() . 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: AbstractFileProvider.java    From CodeGen with MIT License 6 votes vote down vote up
/**
 * 根据选择的package目录,找到resources目录
 * @param psiDirectory
 * @return
 */
private PsiDirectory findResourcesDirectory(PsiDirectory psiDirectory) {

    PsiDirectory parentDirectory = psiDirectory.getParentDirectory();
    PsiDirectory iterator = psiDirectory.getParentDirectory();

    while (iterator != null && !iterator.getName().equals("main")) {
        iterator = iterator.getParentDirectory();
    }

    PsiDirectory resourcesDirectory = iterator == null ? null : iterator.findSubdirectory("resources");
    if (resourcesDirectory == null) {
        resourcesDirectory = parentDirectory.findSubdirectory("resources");
        if (resourcesDirectory == null) {
            resourcesDirectory = parentDirectory.createSubdirectory("resources");
        }
    }
    return resourcesDirectory;
}
 
Example 2
Source File: BlazeResourcesDomFileDescription.java    From intellij with Apache License 2.0 6 votes vote down vote up
/** Only check that the file is under res/values or res/values-*. */
private static boolean isBlazeResourcesFile(PsiFile file) {
  if (!Blaze.isBlazeProject(file.getProject())) {
    return false;
  }
  file = file.getOriginalFile();
  PsiDirectory parent = file.getContainingDirectory();
  if (parent == null) {
    return false;
  }
  String parentName = parent.getName();
  if (!parentName.equals(FD_RES_VALUES) && !parentName.startsWith(FD_RES_VALUES + '-')) {
    return false;
  }
  PsiDirectory grandParent = parent.getParentDirectory();
  return grandParent != null && grandParent.getName().equals(FD_RES);
}
 
Example 3
Source File: BlazePackage.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
public static BlazePackage getContainingPackage(@Nullable PsiDirectory dir) {
  while (dir != null) {
    VirtualFile buildFile =
        Blaze.getBuildSystemProvider(dir.getProject())
            .findBuildFileInDirectory(dir.getVirtualFile());
    if (buildFile != null) {
      PsiFile psiFile = dir.getManager().findFile(buildFile);
      if (psiFile != null) {
        return psiFile instanceof BuildFile ? new BlazePackage((BuildFile) psiFile) : null;
      }
    }
    dir = dir.getParentDirectory();
  }
  return null;
}
 
Example 4
Source File: RefDirectoryImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void initialize() {
  PsiDirectory psiElement = ObjectUtils.tryCast(getPsiElement(), PsiDirectory.class);
  LOG.assertTrue(psiElement != null);
  final PsiDirectory parentDirectory = psiElement.getParentDirectory();
  if (parentDirectory != null && ProjectFileIndex.getInstance(psiElement.getProject()).isInSourceContent(parentDirectory.getVirtualFile())) {
    final WritableRefElement refElement = (WritableRefElement)getRefManager().getReference(parentDirectory);
    if (refElement != null) {
      refElement.add(this);
      return;
    }
  }
  myRefModule = getRefManager().getRefModule(ModuleUtilCore.findModuleForPsiElement(psiElement));
  if (myRefModule != null) {
    ((WritableRefEntity)myRefModule).add(this);
    return;
  }
  ((WritableRefEntity)myManager.getRefProject()).add(this);
}
 
Example 5
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 6
Source File: NeosUtil.java    From intellij-neos with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Collect all parent directories until a directory named "Fusion" is found.
 * If none is found, return an empty array.
 */
public static ArrayList<PsiDirectory> getParentFusionDirectories(PsiDirectory currentDirectory) {
    if (currentDirectory == null) {
        return null;
    }

    PsiFile composerManifest = ComposerUtil.getComposerManifest(currentDirectory);
    PsiDirectory packageDirectory = null;
    if (composerManifest != null) {
        packageDirectory = composerManifest.getContainingDirectory();
    }

    ArrayList<PsiDirectory> parentDirectories = new ArrayList<>();
    boolean fusionDirectoryExists = false;

    do {
        parentDirectories.add(currentDirectory);
        currentDirectory = currentDirectory.getParentDirectory();

        if (currentDirectory != null && currentDirectory.getName().equals("Fusion")) {
            fusionDirectoryExists = true;
        }
    } while (currentDirectory != null
            && !currentDirectory.getName().equals("Fusion")
            && !currentDirectory.equals(packageDirectory)
            && !currentDirectory.equals(guessProjectDir(currentDirectory.getProject())));

    if (!fusionDirectoryExists) {
        return new ArrayList<>();
    }

    return parentDirectories;
}
 
Example 7
Source File: ComposerUtil.java    From intellij-neos with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
public static JsonFile getComposerManifest(PsiDirectory currentDirectory) {
    if (currentDirectory == null) {
        return null;
    }

    JsonFile composerFile;
    do {
        composerFile = getComposerManifestInDirectory(currentDirectory);
        currentDirectory = currentDirectory.getParentDirectory();
    } while (composerFile == null && currentDirectory != null && !currentDirectory.equals(guessProjectDir(currentDirectory.getProject())));

    return composerFile;
}
 
Example 8
Source File: EntityBase.java    From CleanArchitecturePlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Method that return the complete package name for a component in clean architecture
 *
 * @param directory directory to find the parents
 * @return example: com.digio.project.entityName.view.activity
 */
public static String getPackageNameProject(PsiDirectory directory) {
    PsiDirectory directoryIterator = directory;
    String packageName = directory.getName();

    while (!directoryIterator.getName().equals("com")) {
        directoryIterator = directoryIterator.getParentDirectory();
        packageName = directoryIterator.getName() + "." + packageName;
    }

    return packageName;

}
 
Example 9
Source File: EntityBase.java    From CleanArchitecturePlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Get res package in project
 *
 * @return res package
 */
public static VirtualFile getResPackage() {
    PsiDirectory iterator = projectDirectory;

    // Search main directory in project
    while (!iterator.getName().equals("main")) {
        iterator = iterator.getParentDirectory();
    }

    VirtualFile main = iterator.getVirtualFile();

    // Search res directory in main directory
    return main.findChild("res");
}
 
Example 10
Source File: BashPsiFileUtils.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
/**
 * Takes an existing psi file and tries to find another file relative to the first.
 * The file path is given as a relative path.
 *
 * @param start        The existing psi file
 * @param relativePath The relative path as a string
 * @return The psi file or null if nothing has been found
 */
@Nullable
public static PsiFile findRelativeFile(PsiFile start, String relativePath) {
    PsiDirectory startDirectory = BashPsiUtils.findFileContext(start).getContainingDirectory();
    if (startDirectory == null || StringUtil.isEmptyOrSpaces(relativePath)) {
        return null;
    }

    //fixme handle escaped / chars!
    PsiDirectory currentDir = startDirectory;

    List<String> parts = StringUtil.split(relativePath, "/");
    String filePart = parts.size() > 0 ? parts.get(parts.size() - 1) : "";

    for (int i = 0, partsLength = parts.size() - 1; (i < partsLength) && (currentDir != null); i++) {
        String part = parts.get(i);

        if (".".equals(part)) {
            //ignore this
        } else if ("..".equals(part)) {
            currentDir = currentDir.getParentDirectory();
        } else {
            currentDir = currentDir.findSubdirectory(part);
        }
    }

    if (currentDir != null) {
        return currentDir.findFile(filePart);
    }

    return null;
}
 
Example 11
Source File: CreateFileAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
public MkDirs(@Nonnull String newName, @Nonnull PsiDirectory directory) {
  if (SystemInfo.isWindows) {
    newName = newName.replace('\\', '/');
  }
  if (newName.contains("/")) {
    final List<String> subDirs = StringUtil.split(newName, "/");
    newName = subDirs.remove(subDirs.size() - 1);
    boolean firstToken = true;
    for (String dir : subDirs) {
      if (firstToken && "~".equals(dir)) {
        final VirtualFile userHomeDir = VfsUtil.getUserHomeDir();
        if (userHomeDir == null) throw new IncorrectOperationException("User home directory not found");
        final PsiDirectory directory1 = directory.getManager().findDirectory(userHomeDir);
        if (directory1 == null) throw new IncorrectOperationException("User home directory not found");
        directory = directory1;
      }
      else if ("..".equals(dir)) {
        final PsiDirectory parentDirectory = directory.getParentDirectory();
        if (parentDirectory == null) throw new IncorrectOperationException("Not a valid directory");
        directory = parentDirectory;
      }
      else if (!".".equals(dir)) {
        directory = findOrCreateSubdirectory(directory, dir);
      }
      firstToken = false;
    }
  }

  this.newName = newName;
  this.directory = directory;
}
 
Example 12
Source File: ProjectViewPane.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean addSubtreeToUpdateByElement(@Nonnull Object element) {
  if (element instanceof PsiDirectory && !myProject.isDisposed()) {
    final PsiDirectory dir = (PsiDirectory)element;
    final ProjectTreeStructure treeStructure = (ProjectTreeStructure)myTreeStructure;
    PsiDirectory dirToUpdateFrom = dir;

    // optimization
    // isEmptyMiddleDirectory can be slow when project VFS is not fully loaded (initial dumb mode).
    // It's easiest to disable the optimization in any dumb mode
    if (!treeStructure.isFlattenPackages() && treeStructure.isHideEmptyMiddlePackages() && !DumbService.isDumb(myProject)) {
      while (dirToUpdateFrom != null && BaseProjectViewDirectoryHelper.isEmptyMiddleDirectory(dirToUpdateFrom, true)) {
        dirToUpdateFrom = dirToUpdateFrom.getParentDirectory();
      }
    }
    boolean addedOk;
    while (!(addedOk = super.addSubtreeToUpdateByElement(dirToUpdateFrom == null ? myTreeStructure.getRootElement() : dirToUpdateFrom))) {
      if (dirToUpdateFrom == null) {
        break;
      }
      dirToUpdateFrom = dirToUpdateFrom.getParentDirectory();
    }
    return addedOk;
  }

  return super.addSubtreeToUpdateByElement(element);
}
 
Example 13
Source File: DirectoryChooser.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean isParent(PsiDirectory directory, PsiDirectory parentCandidate) {
  while (directory != null) {
    if (directory.equals(parentCandidate)) return true;
    directory = directory.getParentDirectory();
  }
  return false;
}
 
Example 14
Source File: DoctrineOrmRepositoryIntention.java    From idea-php-annotation-plugin with MIT License 4 votes vote down vote up
@Override
public void invoke(@NotNull Project project, Editor editor, @NotNull PsiElement element) throws IncorrectOperationException {

    PhpClass phpClass = getScopedPhpClass(element);
    if(phpClass == null) {
        return;
    }

    String fileName = phpClass.getName() + "Repository.php";
    String namespace = DoctrineUtil.trimBlackSlashes(phpClass.getNamespaceName());
    PsiDirectory dir = phpClass.getContainingFile().getContainingDirectory();

    PsiDirectory repositoryDir = dir;
    if (dir.getParentDirectory() != null) {
        PsiDirectory checkDir = dir.getParentDirectory().findSubdirectory("Repository");

        if (dir.findFile(fileName) == null && checkDir != null) {
            repositoryDir = checkDir;
        }
    }

    String repoClass = phpClass.getPresentableFQN() + "Repository";
    PhpClass repoPhpClass = PhpElementsUtil.getClass(project, repoClass);

    if (repoPhpClass == null && dir != repositoryDir) {
        // Entity/../Repository/
        namespace = phpClass.getNamespaceName();
        namespace = namespace.substring(0, namespace.lastIndexOf("\\"));
        namespace = namespace.substring(0, namespace.lastIndexOf("\\"));
        namespace = namespace + "\\Repository";
        namespace = DoctrineUtil.trimBlackSlashes(namespace);

        repoClass = namespace + "\\" + phpClass.getName() + "Repository";
        repoClass = PhpLangUtil.toPresentableFQN(repoClass);

        repoPhpClass = PhpElementsUtil.getClass(project, repoClass);
    }

    if(repoPhpClass == null) {
        if(repositoryDir.findFile(fileName) == null) {
            final FileTemplate fileTemplate = FileTemplateManager.getInstance(project).getTemplate("Doctrine Entity Repository");
            final Properties defaultProperties = FileTemplateManager.getInstance(project).getDefaultProperties();

            Properties properties = new Properties(defaultProperties);

            properties.setProperty("NAMESPACE", namespace);
            properties.setProperty("NAME", phpClass.getName() + "Repository");

            properties.setProperty("ENTITY_NAMESPACE", DoctrineUtil.trimBlackSlashes(phpClass.getNamespaceName()));
            properties.setProperty("ENTITY_NAME", phpClass.getName());

            try {
                PsiElement newElement = FileTemplateUtil.createFromTemplate(fileTemplate, fileName, properties, repositoryDir);

                new OpenFileDescriptor(project, newElement.getContainingFile().getVirtualFile(), 0).navigate(true);
            } catch (Exception e) {
                return;
            }
        } else {
            if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
                HintManager.getInstance().showErrorHint(editor, "Repository already exists ");
            }
        }
    }

    PhpDocTagAnnotation ormEntityPhpDocBlock = DoctrineUtil.getOrmEntityPhpDocBlock(phpClass);
    if(ormEntityPhpDocBlock != null) {
        PhpDocTag phpDocTag = ormEntityPhpDocBlock.getPhpDocTag();
        PhpPsiElement firstPsiChild = phpDocTag.getFirstPsiChild();
        insertAttribute(editor, repoClass, phpDocTag, firstPsiChild);
    }

}