Exemple #1
0
  @Nullable
  private PsiDirectory chooseDirectory(final Project project, final PsiFile file) {
    PsiDirectory preferredDirectory =
        myWritableDirectoryList.isEmpty() ? null : myWritableDirectoryList.get(0);
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final VirtualFile virtualFile = file.getVirtualFile();
    assert virtualFile != null;
    final Module moduleForFile = fileIndex.getModuleForFile(virtualFile);
    if (myWritableDirectoryList.size() > 1
        && !ApplicationManager.getApplication().isUnitTestMode()) {
      if (moduleForFile != null) {
        for (PsiDirectory directory : myWritableDirectoryList) {
          if (fileIndex.getModuleForFile(directory.getVirtualFile()) == moduleForFile) {
            preferredDirectory = directory;
            break;
          }
        }
      }

      return DirectoryChooserUtil.chooseDirectory(
          myWritableDirectoryList.toArray(new PsiDirectory[myWritableDirectoryList.size()]),
          preferredDirectory,
          project,
          new HashMap<PsiDirectory, String>());
    }
    return preferredDirectory;
  }
  @NotNull
  private static List<RatedResolveResult> resolveInDirectory(
      @NotNull final String referencedName,
      @Nullable final PsiFile containingFile,
      final PsiDirectory dir,
      boolean isFileOnly,
      boolean checkForPackage) {
    final PsiDirectory subdir = dir.findSubdirectory(referencedName);
    if (subdir != null && (!checkForPackage || PyUtil.isPackage(subdir, containingFile))) {
      return ResolveResultList.to(subdir);
    }

    final PsiFile module = findPyFileInDir(dir, referencedName);
    if (module != null) {
      return ResolveResultList.to(module);
    }

    if (!isFileOnly) {
      // not a subdir, not a file; could be a name in parent/__init__.py
      final PsiFile initPy = dir.findFile(PyNames.INIT_DOT_PY);
      if (initPy == containingFile) {
        return Collections.emptyList(); // don't dive into the file we're in
      }
      if (initPy instanceof PyFile) {
        return ((PyFile) initPy).multiResolveName(referencedName);
      }
    }
    return Collections.emptyList();
  }
  @Nullable
  private static PsiDirectory getCommonParentDirectory(PsiElement[] elements) {
    PsiDirectory result = null;

    for (PsiElement element : elements) {
      PsiDirectory directory;

      if (element instanceof PsiDirectory) {
        directory = (PsiDirectory) element;
        directory = directory.getParentDirectory();
      } else if (element instanceof PsiFile) {
        directory = PlatformPackageUtil.getDirectory(element);
      } else {
        throw new IllegalArgumentException("unexpected element " + element);
      }

      if (directory == null) continue;

      if (result == null) {
        result = directory;
      } else {
        if (PsiTreeUtil.isAncestor(directory, result, true)) {
          result = directory;
        }
      }
    }

    return result;
  }
 @Override
 public void apply(
     @NotNull PsiElement startElement,
     @NotNull PsiElement endElement,
     @NotNull AndroidQuickfixContexts.Context context) {
   PsiFile file = startElement.getContainingFile();
   if (file instanceof XmlFile) {
     ResourceFolderType folderType = ResourceHelper.getFolderType(file);
     if (folderType != null) {
       if (folderType != ResourceFolderType.VALUES) {
         forkResourceFile((XmlFile) file, myFolder, true);
       } else {
         XmlTag tag =
             getValueTag(PsiTreeUtil.getParentOfType(startElement, XmlTag.class, false));
         if (tag != null) {
           AndroidFacet facet = AndroidFacet.getInstance(startElement);
           if (facet != null) {
             PsiDirectory dir = null;
             if (myFolder != null) {
               PsiDirectory resFolder = findRes(file);
               if (resFolder != null) {
                 dir = resFolder.findSubdirectory(myFolder);
                 if (dir == null) {
                   dir = resFolder.createSubdirectory(myFolder);
                 }
               }
             }
             forkResourceValue(startElement.getProject(), tag, file, facet, dir);
           }
         }
       }
     }
   }
 }
  protected void performRefactoring(
      Project project,
      PsiDirectory directory,
      PsiPackage aPackage,
      boolean searchInComments,
      boolean searchForTextOccurences) {
    final VirtualFile sourceRoot =
        ProjectRootManager.getInstance(project)
            .getFileIndex()
            .getSourceRootForFile(directory.getVirtualFile());
    if (sourceRoot == null) {
      Messages.showErrorDialog(
          project,
          RefactoringBundle.message("destination.directory.does.not.correspond.to.any.package"),
          RefactoringBundle.message("cannot.move"));
      return;
    }
    final JavaRefactoringFactory factory = JavaRefactoringFactory.getInstance(project);
    final MoveDestination destination =
        myPreserveSourceRoot.isSelected() && myPreserveSourceRoot.isVisible()
            ? factory.createSourceFolderPreservingMoveDestination(aPackage.getQualifiedName())
            : factory.createSourceRootMoveDestination(aPackage.getQualifiedName(), sourceRoot);

    MoveClassesOrPackagesProcessor processor =
        new MoveClassesOrPackagesProcessor(
            myDirectory.getProject(),
            myElementsToMove,
            destination,
            searchInComments,
            searchForTextOccurences,
            myMoveCallback);
    if (processor.verifyValidPackageName()) {
      processor.run();
    }
  }
 @Override
 public boolean isSourceRoot(@NotNull PsiDirectory dir) {
   final VirtualFile file = dir.getVirtualFile();
   final VirtualFile sourceRoot =
       ProjectRootManager.getInstance(dir.getProject()).getFileIndex().getSourceRootForFile(file);
   return file.equals(sourceRoot);
 }
Exemple #7
0
    @Override
    public Result<PsiModifierList> compute() {
      List<PsiModifierList> list = new ArrayList<PsiModifierList>();
      for (PsiDirectory directory : getDirectories()) {
        PsiFile file = directory.findFile(PACKAGE_INFO_FILE);
        if (file != null) {
          PsiPackageStatement stmt = PsiTreeUtil.getChildOfType(file, PsiPackageStatement.class);
          if (stmt != null) {
            final PsiModifierList modifierList = stmt.getAnnotationList();
            if (modifierList != null) {
              list.add(modifierList);
            }
          }
        }
      }

      final JavaPsiFacade facade = getFacade();
      final GlobalSearchScope scope = allScope();
      for (PsiClass aClass : facade.findClasses(getQualifiedName() + ".package-info", scope)) {
        ContainerUtil.addIfNotNull(aClass.getModifierList(), list);
      }

      return new Result<PsiModifierList>(
          list.isEmpty() ? null : new PsiCompositeModifierList(getManager(), list),
          OOCB_DEPENDENCY);
    }
    public MkDirs(@NotNull String newName, @NotNull 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)) {
            final PsiDirectory sub = directory.findSubdirectory(dir);
            directory = sub == null ? directory.createSubdirectory(dir) : sub;
          }
          firstToken = false;
        }
      }

      this.newName = newName;
      this.directory = directory;
    }
  @Nullable
  public static PsiDirectory selectFolderDir(
      final Project project, VirtualFile res, ResourceFolderType folderType) {
    final PsiDirectory directory = PsiManager.getInstance(project).findDirectory(res);
    if (directory == null) {
      return null;
    }
    if (ApplicationManager.getApplication().isUnitTestMode() && ourTargetFolderName != null) {
      PsiDirectory subDirectory = directory.findSubdirectory(ourTargetFolderName);
      if (subDirectory != null) {
        return subDirectory;
      }
      return directory.createSubdirectory(ourTargetFolderName);
    }
    final CreateResourceDirectoryDialog dialog =
        new CreateResourceDirectoryDialog(project, folderType, directory, null) {
          @Override
          protected InputValidator createValidator() {
            return new ResourceDirectorySelector(project, directory);
          }
        };
    dialog.setTitle("Select Resource Directory");
    dialog.show();
    final InputValidator validator = dialog.getValidator();
    if (validator != null) {
      PsiElement[] createdElements = ((ResourceDirectorySelector) validator).getCreatedElements();
      if (createdElements != null && createdElements.length > 0) {
        return (PsiDirectory) createdElements[0];
      }
    }

    return null;
  }
  @Override
  public void update(@NotNull AnActionEvent event) {
    final Presentation presentation = event.getPresentation();
    final Project project = event.getData(CommonDataKeys.PROJECT);
    if (project == null) {
      presentation.setVisible(false);
      presentation.setEnabled(false);
      return;
    }

    final IdeView view = event.getData(LangDataKeys.IDE_VIEW);
    if (view == null) {
      presentation.setVisible(false);
      presentation.setEnabled(false);
      return;
    }

    final PsiDirectory[] directories = view.getDirectories();
    if (directories.length == 0) {
      presentation.setVisible(false);
      presentation.setEnabled(false);
      return;
    }
    final PsiDirectory directory = DirectoryChooserUtil.getOrChooseDirectory(view);
    final CCProjectService service = CCProjectService.getInstance(project);
    final Course course = service.getCourse();
    if (course != null && directory != null && course.getLesson(directory.getName()) == null) {
      presentation.setVisible(false);
      presentation.setEnabled(false);
      return;
    }

    presentation.setVisible(true);
    presentation.setEnabled(true);
  }
  @Nullable
  private XmlFile createAnnotationsXml(
      @NotNull VirtualFile root, @NonNls @NotNull String packageName) {
    final String[] dirs = packageName.split("[\\.]");
    for (String dir : dirs) {
      if (dir.isEmpty()) break;
      VirtualFile subdir = root.findChild(dir);
      if (subdir == null) {
        try {
          subdir = root.createChildDirectory(null, dir);
        } catch (IOException e) {
          LOG.error(e);
        }
      }
      root = subdir;
    }
    final PsiDirectory directory = myPsiManager.findDirectory(root);
    if (directory == null) return null;

    final PsiFile psiFile = directory.findFile(ANNOTATIONS_XML);
    if (psiFile instanceof XmlFile) {
      return (XmlFile) psiFile;
    }

    try {
      final PsiFileFactory factory = PsiFileFactory.getInstance(myPsiManager.getProject());
      return (XmlFile)
          directory.add(
              factory.createFileFromText(ANNOTATIONS_XML, XmlFileType.INSTANCE, "<root></root>"));
    } catch (IncorrectOperationException e) {
      LOG.error(e);
    }
    return null;
  }
  public static PsiFile createFromTemplate(
      final PsiDirectory directory,
      final String name,
      String fileName,
      String templateName,
      @NonNls String... parameters)
      throws IncorrectOperationException {
    log.debug("createFromTemplate: dir:" + directory + ", filename: " + fileName);

    final FileTemplate template = FileTemplateManager.getInstance().getTemplate(templateName);

    Properties properties =
        new Properties(FileTemplateManager.getInstance().getDefaultProperties());

    String text;

    try {
      text = template.getText(properties);
    } catch (Exception e) {
      throw new RuntimeException(
          "Unable to load template for "
              + FileTemplateManager.getInstance().internalTemplateToSubject(templateName),
          e);
    }

    final PsiFileFactory factory = PsiFileFactory.getInstance(directory.getProject());

    log.debug("Create file from text");
    final PsiFile file = factory.createFileFromText(fileName, MoonFileType.MOON_FILE_TYPE, text);

    log.debug("Adding file to directory");
    return (PsiFile) directory.add(file);
  }
  @Nullable
  public static PsiDirectory selectDirectory(
      Project project,
      PsiDirectory[] packageDirectories,
      PsiDirectory defaultDirectory,
      String postfixToShow) {
    ProjectFileIndex projectFileIndex = getInstance(project).getFileIndex();

    ArrayList<PsiDirectory> possibleDirs = new ArrayList<>();
    for (PsiDirectory dir : packageDirectories) {
      if (!dir.isValid()) continue;
      if (!dir.isWritable()) continue;
      if (possibleDirs.contains(dir)) continue;
      if (!projectFileIndex.isInContent(dir.getVirtualFile())) continue;
      possibleDirs.add(dir);
    }

    if (possibleDirs.isEmpty()) return null;
    if (possibleDirs.size() == 1) return possibleDirs.get(0);

    if (getApplication().isUnitTestMode()) return possibleDirs.get(0);

    DirectoryChooser chooser = new DirectoryChooser(project);
    chooser.setTitle(message("title.choose.destination.directory"));
    chooser.fillList(
        possibleDirs.toArray(new PsiDirectory[possibleDirs.size()]),
        defaultDirectory,
        project,
        postfixToShow);
    return chooser.showAndGet() ? chooser.getSelectedDirectory() : null;
  }
    @Override
    protected void addCompletions(
        @NotNull CompletionParameters completionParameters,
        final ProcessingContext processingContext,
        @NotNull final CompletionResultSet completionResultSet) {

      PsiFile originalFile = completionParameters.getOriginalFile();
      final PsiDirectory containingDirectory = originalFile.getContainingDirectory();
      if (containingDirectory == null) {
        return;
      }

      final VirtualFile containingDirectoryFiles = containingDirectory.getVirtualFile();
      VfsUtil.visitChildrenRecursively(
          containingDirectoryFiles,
          new VirtualFileVisitor() {
            @Override
            public boolean visitFile(@NotNull VirtualFile file) {

              String relativePath = VfsUtil.getRelativePath(file, containingDirectoryFiles, '/');
              if (relativePath == null) {
                return super.visitFile(file);
              }

              completionResultSet.addElement(
                  LookupElementBuilder.create(relativePath).withIcon(file.getFileType().getIcon()));

              return super.visitFile(file);
            }
          });
    }
  public PsiElement createFromTemplate(
      final Project project,
      final PsiDirectory directory,
      String fileName,
      final FileTemplate template,
      final String templateText,
      final Properties props)
      throws IncorrectOperationException {
    fileName = checkAppendExtension(fileName, template);

    if (FileTypeManager.getInstance().isFileIgnored(fileName)) {
      throw new IncorrectOperationException(
          "This filename is ignored (Settings | File Types | Ignore files and folders)");
    }

    directory.checkCreateFile(fileName);
    PsiFile file = PsiFileFactory.getInstance(project).createFileFromText(fileName, templateText);

    if (template.isReformatCode()) {
      CodeStyleManager.getInstance(project).reformat(file);
    }

    file = (PsiFile) directory.add(file);
    return file;
  }
 @Override
 public PsiPackage getPackage(@NotNull PsiDirectory dir) {
   ProjectFileIndex projectFileIndex =
       ProjectRootManager.getInstance(dir.getProject()).getFileIndex();
   String packageName = projectFileIndex.getPackageNameByDirectory(dir.getVirtualFile());
   if (packageName == null) return null;
   return JavaPsiFacade.getInstance(dir.getProject()).findPackage(packageName);
 }
 @Override
 public PsiElement[] create(String newName) throws Exception {
   PsiDirectory subdirectory = myDirectory.findSubdirectory(newName);
   if (subdirectory == null) {
     subdirectory = myDirectory.createSubdirectory(newName);
   }
   return new PsiElement[] {subdirectory};
 }
 private static boolean isWritablePackage(PsiPackage aPackage) {
   PsiDirectory[] directories = aPackage.getDirectories();
   for (PsiDirectory directory : directories) {
     if (directory.isValid() && directory.isWritable()) {
       return true;
     }
   }
   return false;
 }
 @NotNull
 public static PsiDirectory findOrCreateSubdirectory(
     @NotNull PsiDirectory directory, @NotNull String directoryName) {
   PsiDirectory subDirectory = directory.findSubdirectory(directoryName);
   if (subDirectory == null) {
     subDirectory = directory.createSubdirectory(directoryName);
   }
   return subDirectory;
 }
  @SuppressWarnings("DialogTitleCapitalization")
  @Nullable
  public static PsiFile createFileFromTemplate(
      @SuppressWarnings("NullableProblems") @NotNull String name,
      @NotNull FileTemplate template,
      @NotNull PsiDirectory dir,
      @Nullable String defaultTemplateProperty) {
    // TODO: Do we *have* to hack the IntelliJ source?
    // This is a roughly a copy/paste then slight adaptation from the IntelliJ definition of this
    // method.
    // We can't override it directly, and more importantly we can't override its call to
    // FileTemplateUtil.createFromTemplate()
    List<String> pathItems = FileUtil.getPathFromSourceRoot(dir.getProject(), dir.getVirtualFile());
    // modulePrefix is the empty string if the module is either in the top
    // level directory or one of the subdirectories start with a lower-case
    // letter.
    final String modulePrefix =
        pathItems == null || invalidPathItems(pathItems) ? "" : StringUtil.join(pathItems, ".");

    // Adapted from super definition.
    CreateFileAction.MkDirs mkdirs = new CreateFileAction.MkDirs(name, dir);
    name = mkdirs.newName;
    dir = mkdirs.directory;
    PsiElement element;
    Project project = dir.getProject();
    try {
      // Patch props with custom property.
      Properties props = FileTemplateManager.getInstance().getDefaultProperties(project);
      props.setProperty(
          "HASKELL_MODULE_NAME", modulePrefix.isEmpty() ? name : modulePrefix + '.' + name);
      element = FileTemplateUtil.createFromTemplate(template, name, props, dir);

      final PsiFile psiFile = element.getContainingFile();

      final VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile != null) {
        FileEditorManager.getInstance(project).openFile(virtualFile, true);
        if (defaultTemplateProperty != null) {
          PropertiesComponent.getInstance(project)
              .setValue(defaultTemplateProperty, template.getName());
        }
        return psiFile;
      }
    } catch (ParseException e) {
      Messages.showErrorDialog(
          project,
          "Error parsing Velocity template: " + e.getMessage(),
          "Create File from Template");
      return null;
    } catch (IncorrectOperationException e) {
      throw e;
    } catch (Exception e) {
      LOG.error(e);
    }

    return null;
  }
  @Nullable
  public static FolderConfiguration selectFolderConfig(
      final Project project, VirtualFile res, ResourceFolderType folderType) {
    PsiDirectory dir = selectFolderDir(project, res, folderType);
    if (dir != null) {
      return FolderConfiguration.getConfigForFolder(dir.getName());
    }

    return null;
  }
  private static LanguageLevel getLanguageLevelInner(@NotNull PsiDirectory dir) {
    final VirtualFile virtualFile = dir.getVirtualFile();
    final Project project = dir.getProject();
    final Module module =
        ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile);
    if (module != null) {
      return LanguageLevelUtil.getEffectiveLanguageLevel(module);
    }

    return LanguageLevelProjectExtension.getInstance(project).getLanguageLevel();
  }
 private static PsiDirectory getWritableModuleDirectory(
     @NotNull Query<VirtualFile> vFiles, @NotNull Module module, PsiManager manager) {
   for (VirtualFile vFile : vFiles) {
     if (ModuleUtil.findModuleForFile(vFile, module.getProject()) != module) continue;
     PsiDirectory directory = manager.findDirectory(vFile);
     if (directory != null && directory.isValid() && directory.isWritable()) {
       return directory;
     }
   }
   return null;
 }
 @Override
 public LanguageLevel getLanguageLevel(@NotNull PsiDirectory dir) {
   synchronized (PsiLock.LOCK) {
     LanguageLevel level = dir.getUserData(LANG_LEVEL_IN_DIRECTORY);
     if (level == null) {
       level = getLanguageLevelInner(dir);
       dir.putUserData(LANG_LEVEL_IN_DIRECTORY, level);
     }
     return level;
   }
 }
Exemple #25
0
  private SModelReference makeModelReference(PsiDirectory sourceRoot, PsiDirectory dir) {
    int skipPrefix = sourceRoot.toString().length();
    String relativeDirName = dir.toString().substring(skipPrefix);
    String packageName = relativeDirName.replace('/', '.').replace('\\', '.');

    if (packageName.length() > 0 && packageName.charAt(0) == '.') {
      packageName = packageName.substring(1);
    }

    return (SModelReference) Util.makeModelReference(packageName, getModule());
  }
 private void doTestAppResolveTest(String expectedAppDirName) throws Exception {
   PsiFile testappuserErl = myFixture.getFile();
   assertTrue(testappuserErl instanceof ErlangFile);
   List<ErlangFile> directlyIncludedFiles =
       ErlangPsiImplUtil.getDirectlyIncludedFiles((ErlangFile) testappuserErl);
   assertEquals(1, directlyIncludedFiles.size());
   PsiDirectory ebinDirectory = directlyIncludedFiles.get(0).getParent();
   assertNotNull(ebinDirectory);
   PsiDirectory appDir = ebinDirectory.getParent();
   assertNotNull(appDir);
   assertEquals(expectedAppDirName, appDir.getName());
 }
  public static boolean isInsideProjectSources(AnActionEvent event) {
    ProjectFileIndex projectFileIndex =
        ProjectRootManager.getInstance(event.getProject()).getFileIndex();
    final IdeView view = event.getData(DataKeys.IDE_VIEW);

    for (PsiDirectory dir : view.getDirectories()) {
      if (projectFileIndex.isInSourceContent(dir.getVirtualFile())
          && JavaDirectoryService.getInstance().getPackage(dir) != null) {
        return true;
      }
    }
    return false;
  }
  private static boolean allowed(@NotNull GoNamedElement element) {
    GoFile file = element.getContainingFile();
    if (GoPsiImplUtil.builtin(element) || !GoUtil.allowed(file) || GoUtil.isExcludedFile(file))
      return false;
    PsiDirectory directory = file.getContainingDirectory();
    if (directory != null) {
      VirtualFile vFile = directory.getVirtualFile();
      if (vFile.getPath().endsWith("go/doc/testdata")) return false;
    }

    if (StringUtil.equals(file.getPackageName(), GoConstants.MAIN)) return false;
    return true;
  }
 private static boolean isTestDirectory(final Module module, final PsiElement element) {
   final PsiDirectory dir = (PsiDirectory) element;
   final ModuleRootManager manager = ModuleRootManager.getInstance(module);
   final ContentEntry[] entries = manager.getContentEntries();
   for (ContentEntry entry : entries) {
     for (SourceFolder folder : entry.getSourceFolders()) {
       if (folder.isTestSource() && folder.getFile() == dir.getVirtualFile()) {
         return true;
       }
     }
   }
   return false;
 }
 public static List<VirtualFile> getPotentialRoots(Module module) {
   final PsiDirectory[] dirs = getIntentionDescriptionsDirs(module);
   final List<VirtualFile> result = new ArrayList<VirtualFile>();
   if (dirs.length != 0) {
     for (PsiDirectory dir : dirs) {
       final PsiDirectory parent = dir.getParentDirectory();
       if (parent != null) result.add(parent.getVirtualFile());
     }
   } else {
     ContainerUtil.addAll(result, ModuleRootManager.getInstance(module).getSourceRoots());
   }
   return result;
 }