Java Code Examples for com.intellij.openapi.vfs.VirtualFile#getChildren()

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#getChildren() . These examples are extracted from open source projects. 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
/**
 * Autocomplete when inside the target part of a relative-qualified extension file, e.g. {@code
 * ":ex" => ":ext.bzl"}.
 */
private void doTargetsForRelativeExtensionFile(
    VirtualFile virtualFile, String prefixToAutocomplete, CompletionResultSet result) {
  if (!prefixToAutocomplete.startsWith(":")) {
    return;
  }
  Matcher matcher = RELATIVE_TARGET_TO_EXTENSION_FILE_PATTERN.matcher(prefixToAutocomplete);
  if (!matcher.matches()) {
    return;
  }
  String path = matcher.group("path");
  VirtualFile dir = virtualFile.findFileByRelativePath("../" + path);
  if (dir == null || !dir.isDirectory()) {
    return;
  }
  String partial = matcher.group("partial");
  for (VirtualFile child : dir.getChildren()) {
    String name = child.getName();
    if (!name.startsWith(partial)) {
      continue;
    }
    if (child.isDirectory() || name.endsWith(".bzl")) {
      addResultForFile(result, child, path + name);
    }
  }
}
 
Example 2
private String getOutputPath(VirtualFile[] virtualFiles) {
    for (VirtualFile virtualFile : virtualFiles) {
        String name = virtualFile.getName();
        VirtualFile[] childVirtualFile = virtualFile.getChildren();

        if (name.equals("res")) {
            return virtualFile.getCanonicalPath();
        } else if (childVirtualFile.length > 0) {
            String resPath = getOutputPath(childVirtualFile);
            if (resPath != null) {
                return resPath;
            }
        }
    }
    return null;
}
 
Example 3
@Nullable
private static VirtualFile findStudioProjectFile(@NotNull Project project) {
  for (PubRoot root : PubRoots.forProject(project)) {
    for (VirtualFile child : root.getRoot().getChildren()) {
      if (isProjectFileName(child.getName())) {
        return child;
      }
      if (FlutterExternalIdeActionGroup.isAndroidDirectory(child)) {
        for (VirtualFile androidChild : child.getChildren()) {
          if (isProjectFileName(androidChild.getName())) {
            return androidChild;
          }
        }
      }
    }
  }
  return null;
}
 
Example 4
Source Project: intellij-haxe   File: UsefulPsiTreeUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static void populateClassesList(List<HaxeClass> classList, Project project, VirtualFile file) {
  VirtualFile[] files = file.getChildren();
  for (VirtualFile virtualFile : files) {
    if (virtualFile.getFileType().equals(HaxeFileType.HAXE_FILE_TYPE)) {
      PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);

      String nameWithoutExtension = virtualFile.getNameWithoutExtension();

      List<HaxeClass> haxeClassList = HaxeResolveUtil.findComponentDeclarations(psiFile);
      for (HaxeClass haxeClass : haxeClassList) {
        if (Objects.equals(haxeClass.getName(), nameWithoutExtension)) {
          classList.add(haxeClass);
        }
      }
    }
  }
}
 
Example 5
private static void addUnityExtensions(List<String> list, @Nonnull Version version, String baseDir)
{
	VirtualFile dir = LocalFileSystem.getInstance().findFileByPath(baseDir);
	if(dir == null)
	{
		return;
	}

	for(VirtualFile virtualFile : dir.getChildren())
	{
		if(virtualFile.isDirectory())
		{
			addUnityExtension(list, virtualFile, version);
		}
	}
}
 
Example 6
Source Project: consulo   File: PatchProjectUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static void processIncluded(final ContentEntry contentEntry, final Set<VirtualFile> included) {
  if (included.isEmpty()) return;
  final Set<VirtualFile> parents = new HashSet<VirtualFile>();
  for (VirtualFile file : included) {
    if (Comparing.equal(file, contentEntry.getFile())) return;
    final VirtualFile parent = file.getParent();
    if (parent == null || parents.contains(parent)) continue;
    parents.add(parent);
    for (VirtualFile toExclude : parent.getChildren()) {  // if it will ever dead-loop on symlink blame anna.kozlova
      boolean toExcludeSibling = true;
      for (VirtualFile includeRoot : included) {
        if (VfsUtilCore.isAncestor(toExclude, includeRoot, false)) {
          toExcludeSibling = false;
        }
      }
      if (toExcludeSibling) {
        contentEntry.addFolder(toExclude, ExcludedContentFolderTypeProvider.getInstance());
      }
    }
  }
  processIncluded(contentEntry, parents);
}
 
Example 7
Source Project: aem-ide-tooling-4-intellij   File: Util.java    License: Apache License 2.0 6 votes vote down vote up
public static VirtualFile findFileOrFolder(VirtualFile rootFile, String name, boolean isFolder) {
    VirtualFile ret = null;
    for(VirtualFile child: rootFile.getChildren()) {
        if(child.isDirectory()) {
            if(isFolder) {
                if(child.getName().equals(name)) {
                    return child;
                }
            }
            ret = findFileOrFolder(child, name, isFolder);
            if(ret != null) { break; }
        } else {
            if(child.getName().equals(name)) {
                ret = child;
                break;
            }
        }
    }
    return ret;
}
 
Example 8
private VirtualFile findFileOrFolder(VirtualFile rootFile, String name, boolean isFolder) {
    VirtualFile ret = null;
    for(VirtualFile child: rootFile.getChildren()) {
        if(child.isDirectory()) {
            if(isFolder) {
                if(child.getName().equals(name)) {
                    return child;
                }
            }
            ret = findFileOrFolder(child, name, isFolder);
            if(ret != null) { break; }
        } else {
            if(child.getName().equals(name)) {
                ret = child;
                break;
            }
        }
    }
    return ret;
}
 
Example 9
/**
 * Autocomplete when inside the target part of a fully-qualified extension file, e.g. {@code
 * "@cell//path/to:ex" => "@cell//path/to:ext.bzl"}.
 */
private void doTargetsForFullyQualifiedExtensionFile(
    VirtualFile sourceVirtualFile,
    Project project,
    String prefixToAutocomplete,
    CompletionResultSet result) {
  Matcher matcher = TARGET_TO_EXTENSION_FILE_PATTERN.matcher(prefixToAutocomplete);
  if (!matcher.matches()) {
    return;
  }
  String cellName = matcher.group("cell");
  String cellPath = matcher.group("path");
  String extPath = matcher.group("extpath");
  BuckTargetLocator buckTargetLocator = BuckTargetLocator.getInstance(project);
  VirtualFile targetDirectory =
      BuckTargetPattern.parse(cellName + "//" + cellPath + "/" + extPath)
          .flatMap(p -> buckTargetLocator.resolve(sourceVirtualFile, p))
          .flatMap(buckTargetLocator::findVirtualFileForTargetPattern)
          .orElse(null);
  if (targetDirectory == null) {
    return;
  }
  String partialPrefix;
  if ("".equals(cellName)) {
    partialPrefix = cellPath + ":" + extPath;
  } else {
    partialPrefix = cellName + "//" + cellPath + ":" + extPath;
  }
  String partial = matcher.group("partial");
  for (VirtualFile child : targetDirectory.getChildren()) {
    String name = child.getName();
    if (!child.isDirectory() && name.startsWith(partial) && name.endsWith(".bzl")) {
      addResultForFile(result, child, partialPrefix + name);
    }
  }
}
 
Example 10
@Nullable
protected static VirtualFile findPackageDirectory(VirtualFile packagesDirectory, String packageName) {
    VirtualFile packageDir;
    for (VirtualFile packageChild : packagesDirectory.getChildren()) {
        if (packageChild.isDirectory()) {
            packageDir = packageChild.findChild(packageName);
            if (packageDir != null) {
                return packageDir;
            }
        }
    }

    return null;
}
 
Example 11
Source Project: bxfs   File: BxCore.java    License: MIT License 5 votes vote down vote up
public VirtualFile[] getSiteTemplatesComponents(String templateComponent) {
	List<VirtualFile> templates = new ArrayList<VirtualFile>();
	for (String bitrixPath : BitrixPaths) {
		VirtualFile templatesDir = project.getBaseDir().findFileByRelativePath(bitrixPath + "/templates"); if (templatesDir != null && templatesDir.isDirectory()) {
			for (VirtualFile templateDir : templatesDir.getChildren()) if (templateDir != null && templateDir.isDirectory()) {
				VirtualFile component = templateDir.findChild(templateComponent); if (component != null && !component.isDirectory() && component.isValid())
					templates.add(component);
			}
		}
	}
	return templates.toArray(new VirtualFile[templates.size()]);
}
 
Example 12
Source Project: bxfs   File: BxCore.java    License: MIT License 5 votes vote down vote up
public VirtualFile[] getComponents() {
	List<VirtualFile> components = new ArrayList<VirtualFile>();
	for (String bitrixPath : BitrixPaths) {
		VirtualFile vendorsDir = project.getBaseDir().findFileByRelativePath(bitrixPath + "/components"); if (vendorsDir != null && vendorsDir.isDirectory()) {
			for (VirtualFile componentsDir : vendorsDir.getChildren()) if (componentsDir != null && componentsDir.isDirectory()) {
				Collections.addAll(components, componentsDir.getChildren());
			}
		}
	}
	return components.toArray(new VirtualFile[components.size()]);
}
 
Example 13
Source Project: consulo   File: DvcsUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void visitVcsDirVfs(@Nonnull VirtualFile vcsDir, @Nonnull Collection<String> subDirs) {
  vcsDir.getChildren();
  for (String subdir : subDirs) {
    VirtualFile dir = vcsDir.findFileByRelativePath(subdir);
    // process recursively, because we need to visit all branches under refs/heads and refs/remotes
    ensureAllChildrenInVfs(dir);
  }
}
 
Example 14
public static List<String> getAllFilesInDirectory(VirtualFile directory, String target, String replacement) {
    List<String> files = new ArrayList<String>();
    VirtualFile[] children = directory.getChildren();
    for (VirtualFile child : children) {
        if (child instanceof VirtualDirectoryImpl) {
            files.addAll(getAllFilesInDirectory(child, target, replacement));
        } else if (child instanceof VirtualFileImpl) {
            files.add(child.getPath().replace(target, replacement));
        }
    }
    return files;
}
 
Example 15
Source Project: intellij   File: TestFileSystem.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public File[] listFiles(File file) {
  VirtualFile vf = getVirtualFile(file);
  if (vf == null) {
    return null;
  }
  VirtualFile[] children = vf.getChildren();
  if (children == null) {
    return null;
  }
  return Arrays.stream(vf.getChildren()).map((f) -> new File(f.getPath())).toArray(File[]::new);
}
 
Example 16
@Override
@NotNull
public List<IResource> members() throws IOException {
  VirtualFile folder = getVirtualFile();

  if (folder == null || !folder.exists()) {
    throw new FileNotFoundException(
        "Could not obtain child resources for " + this + " as it does not exist or is not valid");
  }

  if (!folder.isDirectory()) {
    throw new IOException(
        "Could not obtain child resources for " + this + " as it is not a directory.");
  }

  List<IResource> result = new ArrayList<>();

  VirtualFile[] children = folder.getChildren();

  for (VirtualFile child : children) {
    IPath childPath = relativePath.append(IntellijPath.fromString(child.getName()));

    result.add(
        child.isDirectory()
            ? new IntellijFolder(referencePoint, childPath)
            : new IntellijFile(referencePoint, childPath));
  }

  return result;
}
 
Example 17
Source Project: StringKiller   File: LayoutDirAction.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void actionPerformed(AnActionEvent e) {

    VirtualFile file = e.getData(PlatformDataKeys.VIRTUAL_FILE);
    if (file == null) {
        showError("找不到目标文件");
        return;
    }

    if (!file.isDirectory()) {
        showError("请选择layout文件夹");
        return;
    } else if (!file.getName().startsWith("layout")) {
        showError("请选择layout文件夹");
        return;
    }

    VirtualFile[] children = file.getChildren();

    StringBuilder sb = new StringBuilder();

    for (VirtualFile child : children) {
        layoutChild(child, sb);
    }

    VirtualFile resDir = file.getParent();
    if (resDir.getName().equalsIgnoreCase("res")) {
        VirtualFile[] chids = resDir.getChildren();
        for (VirtualFile chid : chids) {
            if (chid.getName().startsWith("values")) {
                if (chid.isDirectory()) {
                    VirtualFile[] values = chid.getChildren();
                    for (VirtualFile value : values) {
                        if (value.getName().startsWith("strings")) {
                            try {
                                String content = new String(value.contentsToByteArray(), "utf-8");
                                System.out.println("utf-8=" + content);
                                String result = content.replace("</resources>", sb.toString() + "\n</resources>");
                                FileUtils.replaceContentToFile(value.getPath(), result);
                            } catch (IOException e1) {
                                e1.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }

    e.getActionManager().getAction(IdeActions.ACTION_SYNCHRONIZE).actionPerformed(e);

}
 
Example 18
@Override
public void actionPerformed(AnActionEvent event) {
  final Project project = event.getData(CommonDataKeys.PROJECT);

  LOG.assertTrue(project != null);

  final FileChooserDescriptor descriptor = new FileChooserDescriptor(false, true, false, false, false, false){
    @Override
    public Image getIcon(VirtualFile file) {
      if (file.isDirectory()) {
        if (file.findChild(InspectionApplication.DESCRIPTIONS + ".xml") != null) {
          return AllIcons.Nodes.InspectionResults;
        }
      }
      return super.getIcon(file);
    }
  };
  descriptor.setTitle("Select Path");
  descriptor.setDescription("Select directory which contains exported inspections results");
  final VirtualFile virtualFile = FileChooser.chooseFile(descriptor, project, null);
  if (virtualFile == null || !virtualFile.isDirectory()) return;

  final Map<String, Map<String, Set<OfflineProblemDescriptor>>> resMap =
          new HashMap<String, Map<String, Set<OfflineProblemDescriptor>>>();
  final String [] profileName = new String[1];
  final Runnable process = new Runnable() {
    @Override
    public void run() {
      final VirtualFile[] files = virtualFile.getChildren();
      try {
        for (final VirtualFile inspectionFile : files) {
          if (inspectionFile.isDirectory()) continue;
          final String shortName = inspectionFile.getNameWithoutExtension();
          final String extension = inspectionFile.getExtension();
          if (shortName.equals(InspectionApplication.DESCRIPTIONS)) {
            profileName[0] = ApplicationManager.getApplication().runReadAction(
                    new Computable<String>() {
                      @Override
                      @Nullable
                      public String compute() {
                        return OfflineViewParseUtil.parseProfileName(inspectionFile);
                      }
                    }
            );
          }
          else if (XML_EXTENSION.equals(extension)) {
            resMap.put(shortName, ApplicationManager.getApplication().runReadAction(
                    new Computable<Map<String, Set<OfflineProblemDescriptor>>>() {
                      @Override
                      public Map<String, Set<OfflineProblemDescriptor>> compute() {
                        return OfflineViewParseUtil.parse(inspectionFile);
                      }
                    }
            ));
          }
        }
      }
      catch (final Exception e) {  //all parse exceptions
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            Messages.showInfoMessage(e.getMessage(), InspectionsBundle.message("offline.view.parse.exception.title"));
          }
        });
        throw new ProcessCanceledException(); //cancel process
      }
    }
  };
  ProgressManager.getInstance().runProcessWithProgressAsynchronously(project, InspectionsBundle.message("parsing.inspections.dump.progress.title"), process, new Runnable() {
    @Override
    public void run() {
      SwingUtilities.invokeLater(new Runnable(){
        @Override
        public void run() {
          final String name = profileName[0];
          showOfflineView(project, name, resMap,
                          InspectionsBundle.message("offline.view.title") +
                          " (" + (name != null ? name : InspectionsBundle.message("offline.view.editor.settings.title")) +")");
        }
      });
    }
  }, null, new PerformAnalysisInBackgroundOption(project));
}
 
Example 19
Source Project: intellij-haxe   File: HaxeModuleBuilder.java    License: Apache License 2.0 4 votes vote down vote up
private void createHelloWorldIfEligible(Module module) {
  ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
  VirtualFile[] srcDirs = rootManager.getSourceRoots();
  VirtualFile[] rootDirs = rootManager.getContentRoots();
  if(rootDirs.length != 1 || srcDirs.length != 1) {
    return;
  }

  VirtualFile root = rootDirs[0];
  VirtualFile src = srcDirs[0];

  if(src.getChildren().length != 0) {
    return;
  }
  for(VirtualFile item:root.getChildren()) {
    if(item.getExtension() == "hxml") {
      return;
    }
  }


  ApplicationManager.getApplication().runWriteAction(new Runnable() {
    @Override
    public void run() {
      try {
        VirtualFile mainHx = src.createChildData(this, "Main.hx");
        String mainHxSource = "class Main {\n"
          + "    static public function main() {\n"
          + "        trace(\"Hello, world!\");\n"
          + "    }\n"
          + "}\n";
        mainHx.setBinaryContent(mainHxSource.getBytes(StandardCharsets.UTF_8));

        VirtualFile buildHxml = root.createChildData(this, "build.hxml");
        String buildHxmlSource = "-cp src\n"
          + "-D analyzer-optimize\n"
          + "-main Main\n"
          + "--interp";
        buildHxml.setBinaryContent(buildHxmlSource.getBytes(StandardCharsets.UTF_8));

        createDefaultRunConfiguration(module, buildHxml.getPath());

        FileEditorManager editorManager = FileEditorManager.getInstance(module.getProject());
        editorManager.openFile(mainHx, true);

      } catch (IOException e) {
      }
    }
  });
}
 
Example 20
Source Project: consulo   File: FileTreeStructure.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Object[] getChildElements(Object nodeElement) {
  if (!(nodeElement instanceof FileElement)) {
    return ArrayUtil.EMPTY_OBJECT_ARRAY;
  }

  FileElement element = (FileElement)nodeElement;
  VirtualFile file = element.getFile();

  if (file == null || !file.isValid()) {
    if (element == myRootElement) {
      return myRootElement.getChildren();
    }
    return ArrayUtil.EMPTY_OBJECT_ARRAY;
  }

  VirtualFile[] children = null;

  if (element.isArchive() && myChooserDescriptor.isChooseJarContents()) {
    String path = file.getPath();
    if (!(file.getFileSystem() instanceof ArchiveFileSystem)) {
      file = ((ArchiveFileType)file.getFileType()).getFileSystem().findLocalVirtualFileByPath(path);
    }
    if (file != null) {
      children = file.getChildren();
    }
  }
  else {
    children = file.getChildren();
  }

  if (children == null) {
    return ArrayUtil.EMPTY_OBJECT_ARRAY;
  }

  Set<FileElement> childrenSet = new HashSet<FileElement>();
  for (VirtualFile child : children) {
    if (myChooserDescriptor.isFileVisible(child, myShowHidden)) {
      final FileElement childElement = new FileElement(child, child.getName());
      childElement.setParent(element);
      childrenSet.add(childElement);
    }
  }
  return ArrayUtil.toObjectArray(childrenSet);
}