Java Code Examples for com.intellij.openapi.roots.ProjectFileIndex#getModuleForFile()

The following examples show how to use com.intellij.openapi.roots.ProjectFileIndex#getModuleForFile() . 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: ProjectFileIndexSampleAction.java    From intellij-sdk-docs with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
  Project project = event.getProject();
  final Editor editor = event.getData(CommonDataKeys.EDITOR);
  if (project == null || editor == null) return;
  Document document = editor.getDocument();
  FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
  VirtualFile virtualFile = fileDocumentManager.getFile(document);
  ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  if (virtualFile != null) {
    Module module = projectFileIndex.getModuleForFile(virtualFile);
    String moduleName;
    moduleName = module != null ? module.getName() : "No module defined for file";

    VirtualFile moduleContentRoot = projectFileIndex.getContentRootForFile(virtualFile);
    boolean isLibraryFile = projectFileIndex.isLibraryClassFile(virtualFile);
    boolean isInLibraryClasses = projectFileIndex.isInLibraryClasses(virtualFile);
    boolean isInLibrarySource = projectFileIndex.isInLibrarySource(virtualFile);
    Messages.showInfoMessage("Module: " + moduleName + "\n" +
                             "Module content root: " + moduleContentRoot + "\n" +
                             "Is library file: " + isLibraryFile + "\n" +
                             "Is in library classes: " + isInLibraryClasses +
                             ", Is in library source: " + isInLibrarySource,
                             "Main File Info for" + virtualFile.getName());
  }
}
 
Example 2
Source File: ModificationAction.java    From intellij-sdk-docs with Apache License 2.0 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull final AnActionEvent event) {
  Project project = event.getProject();
  if (project == null) return;
  Navigatable element = event.getData(CommonDataKeys.NAVIGATABLE);
  if (element instanceof PsiClass) {
    PsiFile file = ((PsiClass) element).getContainingFile();
    if (file == null) return;
    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile == null) return;
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final Module module = fileIndex.getModuleForFile(virtualFile);
    if (module == null) return;
    if (!ModuleRootManager.getInstance(module).getFileIndex().isInContent(virtualFile)) {
      ModuleRootModificationUtil.addModuleLibrary(module, virtualFile.getUrl());
    }
  }

}
 
Example 3
Source File: FilePatternPackageSet.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean matchesModule(final Pattern moduleGroupPattern,
                                    final Pattern modulePattern,
                                    final VirtualFile file,
                                    final ProjectFileIndex fileIndex) {
  final Module module = fileIndex.getModuleForFile(file);
  if (module != null) {
    if (modulePattern != null && modulePattern.matcher(module.getName()).matches()) return true;
    if (moduleGroupPattern != null) {
      final String[] groupPath = ModuleManager.getInstance(module.getProject()).getModuleGroupPath(module);
      if (groupPath != null) {
        for (String node : groupPath) {
          if (moduleGroupPattern.matcher(node).matches()) return true;
        }
      }
    }
  }
  return modulePattern == null && moduleGroupPattern == null;
}
 
Example 4
Source File: FilePatternPackageSet.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public static String getRelativePath(@Nonnull VirtualFile virtualFile,
                                     @Nonnull ProjectFileIndex index,
                                     final boolean useFQName,
                                     VirtualFile projectBaseDir) {
  final VirtualFile contentRootForFile = index.getContentRootForFile(virtualFile);
  if (contentRootForFile != null) {
    return VfsUtilCore.getRelativePath(virtualFile, contentRootForFile, '/');
  }
  final Module module = index.getModuleForFile(virtualFile);
  if (module != null) {
    if (projectBaseDir != null) {
      if (VfsUtilCore.isAncestor(projectBaseDir, virtualFile, false)){
        final String projectRelativePath = VfsUtilCore.getRelativePath(virtualFile, projectBaseDir, '/');
        return useFQName ? projectRelativePath : projectRelativePath.substring(projectRelativePath.indexOf('/') + 1);
      }
    }
    return virtualFile.getPath();
  } else {
    return getLibRelativePath(virtualFile, index);
  }
}
 
Example 5
Source File: ChangesModuleGroupingPolicy.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public ChangesBrowserNode getParentNodeFor(final StaticFilePath node, final ChangesBrowserNode rootNode) {
  if (myProject.isDefault()) return null;

  ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex();

  VirtualFile vFile = node.getVf();
  if (vFile == null) {
    vFile = LocalFileSystem.getInstance().findFileByIoFile(new File(node.getPath()));
  }
  boolean hideExcludedFiles = Registry.is("ide.hide.excluded.files");
  if (vFile != null && Comparing.equal(vFile, index.getContentRootForFile(vFile, hideExcludedFiles))) {
    Module module = index.getModuleForFile(vFile, hideExcludedFiles);
    return getNodeForModule(module, rootNode);
  }
  return null;
}
 
Example 6
Source File: TodoTreeBuilder.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * @return read-only iterator of all valid PSI files that can have T.O.D.O items
 * and which in specified {@code module}.
 * @see FileTree#getFiles(VirtualFile)
 */
public Iterator<PsiFile> getFiles(Module module) {
  if (module.isDisposed()) return Collections.emptyIterator();
  ArrayList<PsiFile> psiFileList = new ArrayList<>();
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
  final VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();
  for (VirtualFile virtualFile : contentRoots) {
    List<VirtualFile> files = myFileTree.getFiles(virtualFile);
    PsiManager psiManager = PsiManager.getInstance(myProject);
    for (VirtualFile file : files) {
      if (fileIndex.getModuleForFile(file) != module) continue;
      if (file.isValid()) {
        PsiFile psiFile = psiManager.findFile(file);
        if (psiFile != null) {
          psiFileList.add(psiFile);
        }
      }
    }
  }
  return psiFileList.iterator();
}
 
Example 7
Source File: PackageViewPane.java    From consulo with Apache License 2.0 6 votes vote down vote up
private Module[] getModulesFor(PsiDirectory dir) {
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
  final VirtualFile vFile = dir.getVirtualFile();
  final Set<Module> modules = new HashSet<Module>();
  final Module module = fileIndex.getModuleForFile(vFile);
  if (module != null) {
    modules.add(module);
  }
  if (fileIndex.isInLibrarySource(vFile) || fileIndex.isInLibraryClasses(vFile)) {
    final List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(vFile);
    if (orderEntries.isEmpty()) {
      return Module.EMPTY_ARRAY;
    }
    for (OrderEntry entry : orderEntries) {
      modules.add(entry.getOwnerModule());
    }
  }
  return modules.toArray(new Module[modules.size()]);
}
 
Example 8
Source File: DocCommentProcessor.java    From markdown-doclet with GNU General Public License v3.0 6 votes vote down vote up
public DocCommentProcessor(PsiFile file) {
    this.file = file;
    if ( file == null ) {
        project = null;
        markdownOptions = null;
        psiElementFactory = null;
    }
    else {
        project = file.getProject();
        psiElementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
        ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
        Module module = fileIndex.getModuleForFile(file.getVirtualFile());
        if ( module == null ) {
            markdownOptions = null;
        }
        else if ( !fileIndex.isInSourceContent(file.getVirtualFile()) ) {
            markdownOptions = null;
        }
        else if ( !Plugin.moduleConfiguration(module).isMarkdownEnabled() ) {
            markdownOptions = null;
        }
        else {
            markdownOptions = Plugin.moduleConfiguration(module).getRenderingOptions();
        }
    }
}
 
Example 9
Source File: PantsUnresolvedReferenceFixFinder.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
public static List<PantsQuickFix> findMissingDependencies(@NotNull String referenceName, @NotNull PsiFile containingFile) {
  final VirtualFile containingClassFile = containingFile.getVirtualFile();
  if (containingClassFile == null) return Collections.emptyList();

  final Project project = containingFile.getProject();

  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  final Module containingModule = fileIndex.getModuleForFile(containingClassFile);

  final List<PantsTargetAddress> addresses = PantsUtil.getTargetAddressesFromModule(containingModule);
  if (addresses.size() != 1) return Collections.emptyList();

  final PantsTargetAddress currentAddress = addresses.iterator().next();

  final PsiClass[] classes = PsiShortNamesCache.getInstance(project).getClassesByName(referenceName, GlobalSearchScope.allScope(project));
  final List<PsiClass> allowedDependencies = filterAllowedDependencies(containingFile, classes);
  final List<PantsQuickFix> result = new ArrayList<>();
  for (PsiClass dependency : allowedDependencies) {
    final Module module = ModuleUtil.findModuleForPsiElement(dependency);
    for (PantsTargetAddress addressToAdd : PantsUtil.getTargetAddressesFromModule(module)) {
      result.add(new AddPantsTargetDependencyFix(currentAddress, addressToAdd));
    }
    // todo(fkoroktov): handle jars
  }
  return result;
}
 
Example 10
Source File: ProjectRootsUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
public static ContentFolder findContentFolderForDirectory(@Nonnull ProjectFileIndex projectFileIndex, @Nonnull VirtualFile virtualFile) {
  final Module module = projectFileIndex.getModuleForFile(virtualFile);
  if (module == null) {
    return null;
  }

  ContentFolder contentFolder = projectFileIndex.getContentFolder(virtualFile);
  if (contentFolder == null) {
    return null;
  }
  return virtualFile.equals(contentFolder.getFile()) ? contentFolder : null;
}
 
Example 11
Source File: DocumentationComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
private String getLocationText() {
  PsiElement element = getElement();
  if (element != null) {
    PsiFile file = element.getContainingFile();
    VirtualFile vfile = file == null ? null : file.getVirtualFile();

    if (vfile == null) return null;

    ProjectFileIndex fileIndex = ProjectRootManager.getInstance(element.getProject()).getFileIndex();
    Module module = fileIndex.getModuleForFile(vfile);

    if (module != null) {
      if (ModuleManager.getInstance(element.getProject()).getModules().length == 1) return null;
      return "<icon src='/actions/module.png'>&nbsp;" + module.getName().replace("<", "&lt;");
    }
    else {
      List<OrderEntry> entries = fileIndex.getOrderEntriesForFile(vfile);
      for (OrderEntry order : entries) {
        if (order instanceof OrderEntryWithTracking) {
          return "<icon src='AllIcons.Nodes.PpLibFolder" + "'>&nbsp;" + order.getPresentableName().replace("<", "&lt;");
        }
      }
    }
  }

  return null;
}
 
Example 12
Source File: SummaryNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void createModuleTodoNodeForFile(ArrayList<? super AbstractTreeNode> children, ProjectFileIndex projectFileIndex, VirtualFile virtualFile) {
  Module module = projectFileIndex.getModuleForFile(virtualFile);
  if (module != null) {
    ModuleToDoNode moduleToDoNode = new ModuleToDoNode(getProject(), module, myBuilder);
    if (!children.contains(moduleToDoNode)) {
      children.add(moduleToDoNode);
    }
  }
}
 
Example 13
Source File: BaseProjectViewDirectoryHelper.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
public static Collection<AbstractTreeNode> doGetDirectoryChildren(final PsiDirectory psiDirectory, final ViewSettings settings, final boolean withSubDirectories) {
  final List<AbstractTreeNode> children = new ArrayList<>();
  final Project project = psiDirectory.getProject();
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  final Module module = fileIndex.getModuleForFile(psiDirectory.getVirtualFile());
  final ModuleFileIndex moduleFileIndex = module == null ? null : ModuleRootManager.getInstance(module).getFileIndex();
  if (!settings.isFlattenPackages() || skipDirectory(psiDirectory)) {
    processPsiDirectoryChildren(psiDirectory, directoryChildrenInProject(psiDirectory, settings), children, fileIndex, null, settings, withSubDirectories);
  }
  else { // source directory in "flatten packages" mode
    final PsiDirectory parentDir = psiDirectory.getParentDirectory();
    if (parentDir == null || skipDirectory(parentDir) /*|| !rootDirectoryFound(parentDir)*/ && withSubDirectories) {
      addAllSubpackages(children, psiDirectory, moduleFileIndex, settings);
    }
    PsiDirectory[] subdirs = psiDirectory.getSubdirectories();
    for (PsiDirectory subdir : subdirs) {
      if (!skipDirectory(subdir)) {
        continue;
      }
      VirtualFile directoryFile = subdir.getVirtualFile();
      if (FileTypeRegistry.getInstance().isFileIgnored(directoryFile)) continue;

      if (withSubDirectories) {
        children.add(new PsiDirectoryNode(project, subdir, settings));
      }
    }
    processPsiDirectoryChildren(psiDirectory, psiDirectory.getFiles(), children, fileIndex, moduleFileIndex, settings, withSubDirectories);
  }
  return children;
}
 
Example 14
Source File: CppSupportLoader.java    From CppTools with Apache License 2.0 5 votes vote down vote up
public static boolean isInSource(VirtualFile virtualFile, ProjectFileIndex fileIndex) {
  if (fileIndex.isInSourceContent(virtualFile)) {
    return !fileIndex.isInTestSourceContent(virtualFile) &&
      fileIndex.getModuleForFile(virtualFile) != null;
  } else if (!EnvironmentFacade.isJavaIde()) {
    return fileIndex.getModuleForFile(virtualFile) != null;
  }
  return false;
}
 
Example 15
Source File: BuckAddDependencyIntention.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an {@link com.intellij.codeInsight.intention.IntentionAction} that will create an
 * dependency edge in both the Buck target graph and IntelliJ module graph from the nodes for the
 * given reference element to those of the given psiClass.
 *
 * <p>Note that this intention can fail to be created if either side of the edge cannot be
 * resolved to a buck file in a buck cell, in which case this method returns null. Also, invoking
 * this intention may fail to create edges in either the Buck target graph or the IntelliJ module
 * graph (or both).
 */
@Nullable
public static BuckAddDependencyIntention create(PsiReference reference, PsiClass psiClass) {
  VirtualFile editSourceFile = reference.getElement().getContainingFile().getVirtualFile();
  if (editSourceFile == null) {
    return null;
  }
  Project project = reference.getElement().getProject();
  BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project);
  VirtualFile editBuildFile =
      buckTargetLocator.findBuckFileForVirtualFile(editSourceFile).orElse(null);
  if (editBuildFile == null) {
    return null;
  }
  VirtualFile importSourceFile = psiClass.getContainingFile().getVirtualFile();
  if (importSourceFile == null) {
    return null;
  }
  VirtualFile importBuildFile =
      buckTargetLocator.findBuckFileForVirtualFile(importSourceFile).orElse(null);
  if (importBuildFile == null) {
    return null;
  }
  if (importBuildFile.equals(editBuildFile)) {
    return null;
  }
  ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(project);
  Module editModule = projectFileIndex.getModuleForFile(editSourceFile);
  if (editModule == null) {
    return null;
  }
  Module importModule = projectFileIndex.getModuleForFile(importSourceFile);
  if (importModule == null) {
    return null;
  }
  BuckTarget editSourceTarget =
      buckTargetLocator
          .findTargetPatternForVirtualFile(editSourceFile)
          .flatMap(BuckTargetPattern::asBuckTarget)
          .orElse(null);
  if (editSourceTarget == null) {
    return null;
  }
  BuckTarget importSourceTarget =
      buckTargetLocator
          .findTargetPatternForVirtualFile(importSourceFile)
          .flatMap(BuckTargetPattern::asBuckTarget)
          .orElse(null);
  if (importSourceTarget == null) {
    return null;
  }
  return new BuckAddDependencyIntention(
      project,
      reference,
      editBuildFile,
      editSourceFile,
      editSourceTarget,
      editModule,
      psiClass,
      importBuildFile,
      importSourceFile,
      importSourceTarget,
      importModule);
}
 
Example 16
Source File: PsiDirectoryNode.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected void updateImpl(PresentationData data) {
  final Project project = getProject();
  final PsiDirectory psiDirectory = getValue();
  final VirtualFile directoryFile = psiDirectory.getVirtualFile();

  final Object parentValue = getParentValue();
  if (ProjectRootsUtil.isModuleContentRoot(directoryFile, project)) {
    ProjectFileIndex fi = ProjectRootManager.getInstance(project).getFileIndex();
    Module module = fi.getModuleForFile(directoryFile);

    data.setPresentableText(directoryFile.getName());
    if (module != null) {
      if (!(parentValue instanceof Module)) {
        if (Comparing.equal(module.getName(), directoryFile.getName())) {
          data.addText(directoryFile.getName(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
        }
        else {
          data.addText(directoryFile.getName() + " ", SimpleTextAttributes.REGULAR_ATTRIBUTES);
          data.addText("[" + module.getName() + "]", SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
        }
      }
      else {
        data.addText(directoryFile.getName(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
      }

      if (parentValue instanceof Module || parentValue instanceof Project) {
        final String location = FileUtil.getLocationRelativeToUserHome(directoryFile.getPresentableUrl());
        data.addText(" (" + location + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
      }
      else if (ProjectRootsUtil.isSourceOrTestRoot(directoryFile, project)) {
        if (ProjectRootsUtil.isInTestSource(directoryFile, project)) {
          data.addText(" (test source root)", SimpleTextAttributes.GRAY_ATTRIBUTES);
        }
        else {
          data.addText(" (source root)",  SimpleTextAttributes.GRAY_ATTRIBUTES);
        }
      }

      setupIcon(data, psiDirectory);

      return;
    }
  }

  final String name = parentValue instanceof Project
                      ? psiDirectory.getVirtualFile().getPresentableUrl()
                      : BaseProjectViewDirectoryHelper.getNodeName(getSettings(), parentValue, psiDirectory);
  if (name == null) {
    setValue(null);
    return;
  }

  data.setPresentableText(name);
  if (ProjectRootsUtil.isLibraryRoot(directoryFile, project)) {
    data.setLocationString("library home");
  }
  else {
    data.setLocationString(BaseProjectViewDirectoryHelper.getLocationString(psiDirectory));
  }

  setupIcon(data, psiDirectory);
}