com.intellij.openapi.vfs.VfsUtilCore Java Examples

The following examples show how to use com.intellij.openapi.vfs.VfsUtilCore. 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: BlazeCppResolvingTestCase.java    From intellij with Apache License 2.0 6 votes vote down vote up
@Before
public void setupDefaultIncludeRoots() {
  VirtualFile genfilesRoot = fileSystem.createDirectory("output/genfiles");
  VirtualFile readonlyRoot = fileSystem.createDirectory("READONLY/workspace");
  workspace.createDirectory(new WorkspacePath("third_party/stl"));
  workspace.createDirectory(new WorkspacePath("third_party/toolchain/include/c++/4.9"));
  BlazeProjectData projectData =
      MockBlazeProjectDataBuilder.builder(workspaceRoot)
          .setOutputBase(fileSystem.getRootDir() + "/output")
          .build();
  setupIncludeRoots(
      projectData,
      ImmutableList.of(
          new ExecutionRootPath("."),
          new ExecutionRootPath(VfsUtilCore.virtualToIoFile(readonlyRoot)),
          new ExecutionRootPath(VfsUtilCore.virtualToIoFile(genfilesRoot))),
      ImmutableList.of(
          new ExecutionRootPath("third_party/stl"),
          new ExecutionRootPath("third_party/toolchain/include/c++/4.9")));
}
 
Example #2
Source File: OCamlSourcesOrderRootTypeUIFactory.java    From reasonml-idea-plugin with MIT License 6 votes vote down vote up
@NotNull
List<VirtualFile> suggestOCamlRoots(@NotNull VirtualFile dir, @NotNull final ProgressIndicator progressIndicator) {
    if (!dir.isDirectory()) {
        return ContainerUtil.emptyList();
    }

    final FileTypeManager typeManager = FileTypeManager.getInstance();
    final ArrayList<VirtualFile> foundDirectories = new ArrayList<>();
    try {
        VfsUtilCore.visitChildrenRecursively(dir, new VirtualFileVisitor() {
            @NotNull
            @Override
            public Result visitFileEx(@NotNull VirtualFile file) {
                progressIndicator.checkCanceled();

                if (!file.isDirectory()) {
                    FileType type = typeManager.getFileTypeByFileName(file.getName());

                    if (type.getDefaultExtension().equals("ml")) {
                        VirtualFile root = file.getParent();
                        if (root != null) {
                            foundDirectories.add(root);
                            return skipTo(root);
                        }
                    }
                }

                return CONTINUE;
            }
        });
    } catch (ProcessCanceledException ignore) {
    }

    return foundDirectories;
}
 
Example #3
Source File: CompilerPathsImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static VirtualFile[] getOutputDirectories(final Module[] modules) {
  if (modules.length == 0) {
    return VirtualFile.EMPTY_ARRAY;
  }

  final Set<VirtualFile> dirs = new OrderedSet<VirtualFile>();
  for (Module module : modules) {
    for (ContentFolderTypeProvider contentFolderType : ContentFolderTypeProvider.filter(ContentFolderScopes.productionAndTest())) {
      VirtualFile virtualFile = ModuleCompilerPathsManager.getInstance(module).getCompilerOutput(contentFolderType);
      if (virtualFile != null) {
        dirs.add(virtualFile);
      }
    }
  }

  return VfsUtilCore.toVirtualFileArray(dirs);
}
 
Example #4
Source File: AbstractFileTreeTable.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void select(@Nonnull VirtualFile toSelect, final TreeNode root) {
  for (int i = 0; i < root.getChildCount(); i++) {
    TreeNode child = root.getChildAt(i);
    VirtualFile file = ((FileNode)child).getObject();
    if (VfsUtilCore.isAncestor(file, toSelect, false)) {
      if (Comparing.equal(file, toSelect)) {
        TreeUtil.selectNode(getTree(), child);
        getSelectionModel().clearSelection();
        addSelectedPath(TreeUtil.getPathFromRoot(child));
        TableUtil.scrollSelectionToVisible(this);
      }
      else {
        select(toSelect, child);
      }
      return;
    }
  }
}
 
Example #5
Source File: LightVirtualFile.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nonnull
public OutputStream getOutputStream(Object requestor, final long newModificationStamp, long newTimeStamp) throws IOException {
  return VfsUtilCore.outputStreamAddingBOM(new ByteArrayOutputStream() {
    @Override
    public void close() {
      setModificationStamp(newModificationStamp);

      try {
        String content = toString(getCharset().name());
        setContent(content);
      }
      catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
      }
    }
  }, this);
}
 
Example #6
Source File: BlazeRenderErrorContributor.java    From intellij with Apache License 2.0 6 votes vote down vote up
private File getSourceFileForClass(String className) {
  return ApplicationManager.getApplication()
      .runReadAction(
          (Computable<File>)
              () -> {
                try {
                  PsiClass psiClass =
                      JavaPsiFacade.getInstance(project)
                          .findClass(className, GlobalSearchScope.projectScope(project));
                  if (psiClass == null) {
                    return null;
                  }
                  return VfsUtilCore.virtualToIoFile(
                      psiClass.getContainingFile().getVirtualFile());
                } catch (IndexNotReadyException ignored) {
                  // We're in dumb mode. Abort! Abort!
                  return null;
                }
              });
}
 
Example #7
Source File: LocalChangesUnderRoots.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
private VirtualFile getRootForPath(@Nonnull FilePath file, @Nonnull Collection<VirtualFile> rootsToSave) {
  final VirtualFile vf = ChangesUtil.findValidParentUnderReadAction(file);
  if (vf == null) {
    return null;
  }
  VirtualFile rootCandidate = null;
  for (VcsRoot root : myRoots) {
    if (VfsUtilCore.isAncestor(root.getPath(), vf, false)) {
      if (rootCandidate == null || VfsUtil.isAncestor(rootCandidate, root.getPath(), true)) { // in the case of nested roots choose the closest root
        rootCandidate = root.getPath();
      }
    }
  }
  if (! rootsToSave.contains(rootCandidate)) return null;
  return rootCandidate;
}
 
Example #8
Source File: PathsVerifier.java    From consulo with Apache License 2.0 6 votes vote down vote up
public VirtualFile doMove() throws IOException {
  final VirtualFile oldParent = myCurrent.getParent();
  boolean needRename = !Comparing.equal(myCurrent.getName(), myNewName);
  boolean needMove = !myNewParent.equals(oldParent);
  if (needRename) {
    if (needMove) {
      File oldParentFile = VfsUtilCore.virtualToIoFile(oldParent);
      File targetAfterRenameFile = new File(oldParentFile, myNewName);
      if (targetAfterRenameFile.exists() && myCurrent.exists()) {
        // if there is a conflict during first rename we have to rename to third name, then move, then rename to final target
        performRenameWithConflicts(oldParentFile);
        return myCurrent;
      }
    }
    myCurrent.rename(PatchApplier.class, myNewName);
  }
  if (needMove) {
    myCurrent.move(PatchApplier.class, myNewParent);
  }
  return myCurrent;
}
 
Example #9
Source File: GlobalSearchScopesCore.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public GlobalSearchScope uniteWith(@Nonnull GlobalSearchScope scope) {
  if (equals(scope)) return this;
  if (scope instanceof DirectoryScope) {
    DirectoryScope other = (DirectoryScope)scope;
    VirtualFile otherDirectory = other.myDirectory;
    if (myWithSubdirectories && VfsUtilCore.isAncestor(myDirectory, otherDirectory, false)) return this;
    if (other.myWithSubdirectories && VfsUtilCore.isAncestor(otherDirectory, myDirectory, false)) return other;
    BitSet newWithSubdirectories = new BitSet();
    newWithSubdirectories.set(0, myWithSubdirectories);
    newWithSubdirectories.set(1, other.myWithSubdirectories);
    return new DirectoriesScope(getProject(), new VirtualFile[]{myDirectory,otherDirectory}, newWithSubdirectories);
  }
  return super.uniteWith(scope);
}
 
Example #10
Source File: ChangeFileEncodingAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
public ListPopup createPopup(@Nonnull DataContext dataContext) {
  final VirtualFile virtualFile = dataContext.getData(CommonDataKeys.VIRTUAL_FILE);
  if (virtualFile == null) return null;
  boolean enabled = checkEnabled(virtualFile);
  if (!enabled) return null;
  Editor editor = dataContext.getData(CommonDataKeys.EDITOR);
  FileDocumentManager documentManager = FileDocumentManager.getInstance();
  final Document document = documentManager.getDocument(virtualFile);
  if (!allowDirectories && virtualFile.isDirectory() || document == null && !virtualFile.isDirectory()) return null;

  final byte[] bytes;
  try {
    bytes = virtualFile.isDirectory() ? null : VfsUtilCore.loadBytes(virtualFile);
  }
  catch (IOException e) {
    return null;
  }
  DefaultActionGroup group = createActionGroup(virtualFile, editor, document, bytes, null);

  return JBPopupFactory.getInstance().createActionGroupPopup(getTemplatePresentation().getText(), group, dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false);
}
 
Example #11
Source File: FileStatusCalculator.java    From SVNToolBox with Apache License 2.0 6 votes vote down vote up
private boolean allFilesUnderSvnImpl(@NotNull SvnVcs svn, @Nullable Project project, boolean fast, VirtualFile... vFiles) {
    if (project == null) {
        return false;
    }
    boolean result = ProjectLevelVcsManager.getInstance(project).checkAllFilesAreUnder(svn, vFiles);
    if (result && vFiles != null) {
        for (VirtualFile vFile : vFiles) {
            if (!SvnStatusUtil.isUnderControl(project, vFile)) {
                return false;
            } else if (!fast) {
                if (!getWCRoot(VfsUtilCore.virtualToIoFile(vFile)).isPresent()) {
                    return false;
                }
            }
        }
    }
    return result;
}
 
Example #12
Source File: PsiUtilsImpl.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Location toLocation(PsiMember psiMember) {
    PsiElement sourceElement = psiMember.getNavigationElement();
    if (sourceElement != null) {
        PsiFile file = sourceElement.getContainingFile();
        Location location = new Location();
        location.setUri(VfsUtilCore.convertToURL(file.getVirtualFile().getUrl()).toExternalForm());
        Document document = PsiDocumentManager.getInstance(psiMember.getProject()).getDocument(file);
        TextRange range = sourceElement.getTextRange();
        int startLine = document.getLineNumber(range.getStartOffset());
        int startLineOffset = document.getLineStartOffset(startLine);
        int endLine = document.getLineNumber(range.getEndOffset());
        int endLineOffset = document.getLineStartOffset(endLine);
        location.setRange(new Range(LSPIJUtils.toPosition(range.getStartOffset(), document), LSPIJUtils.toPosition(range.getEndOffset(), document)));
        return location;
    }
    return null;
}
 
Example #13
Source File: SimpleCoverageAnnotator.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nullable
protected FileCoverageInfo collectBaseFileCoverage(@Nonnull final VirtualFile file,
                                                   @Nonnull final Annotator annotator,
                                                   @Nonnull final ProjectData projectData,
                                                   @Nonnull 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;
}
 
Example #14
Source File: RefManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #15
Source File: BuildElementsEditor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void moduleCompileOutputChanged(final String baseUrl, final String moduleName) {
  ModuleCompilerPathsManager moduleCompilerPathsManager = ModuleCompilerPathsManager.getInstance(getModule());
  if (moduleCompilerPathsManager.isInheritedCompilerOutput()) {
    if (baseUrl != null) {
      myOutputPathPanel.setText(FileUtil.toSystemDependentName(
              VfsUtilCore.urlToPath(moduleCompilerPathsManager.getCompilerOutputUrl(ProductionContentFolderTypeProvider.getInstance()))));
      myTestsOutputPathPanel.setText(FileUtil.toSystemDependentName(
              VfsUtilCore.urlToPath(moduleCompilerPathsManager.getCompilerOutputUrl(TestContentFolderTypeProvider.getInstance()))));
      myResourcesOutputPathPanel.setText(FileUtil.toSystemDependentName(
              VfsUtilCore.urlToPath(moduleCompilerPathsManager.getCompilerOutputUrl(ProductionResourceContentFolderTypeProvider.getInstance()))));
      myTestResourcesOutputPathPanel.setText(FileUtil.toSystemDependentName(
              VfsUtilCore.urlToPath(moduleCompilerPathsManager.getCompilerOutputUrl(TestResourceContentFolderTypeProvider.getInstance()))));
    }
    else {
      myOutputPathPanel.setText(null);
      myTestsOutputPathPanel.setText(null);
      myResourcesOutputPathPanel.setText(null);
      myTestResourcesOutputPathPanel.setText(null);
    }
  }
}
 
Example #16
Source File: ModuleImportProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
public static <C extends ModuleImportContext> void showImportChooser(@Nullable Project project, VirtualFile file, @Nonnull AsyncResult<Pair<C, ModuleImportProvider<C>>> result) {
  boolean isModuleImport = project != null;

  List<ModuleImportProvider> providers = ModuleImportProviders.getExtensions(isModuleImport);

  File ioFile = VfsUtilCore.virtualToIoFile(file);
  List<ModuleImportProvider> avaliableProviders = ContainerUtil.filter(providers, provider -> provider.canImport(ioFile));
  if (avaliableProviders.isEmpty()) {
    Alerts.okError("Cannot import anything from '" + FileUtil.toSystemDependentName(file.getPath()) + "'").showAsync();
    result.setRejected();
    return;
  }

  showImportChooser(project, file, providers, result);
}
 
Example #17
Source File: OrderEntryAppearanceServiceImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
private static CellAppearanceEx formatRelativePath(@Nonnull final ContentFolder folder, @Nonnull final Image icon) {
  LightFilePointer folderFile = new LightFilePointer(folder.getUrl());
  VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(folder.getContentEntry().getUrl());
  if (file == null) return FileAppearanceService.getInstance().forInvalidUrl(folderFile.getPresentableUrl());

  String contentPath = file.getPath();
  String relativePath;
  SimpleTextAttributes textAttributes;
  VirtualFile folderFileFile = folderFile.getFile();
  if (folderFileFile == null) {
    String absolutePath = folderFile.getPresentableUrl();
    relativePath = absolutePath.startsWith(contentPath) ? absolutePath.substring(contentPath.length()) : absolutePath;
    textAttributes = SimpleTextAttributes.ERROR_ATTRIBUTES;
  }
  else {
    relativePath = VfsUtilCore.getRelativePath(folderFileFile, file, File.separatorChar);
    textAttributes = SimpleTextAttributes.REGULAR_ATTRIBUTES;
  }

  relativePath = StringUtil.isEmpty(relativePath) ? "." + File.separatorChar : relativePath;
  return new SimpleTextCellAppearance(relativePath, icon, textAttributes);
}
 
Example #18
Source File: FileIncludeManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected VirtualFile[] computeFiles(final PsiFile file, final boolean compileTimeOnly) {
  final Set<VirtualFile> files = new THashSet<>();
  processIncludes(file, info -> {
    if (compileTimeOnly != info.runtimeOnly) {
      PsiFileSystemItem item = resolveFileInclude(info, file);
      if (item != null) {
        ContainerUtil.addIfNotNull(files, item.getVirtualFile());
      }
    }
    return true;
  });
  return VfsUtilCore.toVirtualFileArray(files);
}
 
Example #19
Source File: ModuleRootLayerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public VirtualFile[] getContentRoots() {
  final ArrayList<VirtualFile> result = new ArrayList<>();

  for (ContentEntry contentEntry : getContent()) {
    final VirtualFile file = contentEntry.getFile();
    if (file != null) {
      result.add(file);
    }
  }
  return VfsUtilCore.toVirtualFileArray(result);
}
 
Example #20
Source File: FixLineSeparatorsAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void fixSeparators(VirtualFile vFile) {
  VfsUtilCore.visitChildrenRecursively(vFile, new VirtualFileVisitor() {
    @Override
    public boolean visitFile(@Nonnull VirtualFile file) {
      if (!file.isDirectory() && !file.getFileType().isBinary()) {
        final Document document = FileDocumentManager.getInstance().getDocument(file);
        if (areSeparatorsBroken(document)) {
          fixSeparators(document);
        }
      }
      return true;
    }
  });
}
 
Example #21
Source File: WolfTheProblemSolverImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void clearInvalidFiles() {
  VirtualFile[] files;
  synchronized (myProblems) {
    files = VfsUtilCore.toVirtualFileArray(myProblems.keySet());
  }
  for (VirtualFile problemFile : files) {
    if (!problemFile.isValid() || !isToBeHighlighted(problemFile)) {
      doRemove(problemFile);
    }
  }
}
 
Example #22
Source File: FileIndexCompileScope.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public VirtualFile[] getFiles(final FileType fileType, final boolean inSourceOnly) {
  final List<VirtualFile> files = new ArrayList<VirtualFile>();
  final FileIndex[] fileIndices = getFileIndices();
  for (final FileIndex fileIndex : fileIndices) {
    fileIndex.iterateContent(new CompilerContentIterator(fileType, fileIndex, inSourceOnly, files));
  }
  return VfsUtilCore.toVirtualFileArray(files);
}
 
Example #23
Source File: FindPopupPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private String getTitle(@Nullable VirtualFile file) {
  if (file == null) return null;
  String path = VfsUtilCore.getRelativePath(file, myProject.getBaseDir());
  if (path == null) path = file.getPath();
  path = StringUtil.trimMiddle(path, 120);
  if (SystemInfo.isMacOSCatalina) {
    return "<html><body>&nbsp;&nbsp;&nbsp;" + path + "</body></html>";
  }
  return "<html><body>&nbsp;&nbsp;&nbsp;" + path.replace(file.getName(), "<b>" + file.getName() + "</b>") + "</body></html>";
}
 
Example #24
Source File: QuickFixAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @return true if immediate UI update needed.
 */
protected boolean applyFix(@Nonnull RefEntity[] refElements) {
  Set<VirtualFile> readOnlyFiles = getReadOnlyFiles(refElements);
  if (!readOnlyFiles.isEmpty()) {
    final Project project = refElements[0].getRefManager().getProject();
    final ReadonlyStatusHandler.OperationStatus operationStatus = ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(
      VfsUtilCore.toVirtualFileArray(readOnlyFiles));
    if (operationStatus.hasReadonlyFiles()) return false;
  }
  return true;
}
 
Example #25
Source File: BlameCacheImpl.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@Override
public void invalidateForRoot(@NotNull VirtualFile root) {
  LOG.debug("Invalidate for root: ", root);
  gateway.invalidateForRoot(root);
  Set<VirtualFile> files = new HashSet<>(annotations.asMap()
                                             .keySet());
  files.stream()
      .filter(file -> VfsUtilCore.isAncestor(root, file, false))
      .forEach(this::invalidate);
}
 
Example #26
Source File: ModuleRootLayerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public VirtualFile[] getSourceRoots(boolean includingTests) {
  List<VirtualFile> result = new SmartList<>();
  for (ContentEntry contentEntry : getContent()) {
    Collections.addAll(result, includingTests ? contentEntry.getFolderFiles(ContentFolderScopes.productionAndTest()) : contentEntry.getFolderFiles(ContentFolderScopes.production()));
  }
  return VfsUtilCore.toVirtualFileArray(result);
}
 
Example #27
Source File: LRUPopupBuilder.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ListPopup forFileLanguages(@Nonnull Project project, @Nonnull String title, @Nonnull Iterable<? extends VirtualFile> files, @Nonnull PerFileMappings<Language> mappings) {
  VirtualFile[] filesCopy = VfsUtilCore.toVirtualFileArray(JBIterable.from(files).toList());
  Arrays.sort(filesCopy, (o1, o2) -> StringUtil.compare(o1.getName(), o2.getName(), !o1.getFileSystem().isCaseSensitive()));
  return forFileLanguages(project, title, null, t -> {
    try {
      WriteCommandAction.writeCommandAction(project).withName(LangBundle.message("command.name.change.language")).run(() -> changeLanguageWithUndo(project, t, filesCopy, mappings));
    }
    catch (UnexpectedUndoException e) {
      LOG.error(e);
    }
  });
}
 
Example #28
Source File: CompilerUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void computeIntersectingPaths(final Project project,
                                            final Collection<VirtualFile> outputPaths,
                                            final Collection<VirtualFile> result) {
  for (Module module : ModuleManager.getInstance(project).getModules()) {
    final ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
    final VirtualFile[] sourceRoots = rootManager.getContentFolderFiles(ContentFolderScopes.productionAndTest());
    for (final VirtualFile outputPath : outputPaths) {
      for (VirtualFile sourceRoot : sourceRoots) {
        if (VfsUtilCore.isAncestor(outputPath, sourceRoot, true) || VfsUtilCore.isAncestor(sourceRoot, outputPath, false)) {
          result.add(outputPath);
        }
      }
    }
  }
}
 
Example #29
Source File: ImageUtils.java    From markdown-image-kit with MIT License 5 votes vote down vote up
/**
 * 递归遍历目录, 返回所有 Image 文件
 *
 * @param virtualFile the virtual file
 * @return the list
 */
public static List<VirtualFile> recursivelyImageFile(VirtualFile virtualFile) {
    List<VirtualFile> imageFiles = new ArrayList<>();
    /*
     * 递归遍历子文件
     *
     * @param root     the root         父文件
     * @param filter   the filter       过滤器
     * @param iterator the iterator     处理方式
     * @return the boolean
     */
    VfsUtilCore.iterateChildrenRecursively(virtualFile,
                                           file -> {
                                               // todo-dong4j : (2019年03月15日 13:02) [从 .gitignore 中获取忽略的文件]
                                               boolean allowAccept = file.isDirectory() && !file.getName().equals(MikContents.NODE_MODULES_FILE);
                                               if (allowAccept || ImageContents.IMAGE_TYPE_NAME.equals(file.getFileType().getName())) {
                                                   log.trace("accept = {}", file.getPath());
                                                   return true;
                                               }
                                               return false;
                                           },
                                           fileOrDir -> {
                                               // todo-dong4j : (2019年03月15日 13:04) [处理 markdown 逻辑实现]
                                               if (!fileOrDir.isDirectory()) {
                                                   log.trace("processFile = {}", fileOrDir.getName());
                                                   imageFiles.add(fileOrDir);
                                               }
                                               return true;
                                           });
    return imageFiles;
}
 
Example #30
Source File: ChangesUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
public static String getProjectRelativePath(@Nonnull Project project, @Nullable File fileName) {
  if (fileName == null) return null;
  VirtualFile baseDir = project.getBaseDir();
  if (baseDir == null) return fileName.toString();
  String relativePath = FileUtil.getRelativePath(VfsUtilCore.virtualToIoFile(baseDir), fileName);
  if (relativePath != null) return relativePath;
  return fileName.toString();
}