@Test public void testSimpleExternalsStatus() throws Exception { prepareExternal(); final File sourceFile = new File(myWorkingCopyDir.getPath(), "source" + File.separator + "s1.txt"); final File externalFile = new File( myWorkingCopyDir.getPath(), "source" + File.separator + "external" + File.separator + "t12.txt"); final LocalFileSystem lfs = LocalFileSystem.getInstance(); final VirtualFile vf1 = lfs.refreshAndFindFileByIoFile(sourceFile); final VirtualFile vf2 = lfs.refreshAndFindFileByIoFile(externalFile); Assert.assertNotNull(vf1); Assert.assertNotNull(vf2); editFileInCommand(myProject, vf1, "test externals 123" + System.currentTimeMillis()); editFileInCommand(myProject, vf2, "test externals 123" + System.currentTimeMillis()); VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty(); clManager.ensureUpToDate(false); final Change change1 = clManager.getChange(vf1); final Change change2 = clManager.getChange(vf2); Assert.assertNotNull(change1); Assert.assertNotNull(change2); Assert.assertNotNull(change1.getBeforeRevision()); Assert.assertNotNull(change2.getBeforeRevision()); Assert.assertNotNull(change1.getAfterRevision()); Assert.assertNotNull(change2.getAfterRevision()); }
/** @return true if keymap was installed or was successfully installed */ public static boolean installKeyBoardBindings() { LOG.debug("Check for keyboard bindings"); final LocalFileSystem localFileSystem = LocalFileSystem.getInstance(); if (localFileSystem.refreshAndFindFileByPath(KEYMAPS_PATH) == null) { reportError("Failed to install vim keymap. Empty keymaps folder"); return false; } LOG.debug("No vim keyboard installed found. Installing"); try { final byte[] bytes = toByteArray(retrieveSourceKeymapStream()); Files.write(bytes, new File(INSTALLED_VIM_KEYMAP_PATH)); final Document document = StorageUtil.loadDocument(bytes); if (document != null && !ApplicationManager.getApplication().isUnitTestMode()) { // Prompt user to select the parent for the Vim keyboard if (!configureVimParentKeymap(INSTALLED_VIM_KEYMAP_PATH, document, true)) { return false; } } installKeymap(document); } catch (IOException e) { reportError("Source keymap not found", e); return false; } catch (InvalidDataException e) { reportError("Failed to install vim keymap. Vim.xml file is corrupted", e); return false; } catch (Exception e) { reportError("Failed to install vim keymap.\n", e); return false; } return true; }
@Override public void setupRootModel(final ModifiableRootModel modifiableRootModel) throws ConfigurationException { String contentEntryPath = getContentEntryPath(); if (StringUtil.isEmpty(contentEntryPath)) { return; } File contentRootDir = new File(contentEntryPath); FileUtilRt.createDirectory(contentRootDir); LocalFileSystem fileSystem = LocalFileSystem.getInstance(); VirtualFile modelContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir); if (modelContentRootDir == null) { return; } modifiableRootModel.addContentEntry(modelContentRootDir); modifiableRootModel.inheritSdk(); final Project project = modifiableRootModel.getProject(); setupGradleBuildFile(modelContentRootDir); setupGradleSettingsFile(modelContentRootDir, modifiableRootModel); if (myWizardContext.isCreatingNewProject()) { String externalProjectPath = FileUtil.toCanonicalPath(project.getBasePath()); getExternalProjectSettings().setExternalProjectPath(externalProjectPath); AbstractExternalSystemSettings settings = ExternalSystemApiUtil.getSettings(project, GradleConstants.SYSTEM_ID); //noinspection unchecked settings.linkProject(getExternalProjectSettings()); } else { FileDocumentManager.getInstance().saveAllDocuments(); ExternalSystemUtil.refreshProjects(project, GradleConstants.SYSTEM_ID, false); } }
public static void doTestPartialRefresh(@NotNull File top) throws IOException { File sub = IoTestUtil.createTestDir(top, "sub"); File file = IoTestUtil.createTestFile(top, "sub.txt"); LocalFileSystem lfs = LocalFileSystem.getInstance(); NewVirtualFile topDir = (NewVirtualFile) lfs.refreshAndFindFileByIoFile(top); assertNotNull(topDir); NewVirtualFile subDir = (NewVirtualFile) lfs.refreshAndFindFileByIoFile(sub); assertNotNull(subDir); NewVirtualFile subFile = (NewVirtualFile) lfs.refreshAndFindFileByIoFile(file); assertNotNull(subFile); topDir.refresh(false, true); assertFalse(topDir.isDirty()); assertFalse(subDir.isDirty()); assertFalse(subFile.isDirty()); subFile.markDirty(); subDir.markDirty(); assertTrue(topDir.isDirty()); assertTrue(subFile.isDirty()); assertTrue(subDir.isDirty()); topDir.refresh(false, false); assertFalse(subFile.isDirty()); assertTrue(subDir.isDirty()); // should stay unvisited after non-recursive refresh topDir.refresh(false, true); assertFalse(topDir.isDirty()); assertFalse(subFile.isDirty()); assertFalse(subDir.isDirty()); }
public void testCopyToPointDir() throws Exception { File top = createTempDirectory(false); File sub = IoTestUtil.createTestDir(top, "sub"); File file = IoTestUtil.createTestFile(top, "file.txt", "hi there"); LocalFileSystem lfs = LocalFileSystem.getInstance(); VirtualFile topDir = lfs.refreshAndFindFileByIoFile(top); assertNotNull(topDir); VirtualFile sourceFile = lfs.refreshAndFindFileByIoFile(file); assertNotNull(sourceFile); VirtualFile parentDir = lfs.refreshAndFindFileByIoFile(sub); assertNotNull(parentDir); assertEquals(2, topDir.getChildren().length); try { sourceFile.copy(this, parentDir, "."); fail("Copying a file into a '.' path should have failed"); } catch (IOException e) { System.out.println(e.getMessage()); } topDir.refresh(false, true); assertTrue(topDir.exists()); assertEquals(2, topDir.getChildren().length); }
public void testFileCaseChange() throws Exception { if (SystemInfo.isFileSystemCaseSensitive) { System.err.println("Ignored: case-insensitive FS required"); return; } File top = createTempDirectory(false); File file = IoTestUtil.createTestFile(top, "file.txt", "test"); File intermediate = new File(top, "_intermediate_"); LocalFileSystem lfs = LocalFileSystem.getInstance(); VirtualFile topDir = lfs.refreshAndFindFileByIoFile(top); assertNotNull(topDir); VirtualFile sourceFile = lfs.refreshAndFindFileByIoFile(file); assertNotNull(sourceFile); String newName = StringUtil.capitalize(file.getName()); FileUtil.rename(file, intermediate); FileUtil.rename(intermediate, new File(top, newName)); topDir.refresh(false, true); assertFalse(((VirtualDirectoryImpl) topDir).allChildrenLoaded()); assertTrue(sourceFile.isValid()); assertEquals(newName, sourceFile.getName()); topDir.getChildren(); newName = newName.toLowerCase(); FileUtil.rename(file, intermediate); FileUtil.rename(intermediate, new File(top, newName)); topDir.refresh(false, true); assertTrue(((VirtualDirectoryImpl) topDir).allChildrenLoaded()); assertTrue(sourceFile.isValid()); assertEquals(newName, sourceFile.getName()); }
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); } }
private static void attachJdkAnnotations(Sdk jdk) { LocalFileSystem lfs = LocalFileSystem.getInstance(); VirtualFile root = null; if (root == null) { // community idea under idea root = lfs.findFileByPath( FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/java/jdkAnnotations"); } if (root == null) { // idea under idea root = lfs.findFileByPath( FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/community/java/jdkAnnotations"); } if (root == null) { // build root = VirtualFileManager.getInstance() .findFileByUrl( "jar://" + FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/lib/jdkAnnotations.jar!/"); } if (root == null) { LOG.error( "jdk annotations not found in: " + FileUtil.toSystemIndependentName(PathManager.getHomePath()) + "/lib/jdkAnnotations.jar!/"); return; } SdkModificator modificator = jdk.getSdkModificator(); modificator.removeRoot(root, AnnotationOrderRootType.getInstance()); modificator.addRoot(root, AnnotationOrderRootType.getInstance()); modificator.commitChanges(); }
protected void setupRootModel( final String testDir, final VirtualFile[] sourceDir, final String sdkName) { VirtualFile projectDir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir)); assertNotNull("could not find project dir " + testDir, projectDir); sourceDir[0] = projectDir.findChild("src"); if (sourceDir[0] == null) { sourceDir[0] = projectDir; } final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule); final ModifiableRootModel rootModel = rootManager.getModifiableModel(); rootModel.clear(); // configure source and output path final ContentEntry contentEntry = rootModel.addContentEntry(projectDir); contentEntry.addSourceFolder(sourceDir[0], false); ext_src = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir + "/ext_src")); if (ext_src != null) { contentEntry.addSourceFolder(ext_src, false); } // IMPORTANT! The jdk must be obtained in a way it is obtained in the normal program! // ProjectJdkEx jdk = ProjectJdkTable.getInstance().getInternalJdk(); rootModel.setSdk(getTestProjectSdk()); rootModel.commit(); }
private void doStuff(String rootDir, String itemRepr, String itemName) throws FileNotFoundException { String patternName = getTestDataPath() + getTestRoot() + getTestName(true) + "/after/" + itemName; File patternFile = new File(patternName); PrintWriter writer; if (!patternFile.exists()) { writer = new PrintWriter(new FileOutputStream(patternFile)); try { writer.print(itemRepr); } finally { writer.close(); } System.out.println("Pattern not found, file " + patternName + " created."); LocalFileSystem.getInstance().refreshAndFindFileByIoFile(patternFile); } File graFile = new File( FileUtil.getTempDirectory() + File.separator + rootDir + File.separator + itemName); writer = new PrintWriter(new FileOutputStream(graFile)); try { writer.print(itemRepr); } finally { writer.close(); } LocalFileSystem.getInstance().refreshAndFindFileByIoFile(graFile); FileDocumentManager.getInstance().saveAllDocuments(); }
@CalledInAwt public static void refreshPassedFilesAndMoveToChangelist( @NotNull final Project project, final Collection<FilePath> directlyAffected, final Collection<VirtualFile> indirectlyAffected, final Consumer<Collection<FilePath>> targetChangelistMover) { final LocalFileSystem lfs = LocalFileSystem.getInstance(); for (FilePath filePath : directlyAffected) { lfs.refreshAndFindFileByIoFile(filePath.getIOFile()); } if (project.isDisposed()) return; final ChangeListManager changeListManager = ChangeListManager.getInstance(project); if (!directlyAffected.isEmpty() && targetChangelistMover != null) { changeListManager.invokeAfterUpdate( new Runnable() { @Override public void run() { targetChangelistMover.consume(directlyAffected); } }, InvokeAfterUpdateMode.SYNCHRONOUS_CANCELLABLE, VcsBundle.message("change.lists.manager.move.changes.to.list"), new Consumer<VcsDirtyScopeManager>() { @Override public void consume(final VcsDirtyScopeManager vcsDirtyScopeManager) { markDirty(vcsDirtyScopeManager, directlyAffected, indirectlyAffected); } }, null); } else { markDirty(VcsDirtyScopeManager.getInstance(project), directlyAffected, indirectlyAffected); } }
@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; }
@Nullable public static VirtualFile findRefreshFileOrLog(@NotNull String absolutePath) { VirtualFile file = LocalFileSystem.getInstance().findFileByPath(absolutePath); if (file == null) { file = LocalFileSystem.getInstance().refreshAndFindFileByPath(absolutePath); } if (file == null) { LOG.warn("VirtualFile not found for " + absolutePath); } return file; }
public void testChildrenAccessedButNotCached() throws Exception { File dir = createTempDirectory(false); ManagingFS managingFS = ManagingFS.getInstance(); VirtualFile vFile = LocalFileSystem.getInstance() .refreshAndFindFileByPath(dir.getPath().replace(File.separatorChar, '/')); assertNotNull(vFile); assertFalse(managingFS.areChildrenLoaded(vFile)); assertFalse(managingFS.wereChildrenAccessed(vFile)); File child = new File(dir, "child"); boolean created = child.createNewFile(); assertTrue(created); File subdir = new File(dir, "subdir"); boolean subdirCreated = subdir.mkdir(); assertTrue(subdirCreated); File subChild = new File(subdir, "subdir"); boolean subChildCreated = subChild.createNewFile(); assertTrue(subChildCreated); VirtualFile childVFile = LocalFileSystem.getInstance() .refreshAndFindFileByPath(child.getPath().replace(File.separatorChar, '/')); assertNotNull(childVFile); assertFalse(managingFS.areChildrenLoaded(vFile)); assertTrue(managingFS.wereChildrenAccessed(vFile)); VirtualFile subdirVFile = LocalFileSystem.getInstance() .refreshAndFindFileByPath(subdir.getPath().replace(File.separatorChar, '/')); assertNotNull(subdirVFile); assertFalse(managingFS.areChildrenLoaded(subdirVFile)); assertFalse(managingFS.wereChildrenAccessed(subdirVFile)); assertFalse(managingFS.areChildrenLoaded(vFile)); assertTrue(managingFS.wereChildrenAccessed(vFile)); vFile.getChildren(); assertTrue(managingFS.areChildrenLoaded(vFile)); assertTrue(managingFS.wereChildrenAccessed(vFile)); assertFalse(managingFS.areChildrenLoaded(subdirVFile)); assertFalse(managingFS.wereChildrenAccessed(subdirVFile)); VirtualFile subChildVFile = LocalFileSystem.getInstance() .refreshAndFindFileByPath(subChild.getPath().replace(File.separatorChar, '/')); assertNotNull(subChildVFile); assertTrue(managingFS.areChildrenLoaded(vFile)); assertTrue(managingFS.wereChildrenAccessed(vFile)); assertFalse(managingFS.areChildrenLoaded(subdirVFile)); assertTrue(managingFS.wereChildrenAccessed(subdirVFile)); }
@Nullable public VirtualFile findFileByDartUrl(final @NotNull String url) { if (url.startsWith(DART_PREFIX)) { return findFileInDartSdkLibFolder(myProject, myDartSdk, url); } if (url.startsWith(PACKAGE_PREFIX)) { final String packageRelPath = url.substring(PACKAGE_PREFIX.length()); final int slashIndex = packageRelPath.indexOf('/'); final String packageName = slashIndex > 0 ? packageRelPath.substring(0, slashIndex) : packageRelPath; final String pathRelToPackageDir = slashIndex > 0 ? packageRelPath.substring(slashIndex + 1) : ""; final VirtualFile packageDir = StringUtil.isEmpty(packageName) ? null : myLivePackageNameToDirMap.get(packageName); if (packageDir != null) { return packageDir.findFileByRelativePath(pathRelToPackageDir); } for (final VirtualFile packageRoot : myPackageRoots) { final VirtualFile file = packageRoot.findFileByRelativePath(packageRelPath); if (file != null) { return file; } } final Set<String> packageDirs = myPubListPackageDirsMap.get(packageName); if (packageDirs != null) { for (String packageDirPath : packageDirs) { final VirtualFile file = LocalFileSystem.getInstance() .findFileByPath(packageDirPath + "/" + pathRelToPackageDir); if (file != null) { return file; } } } } if (url.startsWith(FILE_PREFIX)) { final String path = StringUtil.trimLeading(url.substring(FILE_PREFIX.length()), '/'); return LocalFileSystem.getInstance() .findFileByPath(SystemInfo.isWindows ? path : ("/" + path)); } if (ApplicationManager.getApplication().isUnitTestMode() && url.startsWith(TEMP_PREFIX)) { return TempFileSystem.getInstance().findFileByPath(url.substring((TEMP_PREFIX).length())); } return null; }
@Nullable private VirtualFile createFileFromTemplate( @Nullable final Project project, String url, final String templateName, final boolean forceNew) { final LocalFileSystem fileSystem = LocalFileSystem.getInstance(); final File file = new File(VfsUtilCore.urlToPath(url)); VirtualFile existingFile = fileSystem.refreshAndFindFileByIoFile(file); if (existingFile != null) { existingFile.refresh(false, false); if (!existingFile.isValid()) { existingFile = null; } } if (existingFile != null && !forceNew) { return existingFile; } try { String text = getText(templateName, project); final VirtualFile childData; if (existingFile == null || existingFile.isDirectory()) { final VirtualFile virtualFile; if (!FileUtil.createParentDirs(file) || (virtualFile = fileSystem.refreshAndFindFileByIoFile(file.getParentFile())) == null) { throw new IOException( IdeBundle.message("error.message.unable.to.create.file", file.getPath())); } childData = virtualFile.createChildData(this, file.getName()); } else { childData = existingFile; } VfsUtil.saveText(childData, text); return childData; } catch (final IOException e) { LOG.info(e); ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { Messages.showErrorDialog( IdeBundle.message( "message.text.error.creating.deployment.descriptor", e.getLocalizedMessage()), IdeBundle.message("message.text.creating.deployment.descriptor")); } }); } return null; }
@NotNull private VirtualFile getOrCreateExtractDirVirtualFile() { File extractDir = new File(myDirectoryTextField.getText()); VirtualFile vFile = LocalFileSystem.getInstance().findFileByIoFile(extractDir); if (vFile == null || !vFile.isValid()) { vFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(extractDir); if (vFile == null || !vFile.isValid()) { throw new RuntimeException( "Can't find valid VirtualFile for " + extractDir.getAbsolutePath()); } } return vFile; }
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()); } }
@Override public void run() { Project project = myModule.getProject(); if (GoSdkService.getInstance(project).isGoModule(myModule)) { synchronized (myLastHandledGoPathSourcesRoots) { Collection<VirtualFile> goPathSourcesRoots = GoSdkUtil.getGoPathSources(project, myModule); Set<VirtualFile> excludeRoots = ContainerUtil.newHashSet(ProjectRootManager.getInstance(project).getContentRoots()); ProgressIndicatorProvider.checkCanceled(); if (!myLastHandledGoPathSourcesRoots.equals(goPathSourcesRoots) || !myLastHandledExclusions.equals(excludeRoots)) { Collection<VirtualFile> includeRoots = gatherIncludeRoots(goPathSourcesRoots, excludeRoots); ApplicationManager.getApplication() .invokeLater( () -> { if (!myModule.isDisposed() && GoSdkService.getInstance(project).isGoModule(myModule)) { attachLibraries(includeRoots, excludeRoots); } }); myLastHandledGoPathSourcesRoots.clear(); myLastHandledGoPathSourcesRoots.addAll(goPathSourcesRoots); myLastHandledExclusions.clear(); myLastHandledExclusions.addAll(excludeRoots); List<String> paths = ContainerUtil.map(goPathSourcesRoots, VirtualFile::getPath); myWatchedRequests.clear(); myWatchedRequests.addAll(LocalFileSystem.getInstance().addRootsToWatch(paths, true)); } } } else { synchronized (myLastHandledGoPathSourcesRoots) { LocalFileSystem.getInstance().removeWatchedRoots(myWatchedRequests); myLastHandledGoPathSourcesRoots.clear(); myLastHandledExclusions.clear(); ApplicationManager.getApplication() .invokeLater( () -> { if (!myModule.isDisposed() && GoSdkService.getInstance(project).isGoModule(myModule)) { removeLibraryIfNeeded(); } }); } } }
public void testUnicodeNames() throws Exception { final File dirFile = createTempDirectory(); final String name = "te\u00dft123123123.txt"; final File childFile = new File(dirFile, name); boolean created = childFile.createNewFile(); assert created || childFile.exists() : childFile; final VirtualFile dir = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(dirFile); assertNotNull(dir); final VirtualFile child = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(childFile); assertNotNull(child); assertTrue(childFile.delete()); }
@Override public void setupRootModel(ModifiableRootModel model) throws ConfigurationException { String contentPath = getContentEntryPath(); if (StringUtil.isEmpty(contentPath)) { return; } File contentRootDir = new File(contentPath); FileUtilRt.createDirectory(contentRootDir); LocalFileSystem fileSystem = LocalFileSystem.getInstance(); VirtualFile vContentRootDir = fileSystem.refreshAndFindFileByIoFile(contentRootDir); if (vContentRootDir == null) { return; } model.addContentEntry(vContentRootDir); VirtualFile configFile = getExternalProjectConfigFile(vContentRootDir); if (configFile != null && myTemplateConfigName != null) { FileTemplateManager manager = FileTemplateManager.getInstance(); FileTemplate template = manager.getInternalTemplate(myTemplateConfigName); try { VfsUtil.saveText(configFile, template.getText()); } catch (IOException e) { LOG.warn( String.format( "Unexpected exception on applying template %s config", myExternalSystemId.getReadableName()), e); throw new ConfigurationException( e.getMessage(), String.format( "Can't apply %s template config text", myExternalSystemId.getReadableName())); } } AbstractExternalSystemSettings settings = ExternalSystemApiUtil.getSettings(model.getProject(), myExternalSystemId); S externalProjectSettings = createSettings(); if (myExternalProjectSettingsControl != null) { String errorMessage = myExternalProjectSettingsControl.apply(externalProjectSettings); myExternalProjectSettingsControl.disposeUIResources(); if (errorMessage != null) { throw new ConfigurationException(errorMessage); } } //noinspection unchecked settings.linkProject(externalProjectSettings); }
@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; }
private static Set<VirtualFile> getFilteredResourcesRoots(@NotNull MavenProject mavenProject) { Pair<Long, Set<VirtualFile>> cachedValue = mavenProject.getCachedValue(FILTERED_RESOURCES_ROOTS_KEY); if (cachedValue == null || cachedValue.first != VirtualFileManager.getInstance().getModificationCount()) { Set<VirtualFile> set = null; for (MavenResource resource : ContainerUtil.concat(mavenProject.getResources(), mavenProject.getTestResources())) { if (!resource.isFiltered()) continue; VirtualFile resourceDir = LocalFileSystem.getInstance().findFileByPath(resource.getDirectory()); if (resourceDir == null) continue; if (set == null) { set = new HashSet<VirtualFile>(); } set.add(resourceDir); } if (set == null) { set = Collections.emptySet(); } cachedValue = Pair.create(VirtualFileManager.getInstance().getModificationCount(), set); mavenProject.putCachedValue(FILTERED_RESOURCES_ROOTS_KEY, cachedValue); } return cachedValue.second; }
public void doCheckout(@NotNull final Project project, @Nullable final Listener listener) { ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { FileDocumentManager.getInstance().saveAllDocuments(); } }); final HgCloneDialog dialog = new HgCloneDialog(project); dialog.show(); if (!dialog.isOK()) { return; } dialog.rememberSettings(); final VirtualFile destinationParent = LocalFileSystem.getInstance().findFileByIoFile(new File(dialog.getParentDirectory())); if (destinationParent == null) { return; } final String targetDir = destinationParent.getPath() + File.separator + dialog.getDirectoryName(); final String sourceRepositoryURL = dialog.getSourceRepositoryURL(); new Task.Backgroundable( project, HgVcsMessages.message("hg4idea.clone.progress", sourceRepositoryURL), true) { @Override public void run(@NotNull ProgressIndicator indicator) { // clone HgCloneCommand clone = new HgCloneCommand(project); clone.setRepositoryURL(sourceRepositoryURL); clone.setDirectory(targetDir); // handle result HgCommandResult myCloneResult = clone.execute(); if (myCloneResult == null) { new HgCommandResultNotifier(project) .notifyError(null, "Clone failed", "Clone failed due to unknown error"); } else if (HgErrorUtil.hasErrorsInCommandExecution(myCloneResult)) { new HgCommandResultNotifier(project) .notifyError( myCloneResult, "Clone failed", "Clone from " + sourceRepositoryURL + " failed."); } else { ApplicationManager.getApplication() .invokeLater( new Runnable() { @Override public void run() { if (listener != null) { listener.directoryCheckedOut( new File(dialog.getParentDirectory(), dialog.getDirectoryName()), HgVcs.getKey()); listener.checkoutCompleted(); } } }); } } }.queue(); }
@Override public SourceScope getSourceScope() { final String dirName = myConfiguration.getPersistentData().getDirName(); final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(FileUtil.toSystemIndependentName(dirName)); final GlobalSearchScope globalSearchScope = file == null ? GlobalSearchScope.EMPTY_SCOPE : GlobalSearchScopes.directoryScope(myProject, file, true); return new SourceScope() { @Override public GlobalSearchScope getGlobalSearchScope() { return globalSearchScope; } @Override public Project getProject() { return myProject; } @Override public GlobalSearchScope getLibrariesScope() { final Module module = myConfiguration.getConfigurationModule().getModule(); LOG.assertTrue(module != null); return GlobalSearchScope.moduleWithLibrariesScope(module); } @Override public Module[] getModulesToCompile() { final Collection<Module> validModules = myConfiguration.getValidModules(); return validModules.toArray(new Module[validModules.size()]); } }; }
public void scan() { List<VirtualFile> workQueue = myWorkQueue; myWorkQueue = new ArrayList<VirtualFile>(); boolean hasEventsToFire = myFinishRunnable != null || !myEvents.isEmpty(); if (!workQueue.isEmpty()) { LocalFileSystemImpl fs = (LocalFileSystemImpl) LocalFileSystem.getInstance(); fs.markSuspiciousFilesDirty(workQueue); FileWatcher watcher = fs.getFileWatcher(); for (VirtualFile file : workQueue) { NewVirtualFile nvf = (NewVirtualFile) file; if (!myIsRecursive && (!myIsAsync || !watcher.isWatched( nvf))) { // We're unable to definitely refresh synchronously by means of file // watcher. nvf.markDirty(); } RefreshWorker worker = new RefreshWorker(file, myIsRecursive); long t = LOG.isDebugEnabled() ? System.currentTimeMillis() : 0; worker.scan(); List<VFileEvent> events = worker.getEvents(); if (t != 0) { t = System.currentTimeMillis() - t; LOG.debug(file + " scanned in " + t + " ms, events: " + events); } myEvents.addAll(events); if (!events.isEmpty()) hasEventsToFire = true; } } iHaveEventsToFire = hasEventsToFire; }
@Nullable public VirtualFile getPackageDirIfLivePackageOrFromPubListPackageDirs( @NotNull final String packageName, @Nullable final String pathRelToPackageDir) { final VirtualFile dir = myLivePackageNameToDirMap.get(packageName); if (dir != null) return dir; final Set<String> dirPaths = myPubListPackageDirsMap.get(packageName); if (dirPaths != null) { VirtualFile notNullPackageDir = null; for (String dirPath : dirPaths) { final VirtualFile packageDir = ApplicationManager.getApplication().isUnitTestMode() ? TempFileSystem.getInstance().findFileByPath(dirPath) : LocalFileSystem.getInstance().findFileByPath(dirPath); if (notNullPackageDir == null && packageDir != null) { notNullPackageDir = packageDir; } if (packageDir != null && (StringUtil.isEmpty(pathRelToPackageDir) || packageDir.findFileByRelativePath(pathRelToPackageDir) != null)) { return packageDir; } } return notNullPackageDir; // file by pathRelToPackageDir was not found, but not-null // packageDir still may be useful } return null; }
public void testAddSourceRoot() throws Exception { File dir = createTempDirectory(); final VirtualFile root = LocalFileSystem.getInstance() .refreshAndFindFileByPath(dir.getCanonicalPath().replace(File.separatorChar, '/')); new WriteCommandAction.Simple(getProject()) { @Override protected void run() throws Throwable { PsiTestUtil.addContentRoot(myModule, root); 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 initialize caches PsiTestUtil.addSourceRoot(myModule, root); PsiClass exceptionClass = myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject())); assertNotNull(exceptionClass); checkUsages(exceptionClass, new String[] {"1.java", "2.java", "New.java"}); checkTodos(new String[] {"2.java", "New.java"}); }
protected void doTest(final PerformAction performAction, final String testName) throws Exception { String path = getTestDataPath() + getTestRoot() + testName; String pathBefore = path + "/before"; final VirtualFile rootDir = PsiTestUtil.createTestProjectStructure( myProject, myModule, pathBefore, myFilesToDelete, false); prepareProject(rootDir); PsiDocumentManager.getInstance(myProject).commitAllDocuments(); String pathAfter = path + "/after"; final VirtualFile rootAfter = LocalFileSystem.getInstance().findFileByPath(pathAfter.replace(File.separatorChar, '/')); performAction.performAction(rootDir, rootAfter); ApplicationManager.getApplication() .runWriteAction( new Runnable() { public void run() { myProject.getComponent(PostprocessReformattingAspect.class).doPostponedFormatting(); } }); FileDocumentManager.getInstance().saveAllDocuments(); if (myDoCompare) { PlatformTestUtil.assertDirectoriesEqual(rootAfter, rootDir); } }
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); } }