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; }
@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; }
@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; }
@Override public void beforeDocumentChange(DocumentEvent event) { final Document document = event.getDocument(); final FileViewProvider viewProvider = getCachedViewProvider(document); if (viewProvider == null) return; if (!isRelevant(viewProvider)) return; VirtualFile virtualFile = viewProvider.getVirtualFile(); if (virtualFile.getFileType().isBinary()) return; final List<PsiFile> files = viewProvider.getAllFiles(); PsiFile psiCause = null; for (PsiFile file : files) { mySmartPointerManager.fastenBelts(file, event.getOffset(), null); if (TextBlock.get(file).isLocked()) { psiCause = file; } } if (psiCause == null) { beforeDocumentChangeOnUnlockedDocument(viewProvider); } ((SingleRootFileViewProvider) viewProvider).beforeDocumentChanged(psiCause); }
@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"; }
private void doSaveDocument(@NotNull final Document document) throws IOException, SaveVetoException { VirtualFile file = getFile(document); if (file == null || file instanceof LightVirtualFile || file.isValid() && !isFileModified(file)) { removeFromUnsaved(document); return; } if (file.isValid() && needsRefresh(file)) { file.refresh(false, false); if (!myUnsavedDocuments.contains(document)) return; } for (FileDocumentSynchronizationVetoer vetoer : Extensions.getExtensions(FileDocumentSynchronizationVetoer.EP_NAME)) { if (!vetoer.maySaveDocument(document)) { throw new SaveVetoException(); } } final AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(getClass()); try { doSaveDocumentInWriteAction(document, file); } finally { token.finish(); } }
private MergeRequestImpl( @NotNull DiffContent left, @NotNull DiffContent base, @NotNull DiffContent right, @Nullable Project project, @Nullable final ActionButtonPresentation okButtonPresentation, @Nullable final ActionButtonPresentation cancelButtonPresentation) { super(project); myOkButtonPresentation = okButtonPresentation; myCancelButtonPresentation = cancelButtonPresentation; myDiffContents[0] = left; myDiffContents[1] = base; myDiffContents[2] = right; if (MergeTool.LOG.isDebugEnabled()) { VirtualFile file = base.getFile(); MergeTool.LOG.debug( new Throwable( base.getClass() + " - writable: " + base.getDocument().isWritable() + ", contentType: " + base.getContentType() + ", file: " + (file != null ? "valid - " + file.isValid() : "null") + ", presentation: " + myOkButtonPresentation + "-" + myCancelButtonPresentation)); } }
public String getDirName() { if (myVDirectory == null || !myVDirectory.isValid()) return ""; if (myCompactPackages && myCompactedDirNode != null) { return myVDirectory.getName() + "/" + myCompactedDirNode.getDirName(); } return myDirName; }
@Override protected void doOKAction() { VirtualFile root = getGitRoot(); GitLineHandler h = handler(); final AtomicBoolean conflict = new AtomicBoolean(); h.addLineListener( new GitLineHandlerAdapter() { public void onLineAvailable(String line, Key outputType) { if (line.contains("Merge conflict")) { conflict.set(true); } } }); int rc = GitHandlerUtil.doSynchronously( h, GitBundle.getString("unstash.unstashing"), h.printableCommandLine(), false); root.refresh(true, true); if (conflict.get()) { boolean conflictsResolved = new UnstashConflictResolver(myProject, root, getSelectedStash()).merge(); LOG.info("loadRoot " + root + ", conflictsResolved: " + conflictsResolved); } else if (rc != 0) { GitUIUtil.showOperationErrors(myProject, h.errors(), h.printableCommandLine()); } super.doOKAction(); }
@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); } } } }); }
protected static void touch(VirtualFile file) throws IOException { file.setBinaryContent( file.contentsToByteArray(), file.getModificationStamp() + 1, file.getTimeStamp() + 1); File ioFile = VfsUtil.virtualToIoFile(file); assert ioFile.setLastModified(ioFile.lastModified() - 100000); file.refresh(false, false); }
@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; }
private void initLivePackageNameToDirMap() { final VirtualFile baseDir = myPubspecYamlFile == null ? null : myPubspecYamlFile.getParent(); if (myPubspecYamlFile == null || baseDir == null) return; final String name = PubspecYamlUtil.getDartProjectName(myPubspecYamlFile); final VirtualFile libFolder = baseDir.findChild(PubspecYamlUtil.LIB_DIR_NAME); if (name != null && libFolder != null && libFolder.isDirectory()) { myLivePackageNameToDirMap.put(name, libFolder); } final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex(); PubspecYamlUtil.processPathPackages( myPubspecYamlFile, new PairConsumer<String, VirtualFile>() { @Override public void consume( @NotNull final String packageName, @NotNull final VirtualFile packageDir) { if (fileIndex.isInContent(packageDir)) { myLivePackageNameToDirMap.put(packageName, packageDir); } } }); }
private VirtualFile getClassFile() { VirtualFile packageDir = libraryDir.findFileByRelativePath(PACKAGE.replace(".", "/")); assertNotNull(packageDir); VirtualFile classFile = packageDir.findChild(getTestName(false) + ".class"); assertNotNull(classFile); return classFile; }
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(); }
@Nullable private static String doGenerateInfo( @NotNull PsiElement element, @NotNull PsiElement atPointer, @NotNull DocumentationProvider documentationProvider) { String info = documentationProvider.getQuickNavigateInfo(element, atPointer); if (info != null) { return info; } if (element instanceof PsiFile) { final VirtualFile virtualFile = ((PsiFile) element).getVirtualFile(); if (virtualFile != null) { return virtualFile.getPresentableUrl(); } } info = getQuickNavigateInfo(element); if (info != null) { return info; } if (element instanceof NavigationItem) { final ItemPresentation presentation = ((NavigationItem) element).getPresentation(); if (presentation != null) { return presentation.getPresentableText(); } } return null; }
@Override public PsiElement getTopLevelElement(PsiElement element) { PsiFile file = element.getContainingFile(); if (file == null || !(file instanceof JetFile)) return null; VirtualFile virtualFile = file.getVirtualFile(); if (!fileInRoots(virtualFile)) return file; PsiElement current = element; while (current != null) { if (isSelectable(current)) break; current = current.getParent(); } if (current instanceof JetFile) { List<JetDeclaration> declarations = ((JetFile) current).getDeclarations(); String nameWithoutExtension = virtualFile != null ? virtualFile.getNameWithoutExtension() : file.getName(); if (declarations.size() == 1 && declarations.get(0) instanceof JetClassOrObject && nameWithoutExtension.equals(declarations.get(0).getName())) { current = declarations.get(0); } } return current != null ? current : file; }
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(); } }
@Override public void contentsChanged(VirtualFileEvent event) { if (event.isFromSave()) return; final VirtualFile file = event.getFile(); final Document document = getCachedDocument(file); if (document == null) { myMultiCaster.fileWithNoDocumentChanged(file); return; } if (isBinaryWithDecompiler(file)) { myMultiCaster.fileWithNoDocumentChanged( file); // This will generate PSI event at FileManagerImpl } long documentStamp = document.getModificationStamp(); long oldFileStamp = event.getOldModificationStamp(); if (documentStamp != oldFileStamp) { LOG.info("reload from disk?"); LOG.info(" documentStamp:" + documentStamp); LOG.info(" oldFileStamp:" + oldFileStamp); if (file.isValid() && askReloadFromDisk(file, document)) { reloadFromDisk(document); } } else { reloadFromDisk(document); } }
@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 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; }
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); } }
@Override public boolean acceptInput(@NotNull final VirtualFile file) { return ourEnabled && findDuplicatesProfile(file.getFileType()) != null && file.isInLocalFileSystem() // skip library sources ; }
public VirtualFile getContentRootForFile(@NotNull VirtualFile file) { VirtualFile dir = file.isDirectory() ? file : file.getParent(); if (dir == null) return null; final DirectoryInfo info = getInfoForDirectory(dir); if (info == null) return null; return info.contentRoot; }
protected XtextResource createExpectedResource() { XtextResource _xblockexpression = null; { XtextResourceSet resourceSet = this.createFreshResourceSet(); VirtualFile _virtualFile = this.myFile.getVirtualFile(); String _url = _virtualFile.getUrl(); final URI uri = URI.createURI(_url); Resource _createResource = resourceSet.createResource(uri); final Procedure1<XtextResource> _function = new Procedure1<XtextResource>() { @Override public void apply(final XtextResource it) { try { String _text = AbstractLanguageParsingTestCase.this.myFile.getText(); byte[] _bytes = _text.getBytes(); ByteArrayInputStream _byteArrayInputStream = new ByteArrayInputStream(_bytes); it.load(_byteArrayInputStream, null); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } }; _xblockexpression = ObjectExtensions.<XtextResource>operator_doubleArrow( ((XtextResource) _createResource), _function); } return _xblockexpression; }
public boolean isLibraryClassFile(@NotNull VirtualFile file) { if (file.isDirectory()) return false; if (myFileTypeRegistry.isFileIgnored(file)) return false; VirtualFile parent = file.getParent(); DirectoryInfo parentInfo = getInfoForDirectory(parent); return parentInfo != null && parentInfo.libraryClassRoot != null; }
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(); }
@NotNull public static Module doCreateRealModuleIn( @NotNull String moduleName, @NotNull final Project project, @NotNull final ModuleType moduleType) { final VirtualFile baseDir = project.getBaseDir(); assertNotNull(baseDir); final File moduleFile = new File( baseDir.getPath().replace('/', File.separatorChar), moduleName + ModuleFileType.DOT_DEFAULT_EXTENSION); FileUtil.createIfDoesntExist(moduleFile); myFilesToDelete.add(moduleFile); return new WriteAction<Module>() { @Override protected void run(@NotNull Result<Module> result) throws Throwable { final VirtualFile virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(moduleFile); assert virtualFile != null; Module module = ModuleManager.getInstance(project).newModule(virtualFile.getPath(), moduleType.getId()); module.getModuleFile(); result.setResult(module); } }.execute().getResultObject(); }
@Override public boolean isFileVisible(VirtualFile file, boolean showHiddenFiles) { if (!super.isFileVisible(file, showHiddenFiles)) { return false; } return file.isDirectory() || GradleConstants.DEFAULT_SCRIPT_NAME.equals(file.getName()); }
public void update(AnActionEvent e) { super.update(e); final Project project = e.getData(DataKeys.PROJECT); final VirtualFile file = e.getData(DataKeys.VIRTUAL_FILE); boolean visible = project != null && file != null && !file.isDirectory() && file.getFileType() == CppSupportLoader.CPP_FILETYPE && !Communicator.isHeaderFile(file); boolean enabled = visible; if (!visible) { visible = ActionPlaces.MAIN_MENU.equals(e.getPlace()); } e.getPresentation().setEnabled(enabled); e.getPresentation().setVisible(visible); if (visible) { final String s = "Do c&ompile for " + (file != null ? file.getName() : "selected c/c++ fileToCompile"); e.getPresentation().setText(s); e.getPresentation().setDescription(s); } }