@NotNull private static Collection<VirtualFile> gatherIncludeRoots( Collection<VirtualFile> goPathSourcesRoots, Set<VirtualFile> excludeRoots) { Collection<VirtualFile> includeRoots = ContainerUtil.newHashSet(); for (VirtualFile goPathSourcesDirectory : goPathSourcesRoots) { ProgressIndicatorProvider.checkCanceled(); boolean excludedRootIsAncestor = false; for (VirtualFile excludeRoot : excludeRoots) { ProgressIndicatorProvider.checkCanceled(); if (VfsUtilCore.isAncestor(excludeRoot, goPathSourcesDirectory, false)) { excludedRootIsAncestor = true; break; } } if (excludedRootIsAncestor) { continue; } for (VirtualFile file : goPathSourcesDirectory.getChildren()) { ProgressIndicatorProvider.checkCanceled(); if (file.isDirectory() && !excludeRoots.contains(file)) { includeRoots.add(file); } } } return includeRoots; }
@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; }
@Override public void beforeFileDeletion(@NotNull VirtualFileEvent event) { final VirtualFile vFile = event.getFile(); VirtualFile parent = vFile.getParent(); final PsiDirectory parentDir = getCachedDirectory(parent); if (parentDir == null) return; // do not notify listeners if parent directory was never accessed via PSI ApplicationManager.getApplication() .runWriteAction( new ExternalChangeAction() { @Override public void run() { if (!vFile.isDirectory()) { PsiFile psiFile = myFileManager.getCachedPsiFile(vFile); if (psiFile != null) { PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager); treeEvent.setParent(parentDir); treeEvent.setChild(psiFile); myManager.beforeChildRemoval(treeEvent); } } else { PsiDirectory psiDir = myFileManager.findDirectory(vFile); if (psiDir != null) { PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager); treeEvent.setParent(parentDir); treeEvent.setChild(psiDir); myManager.beforeChildRemoval(treeEvent); } } } }); }
private static void retainOnlyJarsAndDirectories(List<VirtualFile> woSdk) { for (Iterator<VirtualFile> iterator = woSdk.iterator(); iterator.hasNext(); ) { VirtualFile file = iterator.next(); final VirtualFile local = ArchiveVfsUtil.getVirtualFileForJar(file); final boolean dir = file.isDirectory(); final String name = file.getName(); if (LOG.isDebugEnabled()) { LOG.debug( "Considering: " + file.getPath() + "; local=" + local + "; dir=" + dir + "; name=" + name); } if (dir || local != null) { continue; } if (name.endsWith(".jar")) { continue; } LOG.debug("Removing"); iterator.remove(); } }
@NotNull public GeneralCommandLine createCommand( @NotNull Module module, @Nullable String jvmParams, boolean forCreation, @NotNull MvcCommand command) throws ExecutionException { final JavaParameters params = createJavaParameters(module, forCreation, false, true, jvmParams, command); addJavaHome(params, module); final GeneralCommandLine commandLine = createCommandLine(params); final VirtualFile griffonHome = getSdkRoot(module); if (griffonHome != null) { commandLine .getEnvironment() .put(getSdkHomePropertyName(), FileUtil.toSystemDependentName(griffonHome.getPath())); } final VirtualFile root = findAppRoot(module); final File ioRoot = root != null ? VfsUtilCore.virtualToIoFile(root) : new File(module.getModuleDirPath()); commandLine.setWorkDirectory(forCreation ? ioRoot.getParentFile() : ioRoot); return commandLine; }
@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 void collectCommonPluginRoots( Map<String, VirtualFile> result, @NotNull Module module, boolean refresh) { if (isCommonPluginsModule(module)) { for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) { String pluginName = getInstalledPluginNameByPath(module.getProject(), root); if (pluginName != null) { result.put(pluginName, root); } } } else { VirtualFile root = findAppRoot(module); if (root == null) return; extractPlugins( module.getProject(), root.findChild(MvcModuleStructureUtil.PLUGINS_DIRECTORY), result); extractPlugins( module.getProject(), MvcModuleStructureUtil.findFile(getCommonPluginsDir(module), refresh), result); extractPlugins( module.getProject(), MvcModuleStructureUtil.findFile(getGlobalPluginsDir(module), refresh), result); } }
private static void fillLibrary( @NotNull Library library, @NotNull Collection<VirtualFile> libraryRoots, Set<VirtualFile> exclusions) { ApplicationManager.getApplication().assertWriteAccessAllowed(); Library.ModifiableModel libraryModel = library.getModifiableModel(); for (String root : libraryModel.getUrls(OrderRootType.CLASSES)) { libraryModel.removeRoot(root, OrderRootType.CLASSES); } for (String root : libraryModel.getUrls(OrderRootType.SOURCES)) { libraryModel.removeRoot(root, OrderRootType.SOURCES); } for (VirtualFile libraryRoot : libraryRoots) { libraryModel.addRoot( libraryRoot, OrderRootType .CLASSES); // in order to consider GOPATH as library and show it in Ext. Libraries libraryModel.addRoot( libraryRoot, OrderRootType.SOURCES); // in order to find usages inside GOPATH } for (VirtualFile root : exclusions) { ((LibraryEx.ModifiableModelEx) libraryModel).addExcludedRoot(root.getUrl()); } libraryModel.commit(); }
private static void doCollectResourceDirs( AndroidFacet facet, boolean collectResCacheDirs, List<String> result, CompileContext context) { final Module module = facet.getModule(); if (collectResCacheDirs) { final AndroidPlatform platform = facet.getConfiguration().getAndroidPlatform(); final int platformToolsRevision = platform != null ? platform.getSdk().getPlatformToolsRevision() : -1; if (platformToolsRevision < 0 || platformToolsRevision > 7) { // png cache is supported since platform-tools-r8 final String resCacheDirOsPath = findResourcesCacheDirectory(module, false, context); if (resCacheDirOsPath != null) { result.add(resCacheDirOsPath); } else { LOG.info("PNG cache not found for module " + module.getName()); } } } final VirtualFile resourcesDir = AndroidAptCompiler.getResourceDirForApkCompiler(module, facet); if (resourcesDir != null) { result.add(resourcesDir.getPath()); } }
private static void fileChanged(@NotNull final Project project, @NotNull final VirtualFile file) { if (!DotPackagesFileUtil.DOT_PACKAGES.equals(file.getName())) return; if (LocalFileSystem.getInstance() != file.getFileSystem()) return; final VirtualFile parent = file.getParent(); if (parent == null || parent.findChild(PUBSPEC_YAML) == null) return; scheduleDartPackageRootsUpdate(project); }
@NotNull private static VirtualFile[] filterByReadOnliness(@NotNull VirtualFile[] files) { List<VirtualFile> result = new ArrayList<VirtualFile>(); for (VirtualFile file : files) { if (file.isInLocalFileSystem()) { result.add(file); } } return VfsUtilCore.toVirtualFileArray(result); }
public static void removeDuplicatingClasses( final Module module, @NotNull final String packageName, @NotNull String className, @Nullable File classFile, String sourceRootPath) { if (sourceRootPath == null) { return; } VirtualFile sourceRoot = LocalFileSystem.getInstance().findFileByPath(sourceRootPath); if (sourceRoot == null) { return; } final Project project = module.getProject(); final JavaPsiFacade facade = JavaPsiFacade.getInstance(project); final String interfaceQualifiedName = packageName + '.' + className; PsiClass[] classes = facade.findClasses(interfaceQualifiedName, GlobalSearchScope.moduleScope(module)); final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex(); for (PsiClass c : classes) { PsiFile psiFile = c.getContainingFile(); if (className.equals(FileUtil.getNameWithoutExtension(psiFile.getName()))) { VirtualFile virtualFile = psiFile.getVirtualFile(); if (virtualFile != null && projectFileIndex.getSourceRootForFile(virtualFile) == sourceRoot) { final String path = virtualFile.getPath(); File f = new File(path); try { f = f.getCanonicalFile(); classFile = classFile != null ? classFile.getCanonicalFile() : null; if (f != null && !f.equals(classFile) && f.exists()) { if (f.delete()) { virtualFile.refresh(true, false); } else { ApplicationManager.getApplication() .invokeLater( new Runnable() { public void run() { Messages.showErrorDialog( project, "Can't delete file " + path, CommonBundle.getErrorTitle()); } }, project.getDisposed()); } } } catch (IOException e) { LOG.info(e); } } } } }
@Nullable public VirtualFile findAppRoot(@Nullable Module module) { if (module == null) return null; String appDirName = getApplicationDirectoryName(); for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) { if (root.findChild(appDirName) != null) return root; } return null; }
private boolean isExcludeRoot(VirtualFile file) { VirtualFile parent = file.getParent(); if (parent == null) return false; Module module = myProjectRootManager.getFileIndex().getModuleForFile(parent); if (module == null) return false; VirtualFile[] excludeRoots = ModuleRootManager.getInstance(module).getExcludeRoots(); for (VirtualFile root : excludeRoots) { if (root.equals(file)) return true; } return false; }
@Nullable private Pair<Set<String>, Set<String>> getAllRoots(boolean includeSourceRoots) { if (myProject.isDefault()) return null; final Set<String> recursive = new HashSet<String>(); final Set<String> flat = new HashSet<String>(); final String projectFilePath = myProject.getProjectFilePath(); final File projectDirFile = new File(projectFilePath).getParentFile(); if (projectDirFile != null && projectDirFile.getName().equals(Project.DIRECTORY_STORE_FOLDER)) { recursive.add(projectDirFile.getAbsolutePath()); } else { flat.add(projectFilePath); final VirtualFile workspaceFile = myProject.getWorkspaceFile(); if (workspaceFile != null) { flat.add(workspaceFile.getPath()); } } for (WatchedRootsProvider extension : Extensions.getExtensions(WatchedRootsProvider.EP_NAME, myProject)) { recursive.addAll(extension.getRootsToWatch()); } final Module[] modules = ModuleManager.getInstance(myProject).getModules(); for (Module module : modules) { flat.add(module.getModuleFilePath()); final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); addRootsToTrack(moduleRootManager.getContentRootUrls(), recursive, flat); if (includeSourceRoots) { addRootsToTrack(moduleRootManager.getSourceRootUrls(), recursive, flat); } final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries(); for (OrderEntry entry : orderEntries) { if (entry instanceof LibraryOrSdkOrderEntry) { final LibraryOrSdkOrderEntry libSdkEntry = (LibraryOrSdkOrderEntry) entry; for (OrderRootType orderRootType : OrderRootType.getAllTypes()) { addRootsToTrack(libSdkEntry.getRootUrls(orderRootType), recursive, flat); } } } } return Pair.create(recursive, flat); }
@Nullable public VirtualFile findAppDirectory(@Nullable PsiElement element) { if (element == null) return null; PsiFile containingFile = element.getContainingFile().getOriginalFile(); VirtualFile file = containingFile.getVirtualFile(); if (file == null) return null; ProjectFileIndex index = ProjectRootManager.getInstance(containingFile.getProject()).getFileIndex(); VirtualFile root = index.getContentRootForFile(file); if (root == null) return null; return root.findChild(getApplicationDirectoryName()); }
private void appendChosenAnnotationsRoot( @NotNull final OrderEntry entry, @NotNull final VirtualFile vFile) { if (entry instanceof LibraryOrderEntry) { Library library = ((LibraryOrderEntry) entry).getLibrary(); LOG.assertTrue(library != null); final ModifiableRootModel rootModel = ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel(); final Library.ModifiableModel model = library.getModifiableModel(); model.addRoot(vFile, AnnotationOrderRootType.getInstance()); model.commit(); rootModel.commit(); } else if (entry instanceof ModuleSourceOrderEntry) { final ModifiableRootModel model = ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel(); final JavaModuleExternalPaths extension = model.getModuleExtension(JavaModuleExternalPaths.class); extension.setExternalAnnotationUrls( ArrayUtil.mergeArrays(extension.getExternalAnnotationsUrls(), vFile.getUrl())); model.commit(); } else if (entry instanceof JdkOrderEntry) { final SdkModificator sdkModificator = ((JdkOrderEntry) entry).getJdk().getSdkModificator(); sdkModificator.addRoot(vFile, AnnotationOrderRootType.getInstance()); sdkModificator.commitChanges(); } myExternalAnnotations.clear(); }
public static void removeExcludedRoot(Module module, VirtualFile root) { ModuleRootModificationUtil.updateModel( module, model -> { ContentEntry entry = findContentEntryWithAssertion(model, root); entry.removeExcludeFolder(root.getUrl()); }); }
private static void unexcludeRootIfNeccessary( @NotNull VirtualFile root, @NotNull ModuleRootManager manager) { Set<VirtualFile> excludedRoots = new HashSet<VirtualFile>(Arrays.asList(manager.getExcludeRoots())); VirtualFile excludedRoot = root; while (excludedRoot != null && !excludedRoots.contains(excludedRoot)) { excludedRoot = excludedRoot.getParent(); } if (excludedRoot == null) { return; } Set<VirtualFile> rootsToExclude = new HashSet<VirtualFile>(); collectChildrenRecursively(excludedRoot, root, rootsToExclude); final ModifiableRootModel model = manager.getModifiableModel(); ContentEntry contentEntry = findContentEntryForRoot(model, excludedRoot); if (contentEntry != null) { ExcludeFolder excludedFolder = null; for (ExcludeFolder folder : contentEntry.getExcludeFolders()) { if (folder.getFile() == excludedRoot) { excludedFolder = folder; break; } } if (excludedFolder != null) { contentEntry.removeExcludeFolder(excludedFolder); } for (VirtualFile rootToExclude : rootsToExclude) { if (!excludedRoots.contains(rootToExclude)) { contentEntry.addExcludeFolder(rootToExclude); } } } ApplicationManager.getApplication() .runWriteAction( new Runnable() { @Override public void run() { model.commit(); } }); }
private static void collectChildrenRecursively( @NotNull VirtualFile root, @NotNull VirtualFile anchor, @NotNull Collection<VirtualFile> result) { if (root == anchor) { return; } VirtualFile parent = anchor.getParent(); if (parent == null) { return; } for (VirtualFile child : parent.getChildren()) { if (child != anchor) { result.add(child); } } if (parent != root) { collectChildrenRecursively(root, parent, result); } }
public static VirtualFile createTestProjectStructure( String tempName, Module module, String rootPath, Collection<File> filesToDelete, boolean addProjectRoots) throws IOException { File dir = FileUtil.createTempDirectory(tempName, null, false); filesToDelete.add(dir); VirtualFile vDir = LocalFileSystem.getInstance() .refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/')); assert vDir != null && vDir.isDirectory() : dir; PlatformTestCase.synchronizeTempDirVfs(vDir); EdtTestUtil.runInEdtAndWait( () -> { AccessToken token = WriteAction.start(); try { if (rootPath != null) { VirtualFile vDir1 = LocalFileSystem.getInstance() .findFileByPath(rootPath.replace(File.separatorChar, '/')); if (vDir1 == null) { throw new Exception(rootPath + " not found"); } VfsUtil.copyDirectory(null, vDir1, vDir, null); } if (addProjectRoots) { addSourceContentToRoots(module, vDir); } } finally { token.finish(); } }); return vDir; }
public static void removeSourceRoot(Module module, VirtualFile root) { ModuleRootModificationUtil.updateModel( module, model -> { ContentEntry entry = findContentEntryWithAssertion(model, root); for (SourceFolder sourceFolder : entry.getSourceFolders()) { if (root.equals(sourceFolder.getFile())) { entry.removeSourceFolder(sourceFolder); break; } } }); }
private void extractPlugins( Project project, @Nullable VirtualFile pluginRoot, Map<String, VirtualFile> res) { if (pluginRoot != null) { VirtualFile[] children = pluginRoot.getChildren(); if (children != null) { for (VirtualFile child : children) { String pluginName = getInstalledPluginNameByPath(project, child); if (pluginName != null) { res.put(pluginName, child); } } } } }
public static VirtualFile createTestProjectStructure( String tempName, final Module module, final String rootPath, final Collection<File> filesToDelete, final boolean addProjectRoots) throws Exception { File dir = FileUtil.createTempDirectory(tempName, null, false); filesToDelete.add(dir); final VirtualFile vDir = LocalFileSystem.getInstance() .refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/')); assert vDir != null && vDir.isDirectory() : dir; Project project = module != null ? module.getProject() : null; new WriteCommandAction.Simple(project) { @Override protected void run() throws Throwable { if (rootPath != null) { VirtualFile vDir1 = LocalFileSystem.getInstance() .findFileByPath(rootPath.replace(File.separatorChar, '/')); if (vDir1 == null) { throw new Exception(rootPath + " not found"); } VfsUtil.copyDirectory(null, vDir1, vDir, null); } if (addProjectRoots) { addSourceContentToRoots(module, vDir); } } }.execute().throwException(); return vDir; }
protected List<File> getImplicitClasspathRoots(@NotNull Module module) { final List<File> toExclude = new ArrayList<File>(); VirtualFile sdkRoot = getSdkRoot(module); if (sdkRoot != null) toExclude.add(VfsUtil.virtualToIoFile(sdkRoot)); ContainerUtil.addIfNotNull(getCommonPluginsDir(module), toExclude); final VirtualFile appRoot = findAppRoot(module); if (appRoot != null) { VirtualFile pluginDir = appRoot.findChild(MvcModuleStructureUtil.PLUGINS_DIRECTORY); if (pluginDir != null) toExclude.add(VfsUtil.virtualToIoFile(pluginDir)); VirtualFile libDir = appRoot.findChild("lib"); if (libDir != null) toExclude.add(VfsUtil.virtualToIoFile(libDir)); } final Library library = MvcModuleStructureUtil.findUserLibrary(module, getUserLibraryName()); if (library != null) { for (VirtualFile file : library.getFiles(OrderRootType.CLASSES)) { toExclude.add(VfsUtil.virtualToIoFile(PathUtil.getLocalFile(file))); } } return toExclude; }
@Nullable private PsiFile createFileCopyWithNewName(VirtualFile vFile, String name) { // TODO[ik] remove this. Event handling and generation must be in view providers mechanism since // we // need to track changes in _all_ psi views (e.g. namespace changes in XML) final FileTypeManager instance = FileTypeManager.getInstance(); if (instance.isFileIgnored(name)) return null; final FileType fileTypeByFileName = instance.getFileTypeByFileName(name); final Document document = FileDocumentManager.getInstance().getDocument(vFile); return PsiFileFactory.getInstance(myManager.getProject()) .createFileFromText( name, fileTypeByFileName, document != null ? document.getCharsSequence() : "", vFile.getModificationStamp(), true, false); }
public static void addAvailableSystemScripts( final Collection<String> result, @NotNull Module module) { VirtualFile scriptRoot = null; GlobalSearchScope searchScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, false); for (PsiClass aClass : JavaPsiFacade.getInstance(module.getProject()).findClasses("CreateApp_", searchScope)) { PsiClass superClass = aClass.getSuperClass(); if (superClass != null && GroovyCommonClassNames.GROOVY_LANG_SCRIPT.equals(superClass.getQualifiedName())) { PsiFile psiFile = aClass.getContainingFile(); if (psiFile != null) { VirtualFile file = psiFile.getVirtualFile(); if (file != null && file.getFileSystem() instanceof ArchiveFileSystem) { VirtualFile parent = file.getParent(); if (parent != null && parent.findChild("Console.class") != null) { scriptRoot = parent; break; } } } } } if (scriptRoot == null) return; Pattern scriptPattern = Pattern.compile("([A-Za-z0-9]+)_?\\.class"); for (VirtualFile file : scriptRoot.getChildren()) { Matcher matcher = scriptPattern.matcher(file.getName()); if (matcher.matches()) { result.add(GroovyNamesUtil.camelToSnake(matcher.group(1))); } } }
public static void addAvailableScripts( final Collection<String> result, @Nullable final VirtualFile root) { if (root == null || !root.isDirectory()) { return; } final VirtualFile scripts = root.findChild("scripts"); if (scripts == null || !scripts.isDirectory()) { return; } for (VirtualFile child : scripts.getChildren()) { if (isScriptFile(child)) { result.add(GroovyNamesUtil.camelToSnake(child.getNameWithoutExtension())); } } }
@Nullable public String getInstalledPluginNameByPath(Project project, @NotNull VirtualFile pluginPath) { VirtualFile pluginXml = pluginPath.findChild("plugin.xml"); if (pluginXml == null) return null; PsiFile pluginXmlPsi = PsiManager.getInstance(project).findFile(pluginXml); if (!(pluginXmlPsi instanceof XmlFile)) return null; XmlTag rootTag = ((XmlFile) pluginXmlPsi).getRootTag(); if (rootTag == null || !"plugin".equals(rootTag.getName())) return null; XmlAttribute attrName = rootTag.getAttribute("name"); if (attrName == null) return null; String res = attrName.getValue(); if (res == null) return null; res = res.trim(); if (res.length() == 0) return null; return res; }
private static boolean isScriptFile(VirtualFile virtualFile) { return !virtualFile.isDirectory() && isScriptFileName(virtualFile.getName()); }