@NotNull private Trinity<String[], VirtualFile[], VirtualFile[]> cacheThings() { Trinity<String[], VirtualFile[], VirtualFile[]> result; if (myList.isEmpty()) { result = EMPTY; } else { VirtualFilePointer[] vf = myList.toArray(new VirtualFilePointer[myList.size()]); List<VirtualFile> cachedFiles = new ArrayList<VirtualFile>(vf.length); List<String> cachedUrls = new ArrayList<String>(vf.length); List<VirtualFile> cachedDirectories = new ArrayList<VirtualFile>(vf.length / 3); boolean allFilesAreDirs = true; for (VirtualFilePointer v : vf) { VirtualFile file = v.getFile(); String url = v.getUrl(); cachedUrls.add(url); if (file != null) { cachedFiles.add(file); if (file.isDirectory()) { cachedDirectories.add(file); } else { allFilesAreDirs = false; } } } VirtualFile[] directories = VfsUtilCore.toVirtualFileArray(cachedDirectories); VirtualFile[] files = allFilesAreDirs ? directories : VfsUtilCore.toVirtualFileArray(cachedFiles); String[] urlsArray = ArrayUtil.toStringArray(cachedUrls); result = Trinity.create(urlsArray, files, directories); } myCachedThings = result; myTimeStampOfCachedThings = myVirtualFilePointerManager.getModificationCount(); return result; }
final boolean allowVisitChildren(@NotNull VirtualFile file) { if (!file.is(VFileProperty.SYMLINK)) { return true; } if (!myFollowSymLinks || VfsUtilCore.isInvalidLink(file)) { return false; } VirtualFile target = file.getCanonicalFile(); List<VirtualFile> links = myVisitedTargets.get(target); if (links == null) { myVisitedTargets.put(target, ContainerUtil.newSmartList(file)); return true; } boolean hasLoop = false; for (VirtualFile link : links) { if (VfsUtilCore.isAncestor(link, file, true)) { hasLoop = true; break; } } links.add(file); return !hasLoop; }
@Override public <S> List<S> filterUniqueRoots( final List<S> in, final Convertor<S, VirtualFile> convertor) { Collections.sort( in, new ComparatorDelegate<S, VirtualFile>(convertor, FilePathComparator.getInstance())); for (int i = 1; i < in.size(); i++) { final S sChild = in.get(i); final VirtualFile child = convertor.convert(sChild); final VirtualFile childRoot = GitUtil.gitRootOrNull(child); if (childRoot == null) { // non-git file actually, skip it continue; } for (int j = i - 1; j >= 0; --j) { final S sParent = in.get(j); final VirtualFile parent = convertor.convert(sParent); // the method check both that parent is an ancestor of the child and that they share common // git root if (VfsUtilCore.isAncestor(parent, child, false) && VfsUtilCore.isAncestor(childRoot, parent, false)) { in.remove(i); //noinspection AssignmentToForLoopParameter --i; break; } } } return in; }
@Nullable private VirtualFile setupGradleSettingsFile( @NotNull VirtualFile modelContentRootDir, @NotNull ModifiableRootModel model) throws ConfigurationException { VirtualFile file = null; if (myWizardContext.isCreatingNewProject()) { final String moduleDirName = VfsUtilCore.getRelativePath(modelContentRootDir, model.getProject().getBaseDir(), '/'); file = getExternalProjectConfigFile( model.getProject().getBasePath(), GradleConstants.SETTINGS_FILE_NAME); if (file == null) return null; Map<String, String> attributes = ContainerUtil.newHashMap(); final String projectName = model.getProject().getName(); attributes.put(TEMPLATE_ATTRIBUTE_PROJECT_NAME, projectName); attributes.put(TEMPLATE_ATTRIBUTE_MODULE_DIR_NAME, moduleDirName); attributes.put(TEMPLATE_ATTRIBUTE_MODULE_NAME, model.getModule().getName()); saveFile(file, TEMPLATE_GRADLE_SETTINGS, attributes); } else { Map<String, Module> moduleMap = ContainerUtil.newHashMap(); for (Module module : ModuleManager.getInstance(model.getProject()).getModules()) { for (ContentEntry contentEntry : model.getContentEntries()) { if (contentEntry.getFile() != null) { moduleMap.put(contentEntry.getFile().getPath(), module); } } } VirtualFile virtualFile = modelContentRootDir; Module module = null; while (virtualFile != null && module == null) { module = moduleMap.get(virtualFile.getPath()); virtualFile = virtualFile.getParent(); } if (module != null) { String rootProjectPath = module.getOptionValue(ExternalSystemConstants.ROOT_PROJECT_PATH_KEY); if (!StringUtil.isEmpty(rootProjectPath)) { VirtualFile rootProjectFile = VfsUtil.findFileByIoFile(new File(rootProjectPath), true); if (rootProjectFile == null) return null; final String moduleDirName = VfsUtilCore.getRelativePath(modelContentRootDir, rootProjectFile, '/'); file = getExternalProjectConfigFile(rootProjectPath, GradleConstants.SETTINGS_FILE_NAME); if (file == null) return null; Map<String, String> attributes = ContainerUtil.newHashMap(); attributes.put(TEMPLATE_ATTRIBUTE_MODULE_DIR_NAME, moduleDirName); attributes.put(TEMPLATE_ATTRIBUTE_MODULE_NAME, model.getModule().getName()); appendToFile(file, TEMPLATE_GRADLE_SETTINGS_MERGE, attributes); } } } return file; }
private int compareByLibDir( @NotNull VirtualFile m1File, @NotNull VirtualFile m2File, @Nullable VirtualFile libDir) { if (libDir == null) return COMPARE_NO_RESULT; boolean m1InLib = VfsUtilCore.isAncestor(libDir, m1File, true); boolean m2InLib = VfsUtilCore.isAncestor(libDir, m2File, true); if (m1InLib || m2InLib) { return (m1InLib ? -1 : 0) + (m2InLib ? 1 : 0); } return COMPARE_NO_RESULT; }
public void testFileLength() throws Exception { File file = FileUtil.createTempFile("test", "txt"); FileUtil.writeToFile(file, "hello"); VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file); assertNotNull(virtualFile); String s = VfsUtilCore.loadText(virtualFile); assertEquals("hello", s); assertEquals(5, virtualFile.getLength()); FileUtil.writeToFile(file, "new content"); ((PersistentFSImpl) PersistentFS.getInstance()).cleanPersistedContents(); s = VfsUtilCore.loadText(virtualFile); assertEquals("new content", s); assertEquals(11, virtualFile.getLength()); }
@Nullable protected FileCoverageInfo collectBaseFileCoverage( @NotNull final VirtualFile file, @NotNull final Annotator annotator, @NotNull final ProjectData projectData, @NotNull final Map<String, String> normalizedFiles2Files) { final String filePath = normalizeFilePath(file.getPath()); // process file final FileCoverageInfo info; final ClassData classData = getClassData(filePath, projectData, normalizedFiles2Files); if (classData != null) { // fill info from coverage data info = fileInfoForCoveredFile(classData); } else { // file wasn't mentioned in coverage information info = fillInfoForUncoveredFile(VfsUtilCore.virtualToIoFile(file)); } if (info != null) { annotator.annotateFile(filePath, info); } return info; }
public void actionPerformed(final ActionEvent e) { final FileChooserDescriptor descriptor = new FilterFileChooserDescriptor( "Select", "Select a file to import", new FileFilter() { @Override public boolean accept(final File f) { return f.isDirectory() || "xml".equalsIgnoreCase(FileUtilRt.getExtension(f.getAbsolutePath())); } @Override public String getDescription() { return "*.xml"; } }); final Component parent = SwingUtilities.getRoot(_importFile); final VirtualFile toSelect = LocalFileSystem.getInstance().findFileByPath(_importDir); final VirtualFile chosen = FileChooser.chooseFile(descriptor, parent, null, toSelect); if (chosen != null) { _selectedFile = VfsUtilCore.virtualToIoFile(chosen); final String newLocation = _selectedFile.getPath(); _importFile.setText(newLocation); _dialogBuilder.setOkActionEnabled(true); } }
public void testHardLinks() throws Exception { if (!SystemInfo.isWindows && !SystemInfo.isUnix) { System.err.println(getName() + " skipped: " + SystemInfo.OS_NAME); return; } final boolean safeWrite = GeneralSettings.getInstance().isUseSafeWrite(); final File dir = FileUtil.createTempDirectory("hardlinks.", ".dir", false); final SafeWriteRequestor requestor = new SafeWriteRequestor() {}; try { GeneralSettings.getInstance().setUseSafeWrite(false); final File targetFile = new File(dir, "targetFile"); assertTrue(targetFile.createNewFile()); final File hardLinkFile = IoTestUtil.createHardLink(targetFile.getAbsolutePath(), "hardLinkFile"); final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(targetFile); assertNotNull(file); file.setBinaryContent("hello".getBytes("UTF-8"), 0, 0, requestor); assertTrue(file.getLength() > 0); final VirtualFile check = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(hardLinkFile); assertNotNull(check); assertEquals(file.getLength(), check.getLength()); assertEquals("hello", VfsUtilCore.loadText(check)); } finally { GeneralSettings.getInstance().setUseSafeWrite(safeWrite); FileUtil.delete(dir); } }
@Nullable static String getRelativePath(final VirtualFile virtualFile, final Project project) { String url = virtualFile.getPresentableUrl(); if (project == null) { return url; } VirtualFile root = ProjectFileIndex.SERVICE.getInstance(project).getContentRootForFile(virtualFile); if (root != null) { return root.getName() + File.separatorChar + VfsUtilCore.getRelativePath(virtualFile, root, File.separatorChar); } final VirtualFile baseDir = project.getBaseDir(); if (baseDir != null) { //noinspection ConstantConditions final String projectHomeUrl = baseDir.getPresentableUrl(); if (url.startsWith(projectHomeUrl)) { final String cont = url.substring(projectHomeUrl.length()); if (cont.isEmpty()) return null; url = "..." + cont; } } return url; }
public ImportRunProfile(VirtualFile file, Project project) { myFile = file; myProject = project; try { final Document document = JDOMUtil.loadDocument(VfsUtilCore.virtualToIoFile(myFile)); final Element config = document.getRootElement().getChild("config"); if (config != null) { String configTypeId = config.getAttributeValue("configId"); if (configTypeId != null) { final ConfigurationType configurationType = ConfigurationTypeUtil.findConfigurationType(configTypeId); if (configurationType != null) { myConfiguration = configurationType.getConfigurationFactories()[0].createTemplateConfiguration( project); myConfiguration.setName(config.getAttributeValue("name")); myConfiguration.readExternal(config); final Executor executor = ExecutorRegistry.getInstance().getExecutorById(DefaultRunExecutor.EXECUTOR_ID); if (executor != null) { if (myConfiguration instanceof SMRunnerConsolePropertiesProvider) { myProperties = ((SMRunnerConsolePropertiesProvider) myConfiguration) .createTestConsoleProperties(executor); } } } } } } catch (Exception ignore) { } }
private String dubImportPath(String rootPath) { String pathUrl = VirtualFileManager.constructUrl(LocalFileSystem.PROTOCOL, rootPath); VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(pathUrl); if (file == null) { return null; } final List<String> sourcesDir = new ArrayList<>(); VfsUtilCore.visitChildrenRecursively( file, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (file.isDirectory()) { if (file.getName().equals("source")) { sourcesDir.add("source"); } if (file.getName().equals("src")) { sourcesDir.add("src"); } } return true; } }); return sourcesDir.isEmpty() ? null : rootPath + File.separator + sourcesDir.get(0); }
@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; }
private void doTest( @NotNull String fileName, int lineNumber, @NotNull Function1<VirtualFile, String> className) { if (rootDir == null) { configure(); } assert rootDir != null; Filter filter = new JetExceptionFilterFactory().create(GlobalSearchScope.allScope(myProject)); VirtualFile expectedFile = VfsUtilCore.findRelativeFile(fileName, rootDir); assertNotNull(expectedFile); String line = createStackTraceElementLine(fileName, className.invoke(expectedFile), lineNumber); Filter.Result result = filter.applyFilter(line, 0); assertNotNull(result); HyperlinkInfo info = result.getFirstHyperlinkInfo(); assertNotNull(info); assertInstanceOf(info, OpenFileHyperlinkInfo.class); OpenFileDescriptor descriptor = ((OpenFileHyperlinkInfo) info).getDescriptor(); assertNotNull(descriptor); assertEquals(expectedFile, descriptor.getFile()); Document document = FileDocumentManager.getInstance().getDocument(expectedFile); assertNotNull(document); int expectedOffset = document.getLineStartOffset(lineNumber - 1); assertEquals(expectedOffset, descriptor.getOffset()); }
@NotNull private static String findMainClass(VirtualFile gradleHome, VirtualFile script, Project project) { final String userDefined = System.getProperty("gradle.launcher.class"); if (StringUtil.isNotEmpty(userDefined)) { return userDefined; } VirtualFile launcher = gradleHome.findFileByRelativePath("bin/gradle"); if (launcher == null) { launcher = gradleHome.findFileByRelativePath("bin/gradle.bat"); } if (launcher != null) { try { final String text = StringUtil.convertLineSeparators(VfsUtilCore.loadText(launcher)); final Matcher matcher = MAIN_CLASS_NAME_PATTERN.matcher(text); if (matcher.find()) { String candidate = matcher.group(1); if (StringUtil.isNotEmpty(candidate)) { return candidate; } } } catch (IOException ignored) { } } final PsiFile grFile = PsiManager.getInstance(project).findFile(script); if (grFile != null && JavaPsiFacade.getInstance(project) .findClass("org.gradle.BootstrapMain", grFile.getResolveScope()) != null) { return "org.gradle.BootstrapMain"; } return "org.gradle.launcher.GradleMain"; }
@Nullable @Override public RefEntity getReference(final String type, final String fqName) { for (RefManagerExtension extension : myExtensions.values()) { final RefEntity refEntity = extension.getReference(type, fqName); if (refEntity != null) return refEntity; } if (SmartRefElementPointer.FILE.equals(type)) { return RefFileImpl.fileFromExternalName(this, fqName); } if (SmartRefElementPointer.MODULE.equals(type)) { return RefModuleImpl.moduleFromName(this, fqName); } if (SmartRefElementPointer.PROJECT.equals(type)) { return getRefProject(); } if (SmartRefElementPointer.DIR.equals(type)) { String url = VfsUtilCore.pathToUrl(PathMacroManager.getInstance(getProject()).expandPath(fqName)); VirtualFile vFile = VirtualFileManager.getInstance().findFileByUrl(url); if (vFile != null) { final PsiDirectory dir = PsiManager.getInstance(getProject()).findDirectory(vFile); return getReference(dir); } } return null; }
@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; }
private static void appendPackagesFolders( final @NotNull Collection<String> excludedPackagesUrls, final @Nullable VirtualFile folder, final @NotNull ProjectFileIndex fileIndex) { if (folder == null) return; VfsUtilCore.visitChildrenRecursively( folder, new VirtualFileVisitor() { @NotNull public Result visitFileEx(@NotNull final VirtualFile file) { if (!fileIndex.isInContent(file)) { return SKIP_CHILDREN; } if (file.isDirectory()) { if ("packages".equals(file.getName())) { return SKIP_CHILDREN; } else { excludedPackagesUrls.add(file.getUrl() + "/packages"); } } return CONTINUE; } }); }
private boolean ensureUsagesWritable( ReplaceContext replaceContext, Collection<Usage> selectedUsages) { Set<VirtualFile> readOnlyFiles = null; for (final Usage usage : selectedUsages) { final VirtualFile file = ((UsageInFile) usage).getFile(); if (file != null && !file.isWritable()) { if (readOnlyFiles == null) readOnlyFiles = new HashSet<VirtualFile>(); readOnlyFiles.add(file); } } if (readOnlyFiles != null) { ReadonlyStatusHandler.getInstance(myProject) .ensureFilesWritable(VfsUtilCore.toVirtualFileArray(readOnlyFiles)); } if (hasReadOnlyUsages(selectedUsages)) { int result = Messages.showOkCancelDialog( replaceContext.getUsageView().getComponent(), FindBundle.message("find.replace.occurrences.in.read.only.files.prompt"), FindBundle.message("find.replace.occurrences.in.read.only.files.title"), Messages.getWarningIcon()); if (result != Messages.OK) { return false; } } return true; }
private static String url2path(String url) { String path = VfsUtilCore.urlToPath(url); int separatorIndex = path.indexOf(JarFileSystem.JAR_SEPARATOR); if (separatorIndex < 0) return path; return path.substring(0, separatorIndex); }
/** * Collects all files which are located in the passed directory. * * @throws IllegalArgumentException if <code>dir</code> isn't a directory. */ public static void collectFiles( final VirtualFile dir, final List<VirtualFile> files, final boolean recursive, final boolean addDirectories) { if (!dir.isDirectory()) { throw new IllegalArgumentException( VcsBundle.message("exception.text.file.should.be.directory", dir.getPresentableUrl())); } final FileTypeManager fileTypeManager = FileTypeManager.getInstance(); VfsUtilCore.visitChildrenRecursively( dir, new VirtualFileVisitor() { @Override public boolean visitFile(@NotNull VirtualFile file) { if (file.isDirectory()) { if (addDirectories) { files.add(file); } if (!recursive && !Comparing.equal(file, dir)) { return false; } } else if (fileTypeManager == null || file.getFileType() != FileTypes.UNKNOWN) { files.add(file); } return true; } }); }
/** * @param srcFile * @param sourceRoot * @param packagePrefix * @return A 'package'-path to a given src file relative to a specified root. "/" slashes must be * used */ protected static String calcPackagePath( VirtualFile srcFile, VirtualFile sourceRoot, String packagePrefix) { final String prefix = packagePrefix != null && packagePrefix.length() > 0 ? packagePrefix.replace('.', '/') + "/" : ""; return prefix + VfsUtilCore.getRelativePath(srcFile, sourceRoot, '/'); }
public static VirtualFile findVirtualFile(String systemId) { try { return VfsUtil.findFileByURL(new URL(systemId)); } catch (Exception e) { LOG.warn("Failed to build file from uri <" + systemId + ">", e); return VirtualFileManager.getInstance().findFileByUrl(VfsUtilCore.fixURLforIDEA(systemId)); } }
@Nullable private static ContentEntry findContentEntry(ModuleRootModel rootModel, VirtualFile file) { return ContainerUtil.find( rootModel.getContentEntries(), object -> { VirtualFile entryRoot = object.getFile(); return entryRoot != null && VfsUtilCore.isAncestor(entryRoot, file, false); }); }
@Override public VirtualFile[] getAllVersionedRoots() { List<VirtualFile> vFiles = new ArrayList<VirtualFile>(); final AbstractVcs[] vcses = myMappings.getActiveVcses(); for (AbstractVcs vcs : vcses) { Collections.addAll(vFiles, getRootsUnderVcs(vcs)); } return VfsUtilCore.toVirtualFileArray(vFiles); }
public boolean visitRoot(VirtualFile root, Module module, Sdk sdk, boolean isModuleSource) { String vpath = VfsUtilCore.urlToPath(root.getUrl()); if (myPath.startsWith(vpath)) { myResult = vpath; return false; } else { return true; } }
public DirectoryNode( VirtualFile aDirectory, Project project, boolean compactPackages, boolean showFQName, VirtualFile baseDir, final VirtualFile[] contentRoots) { super(project); myVDirectory = aDirectory; final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project); final ProjectFileIndex index = projectRootManager.getFileIndex(); String dirName = aDirectory.getName(); if (showFQName) { final VirtualFile contentRoot = index.getContentRootForFile(myVDirectory); if (contentRoot != null) { if (Comparing.equal(myVDirectory, contentRoot)) { myFQName = dirName; } else { final VirtualFile sourceRoot = index.getSourceRootForFile(myVDirectory); if (Comparing.equal(myVDirectory, sourceRoot)) { myFQName = VfsUtilCore.getRelativePath(myVDirectory, contentRoot, '/'); } else if (sourceRoot != null) { myFQName = VfsUtilCore.getRelativePath(myVDirectory, sourceRoot, '/'); } else { myFQName = VfsUtilCore.getRelativePath(myVDirectory, contentRoot, '/'); } } if (contentRoots.length > 1 && ProjectRootsUtil.isModuleContentRoot(myVDirectory, project)) { myFQName = getContentRootName(baseDir, myFQName); } } else { myFQName = FilePatternPackageSet.getLibRelativePath(myVDirectory, index); } dirName = myFQName; } else { if (contentRoots.length > 1 && ProjectRootsUtil.isModuleContentRoot(myVDirectory, project)) { dirName = getContentRootName(baseDir, dirName); } } myDirName = dirName; myCompactPackages = compactPackages; }
@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); }
// inner roots disclosed public static List<VirtualFile> getRootsUnder( final List<VirtualFile> roots, final VirtualFile underWhat) { final List<VirtualFile> result = new ArrayList<VirtualFile>(roots.size()); for (VirtualFile root : roots) { if (VfsUtilCore.isAncestor(underWhat, root, false)) { result.add(root); } } return result; }
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, '/')); }