@Nullable public static VirtualFile findFileByIoFile(@NotNull File file, boolean refreshIfNeeded) { LocalFileSystem fileSystem = LocalFileSystem.getInstance(); VirtualFile virtualFile = fileSystem.findFileByIoFile(file); if (virtualFile == null && refreshIfNeeded) { virtualFile = fileSystem.refreshAndFindFileByIoFile(file); } return virtualFile; }
@Nullable public static VirtualFile getVirtualFileWithRefresh(final File file) { if (file == null) return null; final LocalFileSystem lfs = LocalFileSystem.getInstance(); VirtualFile result = lfs.findFileByIoFile(file); if (result == null) { result = lfs.refreshAndFindFileByIoFile(file); } return result; }
@SuppressWarnings({"HardCodedStringLiteral"}) @Nullable public static VirtualFile findRelativeFile(@NotNull String uri, @Nullable VirtualFile base) { if (base != null) { if (!base.isValid()) { LOG.error("Invalid file name: " + base.getName() + ", url: " + uri); } } uri = uri.replace('\\', '/'); if (uri.startsWith("file:///")) { uri = uri.substring("file:///".length()); if (!SystemInfo.isWindows) uri = "/" + uri; } else if (uri.startsWith("file:/")) { uri = uri.substring("file:/".length()); if (!SystemInfo.isWindows) uri = "/" + uri; } else if (uri.startsWith("file:")) { uri = uri.substring("file:".length()); } VirtualFile file = null; if (uri.startsWith("jar:file:/")) { uri = uri.substring("jar:file:/".length()); if (!SystemInfo.isWindows) uri = "/" + uri; file = VirtualFileManager.getInstance().findFileByUrl(JarFileSystem.PROTOCOL_PREFIX + uri); } else { if (!SystemInfo.isWindows && StringUtil.startsWithChar(uri, '/')) { file = LocalFileSystem.getInstance().findFileByPath(uri); } else if (SystemInfo.isWindows && uri.length() >= 2 && Character.isLetter(uri.charAt(0)) && uri.charAt(1) == ':') { file = LocalFileSystem.getInstance().findFileByPath(uri); } } if (file == null && uri.contains(JarFileSystem.JAR_SEPARATOR)) { file = JarFileSystem.getInstance().findFileByPath(uri); if (file == null && base == null) { file = VirtualFileManager.getInstance().findFileByUrl(uri); } } if (file == null) { if (base == null) return LocalFileSystem.getInstance().findFileByPath(uri); if (!base.isDirectory()) base = base.getParent(); if (base == null) return LocalFileSystem.getInstance().findFileByPath(uri); file = VirtualFileManager.getInstance().findFileByUrl(base.getUrl() + "/" + uri); if (file == null) return null; } return file; }
private static VirtualFile doCreateDirectoriesIfMissing(String dir) throws IOException { final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(dir); if (file == null) { int pos = dir.lastIndexOf('/'); if (pos < 0) return null; VirtualFile parent = createDirectoryIfMissing(dir.substring(0, pos)); if (parent == null) return null; final String dirName = dir.substring(pos + 1); return parent.createChildDirectory(LocalFileSystem.getInstance(), dirName); } return file; }
public void testSubst() throws Exception { if (!SystemInfo.isWindows) { System.err.println("Ignored: Windows required"); return; } File targetDir = createTestDir("top"); File subDir = createTestDir(targetDir, "sub"); File file = createTestFile(subDir, "test.txt"); File rootFile = createSubst(targetDir.getAbsolutePath()); VirtualDirectoryImpl.allowRootAccess(rootFile.getPath()); VirtualFile vfsRoot = myFileSystem.findFileByIoFile(rootFile); try { assertNotNull(rootFile.getPath(), vfsRoot); File substDir = new File(rootFile, subDir.getName()); File substFile = new File(substDir, file.getName()); refresh(targetDir); refresh(substDir); LocalFileSystem.WatchRequest request = watch(substDir); try { myAccept = true; FileUtil.writeToFile(file, "new content"); assertEvent(VFileContentChangeEvent.class, substFile.getAbsolutePath()); LocalFileSystem.WatchRequest request2 = watch(targetDir); try { myAccept = true; FileUtil.delete(file); assertEvent(VFileDeleteEvent.class, file.getAbsolutePath(), substFile.getAbsolutePath()); } finally { unwatch(request2); } myAccept = true; FileUtil.writeToFile(file, "re-creation"); assertEvent(VFileCreateEvent.class, substFile.getAbsolutePath()); } finally { unwatch(request); } } finally { delete(targetDir); IoTestUtil.deleteSubst(rootFile.getPath()); if (vfsRoot != null) { ((NewVirtualFile) vfsRoot).markDirty(); myFileSystem.refresh(false); } VirtualDirectoryImpl.disallowRootAccess(rootFile.getPath()); } }
@Nullable public static VirtualFile getDirectory(@NotNull final FindModel findModel) { String directoryName = findModel.getDirectoryName(); if (findModel.isProjectScope() || StringUtil.isEmpty(directoryName)) { return null; } String path = directoryName.replace(File.separatorChar, '/'); VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(path); if (virtualFile == null || !virtualFile.isDirectory()) { virtualFile = null; for (LocalFileProvider provider : ((VirtualFileManagerEx) VirtualFileManager.getInstance()).getLocalFileProviders()) { VirtualFile file = provider.findLocalVirtualFileByPath(path); if (file != null && file.isDirectory()) { if (file.getChildren().length > 0) { virtualFile = file; break; } if (virtualFile == null) { virtualFile = file; } } } } return virtualFile; }
@Override protected void setUp() throws Exception { LOG.debug("================== setting up " + getName() + " =================="); super.setUp(); myFileSystem = LocalFileSystem.getInstance(); assertNotNull(myFileSystem); myWatcher = ((LocalFileSystemImpl) myFileSystem).getFileWatcher(); assertNotNull(myWatcher); assertFalse(myWatcher.isOperational()); myWatcher.startup(myNotifier); assertTrue(myWatcher.isOperational()); myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, getProject()); myTimeout = NATIVE_PROCESS_DELAY; myConnection = ApplicationManager.getApplication().getMessageBus().connect(); myConnection.subscribe( VirtualFileManager.VFS_CHANGES, new BulkFileListener.Adapter() { @Override public void after(@NotNull List<? extends VFileEvent> events) { synchronized (myEvents) { myEvents.addAll(events); } } }); ((LocalFileSystemImpl) myFileSystem).cleanupForNextTest(); LOG = FileWatcher.getLog(); LOG.debug("================== setting up " + getName() + " =================="); }
private List<VFileEvent> getEvents(String msg, @Nullable Runnable action) { LOG.debug("** waiting for " + msg); myAccept = true; if (action != null) { action.run(); } int timeout = myTimeout; try { synchronized (myWaiter) { //noinspection WaitNotInLoop myWaiter.wait(timeout); } } catch (InterruptedException e) { LOG.warn(e); } LOG.debug("** waited for " + timeout); myFileSystem.refresh(false); ArrayList<VFileEvent> result; synchronized (myEvents) { result = new ArrayList<VFileEvent>(myEvents); myEvents.clear(); } LOG.debug("** events: " + result.size()); return result; }
private void waitForFileWatcher(@NotNull Project project) { LocalFileSystem fs = LocalFileSystem.getInstance(); if (!(fs instanceof LocalFileSystemImpl)) return; final FileWatcher watcher = ((LocalFileSystemImpl) fs).getFileWatcher(); if (!watcher.isOperational() || !watcher.isSettingRoots()) return; LOG.info("FW/roots waiting started"); Task.Modal task = new Task.Modal(project, ProjectBundle.message("project.load.progress"), true) { @Override public void run(@NotNull ProgressIndicator indicator) { indicator.setIndeterminate(true); indicator.setText(ProjectBundle.message("project.load.waiting.watcher")); if (indicator instanceof ProgressWindow) { ((ProgressWindow) indicator).setCancelButtonText(CommonBundle.message("button.skip")); } while (watcher.isSettingRoots() && !indicator.isCanceled()) { TimeoutUtil.sleep(10); } LOG.info("FW/roots waiting finished"); } }; myProgressManager.run(task); }
public static void createSourceRootIfNotExist( @NotNull final String path, @NotNull final Module module) { ApplicationManager.getApplication().assertIsDispatchThread(); final File rootFile = new File(path); final boolean created; if (!rootFile.exists()) { if (!rootFile.mkdirs()) return; created = true; } else { created = false; } final Project project = module.getProject(); Module genModule = module; final AndroidFacet facet = AndroidFacet.getInstance(genModule); if (facet != null && facet.getConfiguration().LIBRARY_PROJECT) { removeGenModule(module); } if (project.isDisposed() || genModule.isDisposed()) { return; } final VirtualFile root; if (created) { root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(rootFile); } else { root = LocalFileSystem.getInstance().findFileByIoFile(rootFile); } if (root != null) { final ModuleRootManager manager = ModuleRootManager.getInstance(genModule); unexcludeRootIfNeccessary(root, manager); for (VirtualFile existingRoot : manager.getSourceRoots()) { if (existingRoot == root) return; } ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { addSourceRoot(manager, root); } }); } }
public static void attachJdkAnnotations(@NotNull SdkModificator modificator) { LocalFileSystem lfs = LocalFileSystem.getInstance(); List<String> pathsChecked = new ArrayList<>(); // community idea under idea String path = FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/java/jdkAnnotations"; VirtualFile root = lfs.findFileByPath(path); pathsChecked.add(path); if (root == null) { // idea under idea path = FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/community/java/jdkAnnotations"; root = lfs.findFileByPath(path); pathsChecked.add(path); } if (root == null) { // build String url = "jar://" + FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/lib/jdkAnnotations.jar!/"; root = VirtualFileManager.getInstance().findFileByUrl(url); pathsChecked.add( FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/lib/jdkAnnotations.jar"); } if (root == null) { String msg = "Paths checked:\n"; for (String p : pathsChecked) { File file = new File(p); msg += "Path: '" + p + "' " + (file.exists() ? "Found" : "Not found") + "; directory children: " + Arrays.toString(file.getParentFile().listFiles()) + "\n"; } LOG.error("JDK annotations not found", msg); return; } OrderRootType annoType = AnnotationOrderRootType.getInstance(); modificator.removeRoot(root, annoType); modificator.addRoot(root, annoType); }
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); }
@Nullable private static String getProjectPath(final Project project) { final String path = project.getPresentableUrl(); if (path == null) { return null; } final VirtualFile vFile = LocalFileSystem.getInstance().findFileByPath(path); return vFile != null ? vFile.getPath() : null; }
@NotNull private VirtualFilePointer create( @Nullable VirtualFile file, @NotNull String url, @NotNull final Disposable parentDisposable, @Nullable VirtualFilePointerListener listener) { String protocol; VirtualFileSystem fileSystem; if (file == null) { protocol = VirtualFileManager.extractProtocol(url); fileSystem = myVirtualFileManager.getFileSystem(protocol); } else { protocol = null; fileSystem = file.getFileSystem(); } if (fileSystem == TempFileSystem.getInstance()) { // for tests, recreate always since VirtualFile found = fileSystem == null ? null : file != null ? file : VirtualFileManager.getInstance().findFileByUrl(url); return new IdentityVirtualFilePointer(found, url); } if (fileSystem != LocalFileSystem.getInstance() && fileSystem != JarFileSystem.getInstance()) { // we are unable to track alien file systems for now VirtualFile found = fileSystem == null ? null : file != null ? file : VirtualFileManager.getInstance().findFileByUrl(url); // if file is null, this pointer will never be alive return getOrCreateIdentity(url, found); } String path; if (file == null) { path = VirtualFileManager.extractPath(url); path = cleanupPath(path, protocol); url = VirtualFileManager.constructUrl(protocol, path); } else { path = file.getPath(); // url has come from VirtualFile.getUrl() and is good enough } VirtualFilePointerImpl pointer = getOrCreate(file, url, parentDisposable, listener, path); int newCount = pointer.incrementUsageCount(); if (newCount == 1) { Disposer.register(parentDisposable, pointer); } else { // already registered register(parentDisposable, pointer); } return pointer; }
public static String getUrlForLibraryRoot(@NotNull File libraryRoot) { String path = FileUtil.toSystemIndependentName(libraryRoot.getAbsolutePath()); if (FileTypeManager.getInstance().getFileTypeByFileName(libraryRoot.getName()) == FileTypes.ARCHIVE) { return VirtualFileManager.constructUrl( JarFileSystem.getInstance().getProtocol(), path + JarFileSystem.JAR_SEPARATOR); } else { return VirtualFileManager.constructUrl(LocalFileSystem.getInstance().getProtocol(), path); } }
public void testRelativePath() throws Exception { final File root = new File(PathManagerEx.getTestDataPath()); final File testRoot = new File(new File(root, "vfs"), "relativePath"); VirtualFile vTestRoot = LocalFileSystem.getInstance().findFileByIoFile(testRoot); assertNotNull(vTestRoot); assertTrue(vTestRoot.isDirectory()); final File subDir = new File(testRoot, "subDir"); final VirtualFile vSubDir = LocalFileSystem.getInstance().findFileByIoFile(subDir); assertNotNull(vSubDir); final File subSubDir = new File(subDir, "subSubDir"); final VirtualFile vSubSubDir = LocalFileSystem.getInstance().findFileByIoFile(subSubDir); assertNotNull(vSubSubDir); assertEquals("subDir", VfsUtilCore.getRelativePath(vSubDir, vTestRoot, '/')); assertEquals("subDir/subSubDir", VfsUtilCore.getRelativePath(vSubSubDir, vTestRoot, '/')); assertEquals("", VfsUtilCore.getRelativePath(vTestRoot, vTestRoot, '/')); }
@Nullable private static VirtualFile findDocs(@NotNull File file, @NotNull String relativePath) { file = new File( file.getAbsolutePath() + File.separator + relativePath.replace('/', File.separatorChar)); if (!file.exists() || !file.isDirectory()) return null; String path = file.getAbsolutePath().replace(File.separatorChar, '/'); return LocalFileSystem.getInstance().findFileByPath(path); }
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); } } } } }
public static VirtualFile createDirectoryIfMissing(VirtualFile parent, String relativePath) throws IOException { for (String each : StringUtil.split(relativePath, "/")) { VirtualFile child = parent.findChild(each); if (child == null) { child = parent.createChildDirectory(LocalFileSystem.getInstance(), each); } parent = child; } return parent; }
public void testFindChildWithTrailingSpace() throws IOException { File tempDir = createTempDirectory(); VirtualFile vDir = LocalFileSystem.getInstance().findFileByIoFile(tempDir); assertNotNull(vDir); assertTrue(vDir.isDirectory()); VirtualFile child = vDir.findChild(" "); assertNull(child); UsefulTestCase.assertEmpty(vDir.getChildren()); }
@Nullable private static VirtualFile findFileFor(final File root) { File current = root; while (current != null) { final VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(root); if (vFile != null) return vFile; current = current.getParentFile(); } return null; }
public static Sdk addJdkAnnotations(Sdk sdk) { String path = FileUtil.toSystemIndependentName(PlatformTestUtil.getCommunityPath()) + "/java/jdkAnnotations"; VirtualFile root = LocalFileSystem.getInstance().findFileByPath(path); if (root != null) { SdkModificator sdkModificator = sdk.getSdkModificator(); sdkModificator.addRoot(root, AnnotationOrderRootType.getInstance()); sdkModificator.commitChanges(); } return sdk; }
private static boolean isPathOutsideProjectContent( @NotNull final ProjectFileIndex fileIndex, @NotNull String path) { while (!path.isEmpty()) { final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); if (file == null) { path = PathUtil.getParentPath(path); } else { return !fileIndex.isInContent(file); } } return false; }
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; }
private VirtualFile refresh(File file) { VirtualFile vFile = myFileSystem.refreshAndFindFileByIoFile(file); assertNotNull(file.toString(), vFile); VfsUtilCore.visitChildrenRecursively( vFile, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { file.getChildren(); return true; } }); return vFile; }
private void delete(File file) throws IOException { VirtualFile vFile = myFileSystem.findFileByIoFile(file); if (vFile != null) { AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(getClass()); try { vFile.delete(this); } finally { token.finish(); } } if (file.exists()) { FileUtil.delete(file); } }
public static void addLibrary( Module module, ModifiableRootModel model, String libName, String libPath, String... jarArr) { List<VirtualFile> classesRoots = new ArrayList<>(); for (String jar : jarArr) { if (!libPath.endsWith("/") && !jar.startsWith("/")) { jar = "/" + jar; } String path = libPath + jar; VirtualFile root; if (path.endsWith(".jar")) { root = JarFileSystem.getInstance().refreshAndFindFileByPath(path + "!/"); } else { root = LocalFileSystem.getInstance().refreshAndFindFileByPath(path); } assert root != null : "Library root folder not found: " + path + "!/"; classesRoots.add(root); } addProjectLibrary(module, model, libName, classesRoots, Collections.emptyList()); }
/** * Delete a local path with asyncDiskService if available, or otherwise synchronously with local * file system. */ private static void deleteLocalPath( MRAsyncDiskService asyncDiskService, LocalFileSystem fs, Path path) throws IOException { boolean deleted = false; if (asyncDiskService != null) { // Try to delete using asyncDiskService String localPathToDelete = path.toUri().getPath(); deleted = asyncDiskService.moveAndDeleteAbsolutePath(localPathToDelete); if (!deleted) { LOG.warn( "Cannot find DistributedCache path " + localPathToDelete + " on any of the asyncDiskService volumes!"); } } if (!deleted) { // If no asyncDiskService, we will delete the files synchronously fs.delete(path, true); } LOG.info("Deleted path " + path); }
private static VirtualFile[] getFilesToCheckReadonlyStatus( GeneratingCompiler.GenerationItem[] items) { List<VirtualFile> filesToCheck = new ArrayList<VirtualFile>(); for (GeneratingCompiler.GenerationItem item : items) { if (item instanceof AndroidAptCompiler.AptGenerationItem) { final Set<File> generatedFiles = ((AndroidAptCompiler.AptGenerationItem) item).getGeneratedFiles().keySet(); for (File generatedFile : generatedFiles) { if (generatedFile.exists()) { VirtualFile generatedVFile = LocalFileSystem.getInstance().findFileByIoFile(generatedFile); if (generatedVFile != null) { filesToCheck.add(generatedVFile); } } } } } return VfsUtil.toVirtualFileArray(filesToCheck); }
@Nullable @SuppressWarnings("HardCodedStringLiteral") private static VirtualFile findSources(File file, final String srcName) { File jarFile = new File(file, srcName + ".jar"); if (!jarFile.exists()) { jarFile = new File(file, srcName + ".zip"); } if (jarFile.exists()) { VirtualFile vFile = findInJar(jarFile, "src"); if (vFile != null) return vFile; // try 1.4 format vFile = findInJar(jarFile, ""); return vFile; } else { File srcDir = new File(file, "src"); if (!srcDir.exists() || !srcDir.isDirectory()) return null; String path = srcDir.getAbsolutePath().replace(File.separatorChar, '/'); return LocalFileSystem.getInstance().findFileByPath(path); } }