public static boolean isTest(VirtualFile virtualFile, Project project) { if (virtualFile == null) { return false; } final ProjectRootManager rootManager = ProjectRootManager.getInstance(project); final ProjectFileIndex fileIndex = rootManager.getFileIndex(); return fileIndex.isInTestSourceContent(virtualFile); }
@Override public Module getModule() { if (!isValid()) return null; VirtualFile virtualFile = getFile(); if (virtualFile == null) return null; ProjectRootManager projectRootManager = ProjectRootManager.getInstance(getProject()); ProjectFileIndex fileIndex = projectRootManager.getFileIndex(); return fileIndex.getModuleForFile(virtualFile); }
protected boolean isTestScope(@Nullable final PsiFile context) { if ((context == null)) { return false; } PsiFile _originalFile = context.getOriginalFile(); VirtualFile virtualFile = _originalFile.getVirtualFile(); if ((virtualFile != null)) { Project _project = context.getProject(); ProjectRootManager _instance = ProjectRootManager.getInstance(_project); ProjectFileIndex _fileIndex = _instance.getFileIndex(); return _fileIndex.isInTestSourceContent(virtualFile); } return false; }
@NotNull private static String getFileFqn(final PsiFile file) { final VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile == null) { return file.getName(); } final Project project = file.getProject(); final LogicalRoot logicalRoot = LogicalRootsManager.getLogicalRootsManager(project).findLogicalRoot(virtualFile); if (logicalRoot != null) { String logical = FileUtil.toSystemIndependentName( VfsUtil.virtualToIoFile(logicalRoot.getVirtualFile()).getPath()); String path = FileUtil.toSystemIndependentName(VfsUtil.virtualToIoFile(virtualFile).getPath()); return "/" + FileUtil.getRelativePath(logical, path, '/'); } final VirtualFile contentRoot = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(virtualFile); if (contentRoot != null) { return "/" + FileUtil.getRelativePath( VfsUtil.virtualToIoFile(contentRoot), VfsUtil.virtualToIoFile(virtualFile)); } return virtualFile.getPath(); }
@Override public Object[] getDirectoryCachedValueDependencies(PsiPackage psiPackage) { return new Object[] { PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT, ProjectRootManager.getInstance(psiPackage.getProject()) }; }
@Nullable public static Sdk findOrCreateSdk( @Nullable Comparator<Sdk> comparator, final SdkType... sdkTypes) { final Project defaultProject = ProjectManager.getInstance().getDefaultProject(); final Sdk sdk = ProjectRootManager.getInstance(defaultProject).getProjectSdk(); if (sdk != null) { for (SdkType type : sdkTypes) { if (sdk.getSdkType() == type) { return sdk; } } } for (SdkType type : sdkTypes) { List<Sdk> sdks = ProjectJdkTable.getInstance().getSdksOfType(type); if (!sdks.isEmpty()) { if (comparator != null) { Collections.sort(sdks, comparator); } return sdks.get(0); } } for (SdkType sdkType : sdkTypes) { final String suggestedHomePath = sdkType.suggestHomePath(); if (suggestedHomePath != null && sdkType.isValidSdkHome(suggestedHomePath)) { Sdk an_sdk = createAndAddSDK(suggestedHomePath, sdkType); if (an_sdk != null) return an_sdk; } } return null; }
@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; }
@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); }
public void testSCR6066() throws Exception { ProjectRootManagerEx rootManager = (ProjectRootManagerEx) ProjectRootManager.getInstance(myProject); final VirtualFile root = rootManager.getContentRoots()[0]; PsiTodoSearchHelper.SERVICE .getInstance(myProject) .findFilesWithTodoItems(); // to initialize caches new WriteCommandAction.Simple(getProject()) { @Override protected void run() throws Throwable { VirtualFile newFile = createChildData(root, "New.java"); setFileText(newFile, "class A{ Exception e;} //todo"); } }.execute().throwException(); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches PsiTestUtil.addExcludedRoot(myModule, root); PsiClass exceptionClass = myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject())); assertNotNull(exceptionClass); checkUsages(exceptionClass, new String[] {}); checkTodos(new String[] {}); }
public AddModuleDependencyFix( Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) { final PsiElement psiElement = reference.getElement(); final Project project = psiElement.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiClass aClass : classes) { if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue; PsiFile psiFile = aClass.getContainingFile(); if (psiFile == null) continue; VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile == null) continue; final Module classModule = fileIndex.getModuleForFile(virtualFile); if (classModule != null && classModule != currentModule && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) { myModules.add(classModule); } } myCurrentModule = currentModule; myClassVFile = classVFile; myClasses = classes; myReference = reference; }
private boolean fileInRoots(VirtualFile file) { final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex(); return file != null && (index.isInSourceContent(file) || index.isInLibraryClasses(file) || index.isInLibrarySource(file)); }
private void setUpChooseHtmlToShow() { FileChooserDescriptor fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileDescriptor(StdFileTypes.HTML); fileChooserDescriptor.setRoots(ProjectRootManager.getInstance(project).getContentRoots()); htmlChooseFile.addBrowseFolderListener( "Choose file to show after translation is finished", null, project, fileChooserDescriptor); }
private static THashSet<String> collectFoldersToExclude( final Module module, final VirtualFile pubspecYamlFile) { final THashSet<String> newExcludedPackagesUrls = new THashSet<String>(); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex(); final VirtualFile root = pubspecYamlFile.getParent(); final VirtualFile binFolder = root.findChild("bin"); if (binFolder != null && binFolder.isDirectory() && fileIndex.isInContent(binFolder)) { newExcludedPackagesUrls.add(binFolder.getUrl() + "/packages"); } appendPackagesFolders(newExcludedPackagesUrls, root.findChild("benchmark"), fileIndex); appendPackagesFolders(newExcludedPackagesUrls, root.findChild("example"), fileIndex); appendPackagesFolders(newExcludedPackagesUrls, root.findChild("test"), fileIndex); appendPackagesFolders(newExcludedPackagesUrls, root.findChild("tool"), fileIndex); appendPackagesFolders(newExcludedPackagesUrls, root.findChild("web"), fileIndex); // Folder packages/ThisProject (where ThisProject is the name specified in pubspec.yaml) is a // symlink to local 'lib' folder. Exclude it in order not to have duplicates. Resolve goes to // local 'lib' folder. // Empty 'ThisProject (link to 'lib' folder)' node is added to Project Structure by // DartTreeStructureProvider final VirtualFile libFolder = root.findChild("lib"); if (libFolder != null && libFolder.isDirectory()) { final String pubspecName = PubspecYamlUtil.getPubspecName(pubspecYamlFile); if (pubspecName != null) { newExcludedPackagesUrls.add(root.getUrl() + "/packages/" + pubspecName); } } return newExcludedPackagesUrls; }
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(); } }
private void initLivePackageNameToDirMap() { final VirtualFile baseDir = myPubspecYamlFile == null ? null : myPubspecYamlFile.getParent(); if (myPubspecYamlFile == null || baseDir == null) return; final String name = PubspecYamlUtil.getDartProjectName(myPubspecYamlFile); final VirtualFile libFolder = baseDir.findChild(PubspecYamlUtil.LIB_DIR_NAME); if (name != null && libFolder != null && libFolder.isDirectory()) { myLivePackageNameToDirMap.put(name, libFolder); } final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); PubspecYamlUtil.processPathPackages( myPubspecYamlFile, new PairConsumer<String, VirtualFile>() { @Override public void consume( @NotNull final String packageName, @NotNull final VirtualFile packageDir) { if (fileIndex.isInContent(packageDir)) { myLivePackageNameToDirMap.put(packageName, packageDir); } } }); }
private void initPubListPackageDirsMap(final @NotNull VirtualFile contextFile) { final Module module = ModuleUtilCore.findModuleForFile(contextFile, myProject); final List<OrderEntry> orderEntries = module != null ? Arrays.asList(ModuleRootManager.getInstance(module).getOrderEntries()) : ProjectRootManager.getInstance(myProject) .getFileIndex() .getOrderEntriesForFile(contextFile); for (OrderEntry orderEntry : orderEntries) { if (orderEntry instanceof LibraryOrderEntry && LibraryTablesRegistrar.PROJECT_LEVEL.equals( ((LibraryOrderEntry) orderEntry).getLibraryLevel()) && PubListPackageDirsAction.PUB_LIST_PACKAGE_DIRS_LIB_NAME.equals( ((LibraryOrderEntry) orderEntry).getLibraryName())) { final LibraryEx library = (LibraryEx) ((LibraryOrderEntry) orderEntry).getLibrary(); final LibraryProperties properties = library == null ? null : library.getProperties(); if (properties instanceof DartListPackageDirsLibraryProperties) { myPubListPackageDirsMap.putAll( ((DartListPackageDirsLibraryProperties) properties).getPackageNameToDirsMap()); return; } } } }
private void checkProjectRoots() { LocalFileSystem fs = LocalFileSystem.getInstance(); if (!(fs instanceof LocalFileSystemImpl)) return; FileWatcher watcher = ((LocalFileSystemImpl) fs).getFileWatcher(); if (!watcher.isOperational()) return; Collection<String> manualWatchRoots = watcher.getManualWatchRoots(); if (manualWatchRoots.isEmpty()) return; VirtualFile[] roots = ProjectRootManager.getInstance(myProject).getContentRoots(); if (roots.length == 0) return; List<String> nonWatched = new SmartList<String>(); for (VirtualFile root : roots) { if (!(root.getFileSystem() instanceof LocalFileSystem)) continue; String rootPath = root.getPath(); for (String manualWatchRoot : manualWatchRoots) { if (FileUtil.isAncestor(manualWatchRoot, rootPath, false)) { nonWatched.add(rootPath); } } } if (!nonWatched.isEmpty()) { String message = ApplicationBundle.message("watcher.non.watchable.project"); watcher.notifyOnFailure(message, null); LOG.info("unwatched roots: " + nonWatched); LOG.info("manual watches: " + manualWatchRoots); } }
@Override @Nullable public GlobalSearchScope getSearchScope() { GlobalSearchScope scope = null; Module[] modules = getConvertContextModules(); if (modules.length != 0) { PsiFile file = getFile(); file = file.getOriginalFile(); VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null) { ProjectFileIndex fileIndex = ProjectRootManager.getInstance(file.getProject()).getFileIndex(); boolean tests = fileIndex.isInTestSourceContent(virtualFile); for (Module module : modules) { if (scope == null) { scope = module.getModuleRuntimeScope(tests); } else { scope = scope.union(module.getModuleRuntimeScope(tests)); } } } } return scope; // ??? scope == null ? GlobalSearchScope.allScope(getProject()) : scope; ??? }
protected static VirtualFileFilter createFilter(@NotNull final Module module) { final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(module.getProject()).getFileIndex(); return new VirtualFileFilter() { public boolean accept(final VirtualFile file) { Module moduleForFile = fileIndex.getModuleForFile(file); if (moduleForFile != null) { // in module content return module.equals(moduleForFile); } if (fileIndex.isInLibraryClasses(file)) { List<OrderEntry> orderEntries = fileIndex.getOrderEntriesForFile(file); if (orderEntries.isEmpty()) { return false; } for (OrderEntry orderEntry : orderEntries) { Module ownerModule = orderEntry.getOwnerModule(); if (ownerModule != null) { if (ownerModule.equals(module)) { return true; } } } } final VirtualFile parent = file.getParent(); assert parent != null; return parent.getName().equals("standardSchemas"); } }; }
public void annotate( @NotNull final VirtualFile contentRoot, @NotNull final CoverageSuitesBundle suite, final @NotNull CoverageDataManager dataManager, @NotNull final ProjectData data, final Project project, final Annotator annotator) { if (!contentRoot.isValid()) { return; } // TODO: check name filter!!!!! final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); @SuppressWarnings("unchecked") final Set<String> files = data.getClasses().keySet(); final Map<String, String> normalizedFiles2Files = ContainerUtil.newHashMap(); for (final String file : files) { normalizedFiles2Files.put(normalizeFilePath(file), file); } collectFolderCoverage( contentRoot, dataManager, annotator, data, suite.isTrackTestFolders(), index, suite.getCoverageEngine(), ContainerUtil.newHashSet(), Collections.unmodifiableMap(normalizedFiles2Files)); }
public void execute(final String line, final int textEndOffset) { myResult = null; myInfo = parseExceptionLine(line); if (myInfo == null) { return; } myMethod = myInfo.getSecond().substring(line); final int lparenthIndex = myInfo.third.getStartOffset(); final int rparenthIndex = myInfo.third.getEndOffset(); final String fileAndLine = line.substring(lparenthIndex + 1, rparenthIndex).trim(); final int colonIndex = fileAndLine.lastIndexOf(':'); if (colonIndex < 0) return; final String lineString = fileAndLine.substring(colonIndex + 1); try { final int lineNumber = Integer.parseInt(lineString); myClass = findPositionClass(line); myFile = myClass == null ? null : (PsiFile) myClass.getContainingFile().getNavigationElement(); if (myFile == null) { // try find the file with the required name PsiFile[] files = PsiShortNamesCache.getInstance(myProject) .getFilesByName(fileAndLine.substring(0, colonIndex).trim()); if (files.length > 0) { myFile = files[0]; } } if (myFile == null) return; /* IDEADEV-4976: Some scramblers put something like SourceFile mock instead of real class name. final String filePath = fileAndLine.substring(0, colonIndex).replace('/', File.separatorChar); final int slashIndex = filePath.lastIndexOf(File.separatorChar); final String shortFileName = slashIndex < 0 ? filePath : filePath.substring(slashIndex + 1); if (!file.getName().equalsIgnoreCase(shortFileName)) return null; */ final int textStartOffset = textEndOffset - line.length(); final int highlightStartOffset = textStartOffset + lparenthIndex + 1; final int highlightEndOffset = textStartOffset + rparenthIndex; final VirtualFile virtualFile = myFile.getVirtualFile(); HyperlinkInfo linkInfo = new MyHyperlinkInfo(myProject, virtualFile, lineNumber); TextAttributes attributes = HYPERLINK_ATTRIBUTES.clone(); if (!ProjectRootManager.getInstance(myProject).getFileIndex().isInContent(virtualFile)) { Color color = UIUtil.getInactiveTextColor(); attributes.setForegroundColor(color); attributes.setEffectColor(color); } myResult = new Filter.Result(highlightStartOffset, highlightEndOffset, linkInfo, attributes); } catch (NumberFormatException e) { // } }
@NotNull private static DartLibInfo collectPackagesLibraryRoots( @NotNull final Project project, @NotNull final DartSdk sdk) { final DartLibInfo libInfo = new DartLibInfo(false); final Collection<VirtualFile> pubspecYamlFiles = FilenameIndex.getVirtualFilesByName( project, PUBSPEC_YAML, GlobalSearchScope.projectScope(project)); final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (VirtualFile pubspecFile : pubspecYamlFiles) { final VirtualFile dotPackagesFile = pubspecFile.getParent().findChild(DotPackagesFileUtil.DOT_PACKAGES); final Module module = dotPackagesFile == null ? null : fileIndex.getModuleForFile(dotPackagesFile); if (dotPackagesFile != null && !dotPackagesFile.isDirectory() && module != null && DartSdkGlobalLibUtil.isDartSdkEnabled(module)) { final Map<String, String> packagesMap = DotPackagesFileUtil.getPackagesMap(dotPackagesFile); if (packagesMap != null) { for (Map.Entry<String, String> entry : packagesMap.entrySet()) { final String packageName = entry.getKey(); final String packagePath = entry.getValue(); if (isPathOutsideProjectContent(fileIndex, packagePath)) { libInfo.addPackage(packageName, packagePath); } } } } } return libInfo; }
@Nullable public static Sdk getNewProjectJdk(WizardContext context) { if (context.getProjectJdk() != null) { return context.getProjectJdk(); } final Project project = context.getProject() == null ? ProjectManager.getInstance().getDefaultProject() : context.getProject(); final Sdk projectJdk = ProjectRootManager.getInstance(project).getProjectSdk(); if (projectJdk != null) { return projectJdk; } if (context.getProject() == null) { @Nullable final ProjectBuilder projectBuilder = context.getProjectBuilder(); return ProjectJdkTable.getInstance() .findMostRecentSdk( new Condition<Sdk>() { public boolean value(Sdk sdk) { return projectBuilder == null || projectBuilder.isSuitableSdk(sdk); } }); } return null; }
private void createTreeModel() { final PsiManager psiManager = PsiManager.getInstance(myProject); final FileIndex fileIndex = myModule != null ? ModuleRootManager.getInstance(myModule).getFileIndex() : ProjectRootManager.getInstance(myProject).getFileIndex(); fileIndex.iterateContent( new ContentIterator() { public boolean processFile(VirtualFile fileOrDir) { if (fileOrDir.isDirectory() && fileIndex.isInSourceContent(fileOrDir)) { final PsiDirectory psiDirectory = psiManager.findDirectory(fileOrDir); LOG.assertTrue(psiDirectory != null); PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory); if (aPackage != null) { addPackage(aPackage); } } return true; } }); TreeUtil.sort( myModel, new Comparator() { public int compare(Object o1, Object o2) { DefaultMutableTreeNode n1 = (DefaultMutableTreeNode) o1; DefaultMutableTreeNode n2 = (DefaultMutableTreeNode) o2; PsiNamedElement element1 = (PsiNamedElement) n1.getUserObject(); PsiNamedElement element2 = (PsiNamedElement) n2.getUserObject(); return element1.getName().compareToIgnoreCase(element2.getName()); } }); }
@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); }
@Nullable private Sdk getSdk() { if (myModule == null) { return ProjectRootManager.getInstance(myProject).getProjectSdk(); } final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule); return rootManager.getSdk(); }
@Nullable public static Sdk chooseJdk(Project project, Collection<Module> modules) { Sdk projectJdk = ProjectRootManager.getInstance(project).getProjectSdk(); if (projectJdk != null) { return projectJdk; } return chooseJdk(modules); }
private static boolean isMethodDeclarationInSource(@NotNull PsiMethod psiMethod) { if (psiMethod.getContainingFile() == null) return false; final VirtualFile virtualFile = psiMethod.getContainingFile().getVirtualFile(); if (virtualFile == null) return false; return ProjectRootManager.getInstance(psiMethod.getProject()) .getFileIndex() .isInSource(virtualFile); }
@Override public void annotateExternally( @NotNull final PsiModifierListOwner listOwner, @NotNull final String annotationFQName, @NotNull final PsiFile fromFile, final PsiNameValuePair[] value) { final Project project = myPsiManager.getProject(); final PsiFile containingFile = listOwner.getContainingFile(); if (!(containingFile instanceof PsiJavaFile)) { return; } final String packageName = ((PsiJavaFile) containingFile).getPackageName(); final VirtualFile virtualFile = containingFile.getVirtualFile(); LOG.assertTrue(virtualFile != null); final List<OrderEntry> entries = ProjectRootManager.getInstance(project).getFileIndex().getOrderEntriesForFile(virtualFile); if (entries.isEmpty()) { return; } for (final OrderEntry entry : entries) { if (entry instanceof ModuleOrderEntry) continue; VirtualFile[] virtualFiles = AnnotationOrderRootType.getFiles(entry); virtualFiles = filterByReadOnliness(virtualFiles); if (virtualFiles.length > 0) { chooseRootAndAnnotateExternally( listOwner, annotationFQName, fromFile, project, packageName, virtualFile, virtualFiles, value); } else { if (ApplicationManager.getApplication().isUnitTestMode() || ApplicationManager.getApplication().isHeadlessEnvironment()) { return; } SwingUtilities.invokeLater( new Runnable() { @Override public void run() { setupRootAndAnnotateExternally( entry, project, listOwner, annotationFQName, fromFile, packageName, virtualFile, value); } }); } break; } }
@Override public PsiFileSystemItem findRoot(final Project project, @NotNull final VirtualFile file) { final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex(); VirtualFile contentRootForFile = index.getContentRootForFile(file); return contentRootForFile != null ? PsiManager.getInstance(project).findDirectory(contentRootForFile) : null; }