com.intellij.openapi.vfs.VirtualFileVisitor Java Examples

The following examples show how to use com.intellij.openapi.vfs.VirtualFileVisitor. 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: NewViewNameCompletionProvider.java    From idea-php-laravel-plugin with MIT License 6 votes vote down vote up
public NewViewNameCompletionProvider(VirtualFile targetDirectory) {

        completions = new ArrayList<>();

        VfsUtil.visitChildrenRecursively(targetDirectory, new VirtualFileVisitor() {
            @Override
            public boolean visitFile(@NotNull VirtualFile file) {

                if(!file.isDirectory()) {
                    return true;
                }

                String path = StringUtils.stripStart(file.getPath().replace(targetDirectory.getPath(), ""), "\\/");

                completions.add(LookupElementBuilder.create(path.replace("\\", ".").replace("/", ".") + "."));

                return true;
            }
        });
    }
 
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: NewLibraryEditor.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void collectJarFiles(@Nonnull VirtualFile dir, @Nonnull List<? super VirtualFile> container, final boolean recursively) {
  VfsUtilCore.visitChildrenRecursively(dir, new VirtualFileVisitor(VirtualFileVisitor.SKIP_ROOT, recursively ? null : VirtualFileVisitor.ONE_LEVEL_DEEP) {
    @Override
    public boolean visitFile(@Nonnull VirtualFile file) {
      FileType type;
      if (!file.isDirectory() && (type = FileTypeRegistry.getInstance().getFileTypeByFileName(file.getNameSequence())) instanceof ArchiveFileType) {
        VirtualFile jarRoot = ((ArchiveFileType)type).getFileSystem().findFileByPath(file.getPath() + URLUtil.JAR_SEPARATOR);
        if (jarRoot != null) {
          container.add(jarRoot);
          return false;
        }
      }
      return true;
    }
  });
}
 
Example #4
Source File: FileManagerImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void removeFilesAndDirsRecursively(@Nonnull VirtualFile vFile) {
  DebugUtil.performPsiModification("removeFilesAndDirsRecursively", () -> {
    VfsUtilCore.visitChildrenRecursively(vFile, new VirtualFileVisitor<Void>() {
      @Override
      public boolean visitFile(@Nonnull VirtualFile file) {
        if (file.isDirectory()) {
          getVFileToPsiDirMap().remove(file);
        }
        else {
          FileViewProvider viewProvider = getVFileToViewProviderMap().remove(file);
          if (viewProvider != null) {
            markInvalidated(viewProvider);
          }
        }
        return true;
      }
    });
  });
}
 
Example #5
Source File: RemoveBomAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void getFilesWithBom(@Nonnull VirtualFile root, @Nonnull final List<VirtualFile> result, final boolean all) {
  VfsUtilCore.visitChildrenRecursively(root, new VirtualFileVisitor() {
    @Override
    public boolean visitFile(@Nonnull VirtualFile file) {
      if (file.isDirectory()) {
        if (!all && !result.isEmpty()) {
          return false;
        }
      }
      else if (file.getBOM() != null) {
        result.add(file);
      }
      return true;
    }
  });
}
 
Example #6
Source File: PatchProjectUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void iterate(VirtualFile contentRoot, final ContentIterator iterator, final ProjectFileIndex idx) {
  VfsUtilCore.visitChildrenRecursively(contentRoot, new VirtualFileVisitor() {
    @Override
    public boolean visitFile(@Nonnull VirtualFile file) {
      if (!iterator.processFile(file)) return false;
      if (idx.getModuleForFile(file) == null) return false;  // already excluded
      return true;
    }
  });
}
 
Example #7
Source File: CommonRefactoringUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void collectReadOnlyFiles(@Nonnull VirtualFile vFile, @Nonnull final Collection<VirtualFile> list) {
  final FileTypeManager fileTypeManager = FileTypeManager.getInstance();

  VfsUtilCore.visitChildrenRecursively(vFile, new VirtualFileVisitor(VirtualFileVisitor.NO_FOLLOW_SYMLINKS) {
    @Override
    public boolean visitFile(@Nonnull VirtualFile file) {
      final boolean ignored = fileTypeManager.isFileIgnored(file);
      if (!file.isWritable() && !ignored) {
        list.add(file);
      }
      return !ignored;
    }
  });
}
 
Example #8
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 #9
Source File: FileSetCompileScope.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void addRecursively(final Collection<VirtualFile> container, VirtualFile fromDirectory, final FileType fileType) {
  VfsUtilCore.visitChildrenRecursively(fromDirectory, new VirtualFileVisitor(VirtualFileVisitor.SKIP_ROOT) {
    @Override
    public boolean visitFile(@Nonnull VirtualFile child) {
      if (!child.isDirectory() && (fileType == null || fileType.equals(child.getFileType()))) {
        container.add(child);
      }
      return true;
    }
  });
}
 
Example #10
Source File: SymlinkTestCase.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void refresh(boolean recursive) {
  final VirtualFile tempDir = myFileSystem.findFileByIoFile(myTempDir);
  assertNotNull(myTempDir.getPath(), tempDir);
  tempDir.getChildren();
  tempDir.refresh(false, true);
  if (recursive) {
    VfsUtilCore.visitChildrenRecursively(tempDir, new VirtualFileVisitor() { });
  }
}
 
Example #11
Source File: AnalysisScope.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void initFilesSet() {
  if (myType == FILE) {
    myFilesSet = new HashSet<VirtualFile>(1);
    myFilesSet.add(((PsiFileSystemItem)myElement).getVirtualFile());
  }
  else if (myType == DIRECTORY || myType == PROJECT || myType == MODULES || myType == MODULE || myType == CUSTOM) {
    myFilesSet = new HashSet<VirtualFile>();
    accept(createFileSearcher(), false);
  }
  else if (myType == VIRTUAL_FILES) {
    myFilesSet = new HashSet<VirtualFile>();
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
    for (Iterator<VirtualFile> iterator = myVFiles.iterator(); iterator.hasNext(); ) {
      final VirtualFile vFile = iterator.next();
      VfsUtilCore.visitChildrenRecursively(vFile, new VirtualFileVisitor() {
        @Nonnull
        @Override
        public Result visitFileEx(@Nonnull VirtualFile file) {
          boolean ignored = fileIndex.isExcluded(file);
          if (!ignored && !file.isDirectory()) {
            myFilesSet.add(file);
          }
          return ignored ? SKIP_CHILDREN : CONTINUE;
        }
      });

      if (vFile.isDirectory()) {
        iterator.remove();
      }
    }
  }
}
 
Example #12
Source File: YamlCompletionContributor.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
@Override
protected void addCompletions(@NotNull CompletionParameters completionParameters, final ProcessingContext processingContext, @NotNull final CompletionResultSet completionResultSet) {

    PsiFile originalFile = completionParameters.getOriginalFile();
    if(!Symfony2ProjectComponent.isEnabled(originalFile)) {
        return;
    }

    final PsiDirectory containingDirectory = originalFile.getContainingDirectory();
    if (containingDirectory == null) {
        return;
    }

    final VirtualFile containingDirectoryFiles = containingDirectory.getVirtualFile();
    VfsUtil.visitChildrenRecursively(containingDirectoryFiles, new VirtualFileVisitor() {
        @Override
        public boolean visitFile(@NotNull VirtualFile file) {

            String relativePath = VfsUtil.getRelativePath(file, containingDirectoryFiles, '/');
            if (relativePath == null) {
                return super.visitFile(file);
            }

            completionResultSet.addElement(LookupElementBuilder.create(relativePath).withIcon(file.getFileType().getIcon()));

            return super.visitFile(file);
        }
    });

}
 
Example #13
Source File: TwigUtil.java    From idea-php-symfony2-plugin with MIT License 5 votes vote down vote up
private MyLimitedVirtualFileVisitor(@NotNull Project project, @NotNull TwigPath twigPath, boolean withPhp, int maxDepth, int maxDirs) {
    super(VirtualFileVisitor.limit(maxDepth));

    this.project = project;
    this.twigPath = twigPath;
    this.withPhp = withPhp;
    this.childrenAllowToVisit = maxDirs;
}
 
Example #14
Source File: AbstractDelombokAction.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void processDirectory(@NotNull final Project project, @NotNull VirtualFile vFile) {
  VfsUtilCore.visitChildrenRecursively(vFile, new VirtualFileVisitor() {
    @Override
    public boolean visitFile(@NotNull VirtualFile file) {
      if (!file.isDirectory()) {
        processFile(project, file);
      }
      return true;
    }
  });
}
 
Example #15
Source File: HaxeLibRootDetector.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
private static boolean containsHaxeFiles(final VirtualFile dir) {
  final VirtualFileVisitor.Result result = VfsUtilCore.visitChildrenRecursively(dir, new VirtualFileVisitor() {
    @NotNull
    @Override
    public Result visitFileEx(@NotNull VirtualFile file) {
      return !file.isDirectory() && HaxeFileType.DEFAULT_EXTENSION.equalsIgnoreCase(file.getExtension()) ? skipTo(dir) : CONTINUE;
    }
  });
  return result.skipToParent != null;
}
 
Example #16
Source File: CSharpCreateFileAction.java    From consulo-csharp with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
private static boolean isCreationOfAssemblyFileAvailable(PsiDirectory directory)
{
	Module module = ModuleUtilCore.findModuleForPsiElement(directory);
	if(module != null)
	{
		DotNetModuleExtension extension = ModuleUtilCore.getExtension(module, DotNetModuleExtension.class);
		if(extension != null && extension.isAllowSourceRoots())
		{
			return false;
		}
	}
	if(module == null || ModuleUtilCore.getExtension(module, CSharpSimpleModuleExtension.class) == null)
	{
		return false;
	}

	final Ref<VirtualFile> ref = Ref.create();
	VirtualFile moduleDir = module.getModuleDir();
	if(moduleDir == null)
	{
		return false;
	}
	VfsUtil.visitChildrenRecursively(moduleDir, new VirtualFileVisitor<Object>()
	{
		@Override
		public boolean visitFile(@Nonnull VirtualFile file)
		{
			if(file.getName().equals(CSharpAssemblyConstants.FileName))
			{
				ref.set(file);
				return false;
			}
			return true;
		}
	});

	return ref.get() == null;
}
 
Example #17
Source File: ThemeUtil.java    From idea-php-shopware-plugin with MIT License 5 votes vote down vote up
public static void visitThemeAssetsFile(@NotNull PhpClass phpClass, final @NotNull ThemeAssetVisitor themeAssetVisitor) {

        PsiDirectory parent = phpClass.getContainingFile().getParent();
        if(parent == null) {
            return;
        }

        final VirtualFile publicFolder = VfsUtil.findRelativeFile(parent.getVirtualFile(), "frontend", "_public");
        if(publicFolder == null) {
            return;
        }

        // collect on project template dir
        VfsUtil.visitChildrenRecursively(publicFolder, new VirtualFileVisitor() {
            @Override
            public boolean visitFile(@NotNull VirtualFile virtualFile) {

                if(!"js".equals(virtualFile.getExtension())) {
                    return true;
                }

                String relative = VfsUtil.getRelativePath(virtualFile, publicFolder, '/');
                if(relative == null) {
                    return true;
                }

                return themeAssetVisitor.visit(virtualFile, relative);
            }
        });


    }
 
Example #18
Source File: AssetUtil.java    From idea-php-laravel-plugin with MIT License 5 votes vote down vote up
public static Collection<LookupElement> getLookupElements(@NotNull Project project) {
    Collection<LookupElement> lookupElements = new ArrayList<>();

    PsiManager psiManager = PsiManager.getInstance(project);

    for (String folder : FOLDERS) {
        VirtualFile assetDir = VfsUtil.findRelativeFile(project.getBaseDir(), folder);
        if(assetDir == null) {
            continue;
        }

        VfsUtil.visitChildrenRecursively(assetDir, new VirtualFileVisitor() {
            @Override
            public boolean visitFile(@NotNull VirtualFile virtualFile) {
                if(virtualFile.isDirectory()) {
                    return true;
                }

                String filename = VfsUtil.getRelativePath(virtualFile, assetDir, '/');
                if(filename == null || filename.startsWith(".")) {
                    return true;
                }

                PsiFile psiFile = psiManager.findFile(virtualFile);
                if(psiFile != null) {
                    LookupElementBuilder lookupElementBuilder = LookupElementBuilder.create(filename);
                    lookupElementBuilder = lookupElementBuilder.withIcon(psiFile.getIcon(0));

                    lookupElements.add(lookupElementBuilder);
                }

                return true;
            }
        });
    }

    return lookupElements;
}
 
Example #19
Source File: Glob.java    From idea-gitignore with MIT License 4 votes vote down vote up
/**
 * Finds for {@link VirtualFile} list using glob rule in given root directory.
 *
 * @param root          root directory
 * @param entries       ignore entries
 * @param includeNested attach children to the search result
 * @return search result
 */
@NotNull
public static Map<IgnoreEntry, List<VirtualFile>> find(@NotNull final VirtualFile root,
                                                       @NotNull List<IgnoreEntry> entries,
                                                       @NotNull final MatcherUtil matcher,
                                                       final boolean includeNested) {
    final ConcurrentMap<IgnoreEntry, List<VirtualFile>> result = ContainerUtil.newConcurrentMap();
    final HashMap<IgnoreEntry, Pattern> map = new HashMap<>();

    for (IgnoreEntry entry : entries) {
        result.put(entry, new ArrayList<>());

        final Pattern pattern = createPattern(entry);
        if (pattern != null) {
            map.put(entry, pattern);
        }
    }

    VirtualFileVisitor<HashMap<IgnoreEntry, Pattern>> visitor =
            new VirtualFileVisitor<HashMap<IgnoreEntry, Pattern>>(VirtualFileVisitor.NO_FOLLOW_SYMLINKS) {
                @Override
                public boolean visitFile(@NotNull VirtualFile file) {
                    if (root.equals(file)) {
                        return true;
                    }

                    final HashMap<IgnoreEntry, Pattern> current = new HashMap<>();
                    if (getCurrentValue().isEmpty()) {
                        return false;
                    }

                    final String path = Utils.getRelativePath(root, file);
                    if (path == null || Utils.isVcsDirectory(file)) {
                        return false;
                    }

                    for (Map.Entry<IgnoreEntry, Pattern> item : getCurrentValue().entrySet()) {
                        final Pattern value = item.getValue();
                        boolean matches = false;
                        if (value == null || matcher.match(value, path)) {
                            matches = true;
                            result.get(item.getKey()).add(file);
                        }
                        if (includeNested && matches) {
                            current.put(item.getKey(), null);
                        } else {
                            current.put(item.getKey(), item.getValue());
                        }
                    }

                    setValueForChildren(current);
                    return true;
                }
            };
    visitor.setValueForChildren(map);
    VfsUtil.visitChildrenRecursively(root, visitor);

    return result;
}
 
Example #20
Source File: Unity3dProjectImportUtil.java    From consulo-unity3d with Apache License 2.0 4 votes vote down vote up
private static Module createAssemblyCSharpModuleEditor(final Project project,
													   ModifiableModuleModel newModel,
													   final Sdk unityBundle,
													   MultiMap<Module, VirtualFile> virtualFilesByModule,
													   ProgressIndicator progressIndicator,
													   UnityProjectImportContext context)
{
	final List<String> paths = new ArrayList<>();
	paths.add("Assets/Standard Assets/Editor");
	paths.add("Assets/Pro Standard Assets/Editor");
	paths.add("Assets/Plugins/Editor");

	final VirtualFile baseDir = project.getBaseDir();

	final VirtualFile assetsDir = baseDir.findFileByRelativePath(ASSETS_DIRECTORY);
	if(assetsDir != null)
	{
		VfsUtil.visitChildrenRecursively(assetsDir, new VirtualFileVisitor()
		{
			@Override
			public boolean visitFile(@Nonnull VirtualFile file)
			{
				if(file.isDirectory() && "Editor".equals(file.getName()))
				{
					paths.add(VfsUtil.getRelativePath(file, baseDir, '/'));
				}
				return true;
			}
		});
	}

	final String[] pathsAsArray = ArrayUtil.toStringArray(paths);
	return createAndSetupModule("Assembly-CSharp-Editor", project, newModel, pathsAsArray, unityBundle, layer ->
	{
		if(!isVersionHigherOrEqual(unityBundle, "2018.2"))
		{
			layer.addInvalidModuleEntry(ASSEMBLY_UNITYSCRIPT_FIRSTPASS);
		}

		layer.addInvalidModuleEntry("Assembly-CSharp-firstpass");
		layer.addInvalidModuleEntry("Assembly-CSharp");

		layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEditor.Graphs"));

		if(isVersionHigherOrEqual(unityBundle, "4.6.0"))
		{
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEditor.UI"));
		}

		if(isVersionHigherOrEqual(unityBundle, "5.3.0"))
		{
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "nunit.framework"));
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEngine.TestRunner"));
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEditor.TestRunner"));

			// enable nunit
			layer.getExtensionWithoutCheck(Unity3dNUnitMutableModuleExtension.class).setEnabled(true);
		}

		if(isVersionHigherOrEqual(unityBundle, "2017.1.0"))
		{
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "UnityEditor.Timeline"));
		}

		if(isVuforiaEnabled(unityBundle, project))
		{
			layer.addOrderEntry(new DotNetLibraryOrderEntryImpl(layer, "Vuforia.UnityExtensions.Editor"));
		}
	}, "unity3d-csharp-child", CSharpFileType.INSTANCE, virtualFilesByModule, progressIndicator, context);
}