com.intellij.openapi.vfs.VfsUtil Java Examples

The following examples show how to use com.intellij.openapi.vfs.VfsUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProjectConfigurable.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Override
public void reset() {
  myFreeze = true;
  try {

    final String compilerOutput = CompilerConfiguration.getInstance(myProject).getCompilerOutputUrl();
    if (compilerOutput != null) {
      myProjectCompilerOutput.setText(FileUtil.toSystemDependentName(VfsUtil.urlToPath(compilerOutput)));
    }
    if (myProjectName != null) {
      myProjectName.setText(myProject.getName());
    }
  }
  finally {
    myFreeze = false;
  }

  myContext.getDaemonAnalyzer().queueUpdate(mySettingsElement);
}
 
Example #2
Source File: ModuleEditorImpl.java    From intellij with Apache License 2.0 6 votes vote down vote up
private static void removeImlFile(final File imlFile) {
  final VirtualFile imlVirtualFile = VfsUtil.findFileByIoFile(imlFile, true);
  if (imlVirtualFile != null && imlVirtualFile.exists()) {
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              @Override
              public void run() {
                try {
                  imlVirtualFile.delete(this);
                } catch (IOException e) {
                  logger.warn(
                      String.format(
                          "Could not delete file: %s, will try to continue anyway.",
                          imlVirtualFile.getPath()),
                      e);
                }
              }
            });
  }
}
 
Example #3
Source File: SwitchToHeaderOrSourceSearch.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Nullable
private static OCFile correlateTestToHeader(OCFile file) {
  // Quickly check foo_test.cc -> foo.h as well. "getAssociatedFileWithSameName" only does
  // foo.cc <-> foo.h. However, if you do goto-related-symbol again, it will go from
  // foo.h -> foo.cc instead of back to foo_test.cc.
  PsiManager psiManager = PsiManager.getInstance(file.getProject());
  String pathWithoutExtension = FileUtil.getNameWithoutExtension(file.getVirtualFile().getPath());
  for (String testSuffix : PartnerFilePatterns.DEFAULT_PARTNER_SUFFIXES) {
    if (pathWithoutExtension.endsWith(testSuffix)) {
      String possibleHeaderName = StringUtil.trimEnd(pathWithoutExtension, testSuffix) + ".h";
      VirtualFile virtualFile = VfsUtil.findFileByIoFile(new File(possibleHeaderName), false);
      if (virtualFile != null) {
        PsiFile psiFile = psiManager.findFile(virtualFile);
        if (psiFile instanceof OCFile) {
          return (OCFile) psiFile;
        }
      }
    }
  }
  return null;
}
 
Example #4
Source File: TemplateUtil.java    From Thinkphp5-Plugin with MIT License 6 votes vote down vote up
@NotNull
public static Collection<String> resolveTemplateName(@NotNull Project project, @NotNull VirtualFile virtualFile) {
    Set<String> templateNames = new HashSet<>();

    for (TemplatePath templatePath : ViewCollector.getPaths(project)) {
        VirtualFile viewDir = templatePath.getRelativePath(project);
        if (viewDir == null) {
            continue;
        }

        String relativePath = VfsUtil.getRelativePath(virtualFile, viewDir);
        if (relativePath != null) {
            relativePath = stripTemplateExtensions(relativePath);

            if (templatePath.getNamespace() != null && StringUtils.isNotBlank(templatePath.getNamespace())) {
                templateNames.add(templatePath.getNamespace() + "::" + relativePath.replace("/", "."));
            } else {
                templateNames.add(relativePath.replace("/", "."));
            }
        }
    }

    return templateNames;
}
 
Example #5
Source File: IgnoredFileBean.java    From consulo with Apache License 2.0 6 votes vote down vote up
public boolean matchesFile(VirtualFile file) {
  if (myType == IgnoreSettingsType.MASK) {
    myMatcher.reset(file.getName());
    return myMatcher.matches();
  } else {
    // quick check for 'file' == exact match pattern
    if (IgnoreSettingsType.FILE.equals(myType) && ! myFilenameIfFile.equals(file.getName())) return false;

    VirtualFile selector = resolve();
    if (Comparing.equal(selector, NullVirtualFile.INSTANCE)) return false;

    if (myType == IgnoreSettingsType.FILE) {
      return Comparing.equal(selector, file);
    }
    else {
      if ("./".equals(myPath)) {
        // special case for ignoring the project base dir (IDEADEV-16056)
        return !file.isDirectory() && Comparing.equal(file.getParent(), selector);
      }
      return VfsUtil.isAncestor(selector, file, false);
    }
  }
}
 
Example #6
Source File: QualifiedNameProviders.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
public static String getFileFqn(final PsiFile file) {
  final VirtualFile virtualFile = file.getVirtualFile();
  if (virtualFile == null) {
    return file.getName();
  }
  final Project project = file.getProject();
  final LogicalRoot logicalRoot = LogicalRootsManager.getLogicalRootsManager(project).findLogicalRoot(virtualFile);
  if (logicalRoot != null) {
    String logical = FileUtil.toSystemIndependentName(VfsUtil.virtualToIoFile(logicalRoot.getVirtualFile()).getPath());
    String path = FileUtil.toSystemIndependentName(VfsUtil.virtualToIoFile(virtualFile).getPath());
    return "/" + FileUtil.getRelativePath(logical, path, '/');
  }

  final VirtualFile contentRoot = ProjectRootManager.getInstance(project).getFileIndex().getContentRootForFile(virtualFile);
  if (contentRoot != null) {
    return "/" + FileUtil.getRelativePath(VfsUtil.virtualToIoFile(contentRoot), VfsUtil.virtualToIoFile(virtualFile));
  }
  return virtualFile.getPath();
}
 
Example #7
Source File: LogFilter.java    From consulo with Apache License 2.0 6 votes vote down vote up
public Icon getIcon() {
  if (myIcon != null) {
    return myIcon;
  }
  if (myIconPath != null && new File(FileUtil.toSystemDependentName(myIconPath)).exists()) {
    Image image = null;
    try {
      image = ImageLoader.loadFromStream(VfsUtil.convertToURL(VfsUtil.pathToUrl(myIconPath)).openStream());
    }
    catch (IOException e) {
      LOG.debug(e);
    }

    if (image != null){
      return IconLoader.getIcon(image);
    }
  }
  //return IconLoader.getIcon("/ant/filter.png");
  return null;
}
 
Example #8
Source File: BlazeTypeScriptConfigServiceImpl.java    From intellij with Apache License 2.0 6 votes vote down vote up
private void restartServiceIfConfigsChanged() {
  if (!restartTypeScriptService.getValue()) {
    return;
  }
  int pathHash = Arrays.hashCode(configs.keySet().stream().map(VirtualFile::getPath).toArray());
  long contentTimestamp =
      configs.values().stream()
          .map(TypeScriptConfig::getDependencies)
          .flatMap(Collection::stream)
          .map(VfsUtil::virtualToIoFile)
          .map(File::lastModified)
          .max(Comparator.naturalOrder())
          .orElse(0L);
  int newConfigsHash = Objects.hash(pathHash, contentTimestamp);
  if (configsHash.getAndSet(newConfigsHash) != newConfigsHash) {
    TransactionGuard.getInstance()
        .submitTransactionLater(
            project, () -> TypeScriptCompilerService.restartServices(project, false));
  }
}
 
Example #9
Source File: HaxeMoveTest.java    From intellij-haxe with Apache License 2.0 6 votes vote down vote up
public void testMoveClass() throws Exception {
  final String testHx = "pack1/Moved.hx";
  final String targetDirName = "pack2";
  doTest((rootDir, rootAfter) -> {
    final VirtualFile src = VfsUtil.findRelativeFile(testHx, rootDir);
    assertNotNull("Class pack1.Moved not found", src);


    PsiElement file = myPsiManager.findFile(src);
    assertNotNull("Psi for " + testHx + " not found", file);
    PsiElement cls = file.getNode().getPsi(HaxeFile.class).findChildByClass(HaxeClassDeclaration.class);

    PackageWrapper pack = new PackageWrapper(myPsiManager, targetDirName);
    VirtualFile targetDir = VfsUtil.findRelativeFile(targetDirName, rootDir);
    PsiDirectoryImpl dir = new PsiDirectoryImpl(myPsiManager, targetDir);

    ArrayList<PsiElement> list = new ArrayList<>();
    list.add(cls);
    new MoveClassesOrPackagesProcessor(myProject, PsiUtilCore.toPsiElementArray(list),
                                       new SingleSourceRootMoveDestination(pack, dir),
                                       true, true, null).run();
    FileDocumentManager.getInstance().saveAllDocuments();
  });
}
 
Example #10
Source File: TemplateUtils.java    From code-generator with Apache License 2.0 6 votes vote down vote up
private static void generateSourceFile(String source, String baseDir) {
    String packageName = extractPackage(source);
    String className = extractClassName(source);
    String sourcePath = buildSourcePath(baseDir, className, packageName);
    VirtualFileManager manager = VirtualFileManager.getInstance();
    VirtualFile virtualFile = manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
    if (virtualFile == null || !virtualFile.exists() || userConfirmedOverride(className)) {
        ApplicationManager.getApplication().runWriteAction(() -> {
            try {
                if (virtualFile != null && virtualFile.exists()) {
                    virtualFile.setBinaryContent(source.getBytes("utf8"));

                } else {
                    File file = new File(sourcePath);
                    FileUtils.writeStringToFile(file, source, "utf8");
                    manager.refreshAndFindFileByUrl(VfsUtil.pathToUrl(sourcePath));
                }
            } catch (IOException e) {
                log.error(e);
            }
        });
    }
}
 
Example #11
Source File: EditAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void editFiles(final Project project, final List<VirtualFile> files, final List<VcsException> exceptions) {
  ChangesUtil.processVirtualFilesByVcs(project, files, (vcs, items) -> {
    final EditFileProvider provider = vcs.getEditFileProvider();
    if (provider != null) {
      try {
        provider.editFiles(VfsUtil.toVirtualFileArray(items));
      }
      catch (VcsException e1) {
        exceptions.add(e1);
      }
      for(VirtualFile file: items) {
        VcsDirtyScopeManager.getInstance(project).fileDirty(file);
        FileStatusManager.getInstance(project).fileStatusChanged(file);
      }
    }
  });
}
 
Example #12
Source File: LogicalRootsManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public LogicalRoot findLogicalRoot(@Nonnull final VirtualFile file) {
  final Module module = ModuleUtil.findModuleForFile(file, myProject);
  if (module == null) return null;

  LogicalRoot result = null;
  final List<LogicalRoot> list = getLogicalRoots(module);
  for (final LogicalRoot root : list) {
    final VirtualFile rootFile = root.getVirtualFile();
    if (rootFile != null && VfsUtil.isAncestor(rootFile, file, false)) {
      result = root;
      break;
    }
  }

  return result;
}
 
Example #13
Source File: ProjectStoreImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void setProjectFilePath(@Nonnull final String filePath) {
  final StateStorageManager stateStorageManager = getStateStorageManager();
  final LocalFileSystem fs = LocalFileSystem.getInstance();

  final File file = new File(filePath);

  final File dirStore = file.isDirectory() ? new File(file, Project.DIRECTORY_STORE_FOLDER) : new File(file.getParentFile(), Project.DIRECTORY_STORE_FOLDER);
  String defaultFilePath = new File(dirStore, "misc.xml").getPath();
  // deprecated
  stateStorageManager.addMacro(StoragePathMacros.PROJECT_FILE, defaultFilePath);
  stateStorageManager.addMacro(StoragePathMacros.DEFAULT_FILE, defaultFilePath);

  final File ws = new File(dirStore, "workspace.xml");
  stateStorageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, ws.getPath());

  stateStorageManager.addMacro(StoragePathMacros.PROJECT_CONFIG_DIR, dirStore.getPath());

  ApplicationManager.getApplication().invokeAndWait(() -> VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByIoFile(dirStore)), ModalityState.defaultModalityState());

  myPresentableUrl = null;
}
 
Example #14
Source File: FileResourceUtil.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
/**
 * Gives targets to files which relative to current file directory
 */
@NotNull
public static Collection<PsiFile> getFileResourceTargetsInDirectoryScope(@NotNull PsiFile psiFile, @NotNull String content) {

    // bundle scope
    if(content.startsWith("@")) {
        return Collections.emptyList();
    }

    PsiDirectory containingDirectory = psiFile.getContainingDirectory();
    if(containingDirectory == null) {
        return Collections.emptyList();
    }

    VirtualFile relativeFile = VfsUtil.findRelativeFile(content, containingDirectory.getVirtualFile());
    if(relativeFile == null) {
        return Collections.emptyList();
    }

    PsiFile targetFile = PsiElementUtils.virtualFileToPsiFile(psiFile.getProject(), relativeFile);
    if(targetFile == null) {
        return Collections.emptyList();
    }

    return Collections.singletonList(targetFile);
}
 
Example #15
Source File: ProjectStoreImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void setProjectFilePathNoUI(@Nonnull final String filePath) {
  final StateStorageManager stateStorageManager = getStateStorageManager();
  final LocalFileSystem fs = LocalFileSystem.getInstance();

  final File file = new File(filePath);

  final File dirStore = file.isDirectory() ? new File(file, Project.DIRECTORY_STORE_FOLDER) : new File(file.getParentFile(), Project.DIRECTORY_STORE_FOLDER);
  String defaultFilePath = new File(dirStore, "misc.xml").getPath();
  // deprecated
  stateStorageManager.addMacro(StoragePathMacros.PROJECT_FILE, defaultFilePath);
  stateStorageManager.addMacro(StoragePathMacros.DEFAULT_FILE, defaultFilePath);

  final File ws = new File(dirStore, "workspace.xml");
  stateStorageManager.addMacro(StoragePathMacros.WORKSPACE_FILE, ws.getPath());

  stateStorageManager.addMacro(StoragePathMacros.PROJECT_CONFIG_DIR, dirStore.getPath());

  VfsUtil.markDirtyAndRefresh(false, true, true, fs.refreshAndFindFileByIoFile(dirStore));

  myPresentableUrl = null;
}
 
Example #16
Source File: AsposeMavenModuleBuilderHelper.java    From Aspose.OCR-for-Java with MIT License 6 votes vote down vote up
private static void updateFileContents(Project project, final VirtualFile vf, final File f) throws Throwable {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    InputStream in = null;
    try {

        in = new FileInputStream(f);

        write(in, bytes);

    } finally {

        if (in != null) {
            in.close();
        }
    }
    VfsUtil.saveText(vf, bytes.toString());

    PsiFile psiFile = PsiManager.getInstance(project).findFile(vf);
    if (psiFile != null) {
        new ReformatCodeProcessor(project, psiFile, null, false).run();
    }
}
 
Example #17
Source File: AnnotationUtil.java    From idea-php-annotation-plugin with MIT License 6 votes vote down vote up
public static boolean isValidForIndex(@NotNull FileContent inputData) {
    String fileName = inputData.getPsiFile().getName();
    if(fileName.startsWith(".") || fileName.contains("Test")) {
        return false;
    }

    // we check for project path, on no match we are properly inside external library paths
    VirtualFile baseDir = inputData.getProject().getBaseDir();
    if (baseDir == null) {
        return true;
    }

    String relativePath = VfsUtil.getRelativePath(inputData.getFile(), baseDir, '/');
    if(relativePath == null) {
        return true;
    }

    // is Test file in path name
    return !(relativePath.contains("\\Test\\") || relativePath.contains("\\Fixtures\\"));
}
 
Example #18
Source File: DirectoryChooser.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
@Nonnull
public Image getIcon() {
  if (myDirectory != null) {
    VirtualFile virtualFile = myDirectory.getVirtualFile();
    List<ContentFolder> contentFolders = ModuleUtilCore.getContentFolders(myDirectory.getProject());
    for (ContentFolder contentFolder : contentFolders) {
      VirtualFile file = contentFolder.getFile();
      if(file == null) {
        continue;
      }
      if(VfsUtil.isAncestor(file, virtualFile, false)) {
        return contentFolder.getType().getIcon(contentFolder.getProperties());
      }
    }
  }
  return AllIcons.Nodes.Folder;
}
 
Example #19
Source File: FileChooserDialogImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void updatePathFromTree(final List<? extends VirtualFile> selection, boolean now) {
  if (!isToShowTextField() || myTreeIsUpdating) return;

  String text = "";
  if (selection.size() > 0) {
    text = VfsUtil.getReadableUrl(selection.get(0));
  }
  else {
    final List<VirtualFile> roots = myChooserDescriptor.getRoots();
    if (!myFileSystemTree.getTree().isRootVisible() && roots.size() == 1) {
      text = VfsUtil.getReadableUrl(roots.get(0));
    }
  }

  myPathTextField.setText(text, now, new Runnable() {
    public void run() {
      myPathTextField.getField().selectAll();
      setErrorText(null);
    }
  });
}
 
Example #20
Source File: CSharpCopyClassHandlerDelegate.java    From consulo-csharp with Apache License 2.0 6 votes vote down vote up
@Nullable
@RequiredReadAction
private static PsiDirectory tryNotNullizeDirectory(@Nonnull Project project, @Nullable PsiDirectory defaultTargetDirectory)
{
	if(defaultTargetDirectory == null)
	{
		VirtualFile root = ArrayUtil.getFirstElement(ProjectRootManager.getInstance(project).getContentRoots());
		if(root == null)
		{
			root = project.getBaseDir();
		}
		if(root == null)
		{
			root = VfsUtil.getUserHomeDir();
		}
		defaultTargetDirectory = root != null ? PsiManager.getInstance(project).findDirectory(root) : null;

		if(defaultTargetDirectory == null)
		{
			LOG.warn("No directory found for project: " + project.getName() + ", root: " + root);
		}
	}
	return defaultTargetDirectory;
}
 
Example #21
Source File: CompileContextImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public Module getModuleByFile(VirtualFile file) {
  final Module module = myProjectFileIndex.getModuleForFile(file);
  if (module != null) {
    LOG.assertTrue(!module.isDisposed());
    return module;
  }
  for (final VirtualFile root : myRootToModuleMap.keySet()) {
    if (VfsUtil.isAncestor(root, file, false)) {
      final Module mod = myRootToModuleMap.get(root);
      if (mod != null) {
        LOG.assertTrue(!mod.isDisposed());
      }
      return mod;
    }
  }
  return null;
}
 
Example #22
Source File: TemplateCreateByNameLocalQuickFix.java    From idea-php-symfony2-plugin with MIT License 6 votes vote down vote up
private static void createFile(@NotNull Project project, @NotNull String relativePath) {
    VirtualFile relativeBlockScopeFile = null;

    int i = relativePath.lastIndexOf("/");
    if(i > 0) {
        relativeBlockScopeFile = VfsUtil.findRelativeFile(ProjectUtil.getProjectDir(project), relativePath.substring(0, i).split("/"));
    }

    String content = TwigUtil.buildStringFromTwigCreateContainer(project, relativeBlockScopeFile);

    IdeHelper.RunnableCreateAndOpenFile runnableCreateAndOpenFile = IdeHelper.getRunnableCreateAndOpenFile(project, TwigFileType.INSTANCE, ProjectUtil.getProjectDir(project), relativePath);
    if(content != null) {
        runnableCreateAndOpenFile.setContent(content);
    }

    runnableCreateAndOpenFile.run();
}
 
Example #23
Source File: CodeMakerAction.java    From CodeMaker with Apache License 2.0 6 votes vote down vote up
private void saveToFile(AnActionEvent anActionEvent, String language, String className, String content, ClassEntry currentClass, DestinationChooser.FileDestination destination, String encoding) {
    final VirtualFile file = destination.getFile();
    final String sourcePath = file.getPath() + "/" + currentClass.getPackageName().replace(".", "/");
    final String targetPath = CodeMakerUtil.generateClassPath(sourcePath, className, language);

    VirtualFileManager manager = VirtualFileManager.getInstance();
    VirtualFile virtualFile = manager
            .refreshAndFindFileByUrl(VfsUtil.pathToUrl(targetPath));

    if (virtualFile == null || !virtualFile.exists() || userConfirmedOverride()) {
        // async write action
        ApplicationManager.getApplication().runWriteAction(
                new CreateFileAction(targetPath, content, encoding, anActionEvent
                        .getDataContext()));
    }
}
 
Example #24
Source File: WorkspaceRootNode.java    From intellij with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"}) // #api193: wildcard generics added in 2020.1
@Override
public Collection getChildrenImpl() {
  if (!BlazeUserSettings.getInstance().getCollapseProjectView()) {
    return getWrappedChildren();
  }
  Project project = getProject();
  if (project == null) {
    return getWrappedChildren();
  }
  List<AbstractTreeNode<?>> children = Lists.newArrayList();
  ProjectViewSet projectViewSet = ProjectViewManager.getInstance(project).getProjectViewSet();
  if (projectViewSet == null) {
    return getWrappedChildren();
  }

  ImportRoots importRoots =
      ImportRoots.builder(workspaceRoot, Blaze.getBuildSystem(project))
          .add(projectViewSet)
          .build();
  if (importRoots.rootDirectories().stream().anyMatch(WorkspacePath::isWorkspaceRoot)) {
    return getWrappedChildren();
  }
  for (WorkspacePath workspacePath : importRoots.rootDirectories()) {
    VirtualFile virtualFile =
        VfsUtil.findFileByIoFile(workspaceRoot.fileForPath(workspacePath), false);
    if (virtualFile == null) {
      continue;
    }
    PsiDirectory psiDirectory = PsiManager.getInstance(project).findDirectory(virtualFile);
    if (psiDirectory == null) {
      continue;
    }
    children.add(new BlazePsiDirectoryRootNode(project, psiDirectory, getSettings()));
  }
  if (children.isEmpty()) {
    return getWrappedChildren();
  }
  return children;
}
 
Example #25
Source File: CopyFilesOrDirectoriesHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
@RequiredReadAction
private static PsiDirectory tryNotNullizeDirectory(@Nonnull Project project, @Nullable PsiDirectory defaultTargetDirectory) {
  if (defaultTargetDirectory == null) {
    VirtualFile root = ArrayUtil.getFirstElement(ProjectRootManager.getInstance(project).getContentRoots());
    if (root == null) root = project.getBaseDir();
    if (root == null) root = VfsUtil.getUserHomeDir();
    defaultTargetDirectory = root != null ? PsiManager.getInstance(project).findDirectory(root) : null;

    if (defaultTargetDirectory == null) {
      LOG.warn("No directory found for project: " + project.getName() + ", root: " + root);
    }
  }
  return defaultTargetDirectory;
}
 
Example #26
Source File: AddTsConfigNotificationProvider.java    From intellij with Apache License 2.0 5 votes vote down vote up
private EditorNotificationPanel createNotificationPanel(
    Project project, VirtualFile file, Label tsConfig) {
  EditorNotificationPanel panel = new EditorNotificationPanel();
  panel.setText("Do you want to add the tsconfig.json for this file to the project view?");
  panel.createActionLabel(
      "Add tsconfig.json to project view",
      () -> {
        ProjectViewEdit edit =
            ProjectViewEdit.editLocalProjectView(
                project,
                builder -> {
                  ListSection<Label> rules = builder.getLast(TsConfigRulesSection.KEY);
                  builder.replace(
                      rules, ListSection.update(TsConfigRulesSection.KEY, rules).add(tsConfig));
                  return true;
                });
        if (edit != null) {
          edit.apply();
        }
        EditorNotifications.getInstance(project).updateNotifications(file);
      });
  panel.createActionLabel(
      "Hide notification",
      () -> {
        // suppressed for this file until the editor is restarted
        suppressedFiles.add(VfsUtil.virtualToIoFile(file));
        EditorNotifications.getInstance(project).updateNotifications(file);
      });
  return panel;
}
 
Example #27
Source File: HaxeMoveTest.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private void doTest(final String[] toMove, final String targetDirName) throws Exception {
  doTest(new PerformAction() {
    @Override
    public void performAction(VirtualFile rootDir, VirtualFile rootAfter) throws Exception {
      Collection<PsiElement> files = new ArrayList<PsiElement>();
      for (String s : toMove) {
        final VirtualFile child = VfsUtil.findRelativeFile(s, rootDir);
        assertNotNull("Neither class nor file " + s + " not found", child);
        PsiElement file = myPsiManager.findFile(child);
        if (file == null) file = JavaPsiFacade.getInstance(myProject).findPackage(s);
        files.add(file);
      }
      final VirtualFile child1 = VfsUtil.findRelativeFile(targetDirName, rootDir);
      assertNotNull("Target dir " + targetDirName + " not found", child1);
      final PsiDirectory targetDirectory = myPsiManager.findDirectory(child1);
      assertNotNull(targetDirectory);

      if (files.iterator().next() instanceof PsiFile) {
        new MoveFilesOrDirectoriesProcessor(myProject, PsiUtilCore.toPsiElementArray(files), targetDirectory,
                                            false, false, null, null).run();
      }
      else if (files.iterator().next() instanceof PsiPackage) {
        PsiPackage newParentPackage = JavaPsiFacade.getInstance(myPsiManager.getProject()).findPackage(targetDirName);
        assertNotNull(newParentPackage);
        final PsiDirectory[] dirs = newParentPackage.getDirectories();
        assertEquals(dirs.length, 1);

        new MoveClassesOrPackagesProcessor(myProject, PsiUtilCore.toPsiElementArray(files),
                                           new SingleSourceRootMoveDestination(PackageWrapper.create(newParentPackage),
                                                                               newParentPackage.getDirectories()[0]),
                                           true, true, null).run();
      }
      FileDocumentManager.getInstance().saveAllDocuments();
    }
  });
}
 
Example #28
Source File: ChangeListTodosTreeStructure.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean accept(final PsiFile psiFile) {
  if (!psiFile.isValid()) return false;
  boolean isAffected = false;
  final Collection<Change> changes = ChangeListManager.getInstance(myProject).getDefaultChangeList().getChanges();
  for (Change change : changes) {
    if (change.affectsFile(VfsUtil.virtualToIoFile(psiFile.getVirtualFile()))) {
      isAffected = true;
      break;
    }
  }
  return isAffected && (myTodoFilter != null && myTodoFilter.accept(mySearchHelper, psiFile) ||
                        (myTodoFilter == null && mySearchHelper.getTodoItemsCount(psiFile) > 0));
}
 
Example #29
Source File: GitExcludesOutputParser.java    From idea-gitignore with MIT License 5 votes vote down vote up
/**
 * Parses output and returns {@link VirtualFile} instance of the GitFileType.
 *
 * @param text input data
 * @return excludes ignore file instance
 */
@Nullable
@Override
protected VirtualFile parseOutput(@NotNull final String text) {
    final String path = Utils.resolveUserDir(text);
    return StringUtil.isNotEmpty(path) ? VfsUtil.findFileByIoFile(new File(path), true) : null;
}
 
Example #30
Source File: BlazeExternalSyntheticLibrary.java    From intellij with Apache License 2.0 5 votes vote down vote up
void restoreMissingFiles() {
  if (validFiles.size() < files.size()) {
    Sets.difference(
            files,
            validFiles.stream()
                .filter(VirtualFile::isValid)
                .map(VfsUtil::virtualToIoFile)
                .collect(toImmutableSet()))
        .stream()
        .map(file -> VfsUtils.resolveVirtualFile(file, /* refreshIfNeeded= */ false))
        .filter(Objects::nonNull)
        .forEach(validFiles::add);
  }
}