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

The following examples show how to use com.intellij.openapi.vfs.VirtualFile#getParent() . 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: ProjectViewStatusCache.java    From SVNToolBox with Apache License 2.0 6 votes vote down vote up
private boolean isFirstNotEmptyParentStatusEqualTo(VirtualFile vFile, ProjectViewStatus toCheck) {
    for (VirtualFile current = vFile.getParent(); current != null; current = current.getParent()) {
        //look only in dir cache as parents for dirs and files will always be dirs
        ProjectViewStatus status = myDirBranchesCache.get(getKeyFor(current));
        if (status != null) {
            if (!status.isEmpty()) {
                if (status.isTemporary()) {
                    if (toCheck.isTemporary()) {
                        return status.equals(toCheck);
                    } else {
                        return false;    
                    }
                } else {
                    if (toCheck.isTemporary()) {
                        return true;
                    } else {
                        return status.equals(toCheck);
                    }
                }
            }
        }
    }
    return false;
}
 
Example 2
Source File: PathsVerifier.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
private VirtualFile makeSureParentPathExists(final String[] pieces) throws IOException {
  VirtualFile child = myBaseDirectory;

  final int size = (pieces.length - 1);
  for (int i = 0; i < size; i++) {
    final String piece = pieces[i];
    if (StringUtil.isEmptyOrSpaces(piece)) {
      continue;
    }
    if ("..".equals(piece)) {
      child = child.getParent();
      continue;
    }

    VirtualFile nextChild = child.findChild(piece);
    if (nextChild == null) {
      nextChild = VfsUtil.createDirectories(child.getPath() + '/' + piece);
      myCreatedDirectories.add(nextChild);
    }
    child = nextChild;
  }
  return child;
}
 
Example 3
Source File: PsiVFSListener.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void beforeFileDeletion(@Nonnull VFileDeleteEvent event) {
  final VirtualFile vFile = event.getFile();

  VirtualFile parent = vFile.getParent();
  final PsiDirectory parentDir = getCachedDirectory(parent);
  if (parentDir == null) return; // do not notify listeners if parent directory was never accessed via PSI

  runExternalAction(() -> {
    PsiFileSystemItem item = vFile.isDirectory() ? myFileManager.findDirectory(vFile) : myFileManager.getCachedPsiFile(vFile);
    if (item != null) {
      PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
      treeEvent.setParent(parentDir);
      treeEvent.setChild(item);
      myManager.beforeChildRemoval(treeEvent);
    }
  });
}
 
Example 4
Source File: ScratchUtil.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void updateFileExtension(@Nonnull Project project, @Nullable VirtualFile file) throws IOException {
  ApplicationManager.getApplication().assertWriteAccessAllowed();
  if (CommandProcessor.getInstance().getCurrentCommand() == null) {
    throw new AssertionError("command required");
  }

  if (file == null) return;
  Language language = LanguageUtil.getLanguageForPsi(project, file);
  FileType expected = getFileTypeFromName(file);
  FileType actual = language == null ? null : language.getAssociatedFileType();
  if (expected == actual || actual == null) return;
  String ext = actual.getDefaultExtension();
  if (StringUtil.isEmpty(ext)) return;

  String newName = PathUtil.makeFileName(file.getNameWithoutExtension(), ext);
  VirtualFile parent = file.getParent();
  newName = parent != null && parent.findChild(newName) != null ? PathUtil.makeFileName(file.getName(), ext) : newName;
  file.rename(ScratchUtil.class, newName);
}
 
Example 5
Source File: ServerConnectionManager.java    From aem-ide-tooling-4-intellij with Apache License 2.0 6 votes vote down vote up
private long getParentLastModificationTimestamp(
    Module module,
    String basePath,
    VirtualFile file,
    Set<String> handledPaths
) {
    long ret = -1;
    VirtualFile parentFile = file.getParent();
    messageManager.sendDebugNotification("debug.last.modification.time.parent.resource.file", parentFile);
    if(parentFile.getPath().equals(basePath)) {
        return ret;
    }
    // already published by us, a parent of another resource that was published in this execution
    if (handledPaths.contains(parentFile.getPath())) {
        return ret;
    }
    long parentLastModificationTimestamp = getParentLastModificationTimestamp(module, basePath, parentFile, handledPaths);
    ret = Math.max(parentLastModificationTimestamp, ret);
    long timestamp = file.getTimeStamp();
    long fileTimestamp = Util.getModificationStamp(file);
    if(fileTimestamp > 0) {
        ret = Math.max(timestamp, ret);
    }
    return ret;
}
 
Example 6
Source File: VirtualFileRepoCache.java    From GitToolBox with Apache License 2.0 5 votes vote down vote up
@Nullable
default GitRepository getRepoForFile(@NotNull VirtualFile file) {
  Preconditions.checkArgument(!file.isDirectory(), "%s is not file", file);
  VirtualFile parent = file.getParent();
  if (parent != null && parent.isDirectory()) {
    return getRepoForDir(parent);
  }
  return null;
}
 
Example 7
Source File: SelfElementInfo.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static VirtualFile restoreVFile(@Nonnull VirtualFile virtualFile) {
  VirtualFile child;
  if (virtualFile.isValid()) {
    child = virtualFile;
  }
  else {
    VirtualFile vParent = virtualFile.getParent();
    if (vParent == null || !vParent.isValid()) return null;
    String name = virtualFile.getName();
    child = vParent.findChild(name);
  }
  return child;
}
 
Example 8
Source File: FileManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void forceReload(@Nonnull VirtualFile vFile) {
  LanguageSubstitutors.cancelReparsing(vFile);
  FileViewProvider viewProvider = findCachedViewProvider(vFile);
  if (viewProvider == null) {
    return;
  }
  ApplicationManager.getApplication().assertWriteAccessAllowed();

  VirtualFile dir = vFile.getParent();
  PsiDirectory parentDir = dir == null ? null : getCachedDirectory(dir);
  PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(myManager);
  if (parentDir == null) {
    event.setPropertyName(PsiTreeChangeEvent.PROP_UNLOADED_PSI);

    myManager.beforePropertyChange(event);
    setViewProvider(vFile, null);
    myManager.propertyChanged(event);
  }
  else {
    event.setParent(parentDir);

    myManager.beforeChildrenChange(event);
    setViewProvider(vFile, null);
    myManager.childrenChanged(event);
  }
}
 
Example 9
Source File: AwesomeLinkFilter.java    From intellij-awesome-console with MIT License 5 votes vote down vote up
public List<VirtualFile> getResultItemsFileFromBasename(final String match, final int depth) {
	final ArrayList<VirtualFile> matches = new ArrayList<>();
	final char packageSeparator = '.';
	final int index = match.lastIndexOf(packageSeparator);
	if (-1 >= index) {
		return matches;
	}
	final String basename = match.substring(index + 1);
	final String origin = match.substring(0, index);
	final String path = origin.replace(packageSeparator, File.separatorChar);
	if (0 >= basename.length()) {
		return matches;
	}
	if (!fileBaseCache.containsKey(basename)) {
		/* Try to search deeper down the rabbit hole */
		if (depth <= maxSearchDepth) {
			return getResultItemsFileFromBasename(origin, depth + 1);
		}
		return matches;
	}
	for (final VirtualFile file : fileBaseCache.get(basename)) {
		final VirtualFile parent = file.getParent();
		if (null == parent) {
			continue;
		}
		if (!matchSource(parent.getPath(), path)) {
			continue;
		}
		matches.add(file);
	}
	return matches;
}
 
Example 10
Source File: FileWatch.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Returns true if the given VirtualFile is at this location.
 */
boolean matches(VirtualFile file) {
  for (String name : reversedNames) {
    if (file == null || !file.getName().equals(name)) {
      return false;
    }
    file = file.getParent();
  }
  return base.equals(file);
}
 
Example 11
Source File: BlazePackageHeuristic.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private static WorkspacePath findBlazePackage(Project project, @Nullable VirtualFile vf) {
  BuildSystemProvider provider = Blaze.getBuildSystemProvider(project);
  WorkspaceRoot root = WorkspaceRoot.fromProjectSafe(project);
  if (root == null) {
    return null;
  }
  while (vf != null) {
    if (vf.isDirectory() && provider.findBuildFileInDirectory(vf) != null) {
      return root.workspacePathForSafe(new File(vf.getPath()));
    }
    vf = vf.getParent();
  }
  return null;
}
 
Example 12
Source File: MultipleFileMergeDialog.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void customizeCellRenderer(JTable table, Object value, boolean selected, boolean hasFocus, int row, int column) {
  VirtualFile vf = (VirtualFile)value;
  setIcon(VirtualFilePresentation.getIcon(vf));
  append(vf.getName(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
  final VirtualFile parent = vf.getParent();
  if (parent != null) {
    append(" (" + FileUtil.toSystemDependentName(parent.getPresentableUrl()) + ")", SimpleTextAttributes.GRAYED_ATTRIBUTES);
  }
}
 
Example 13
Source File: FlutterExternalIdeActionGroup.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected static boolean isWithinIOsDirectory(@NotNull VirtualFile file, @NotNull Project project) {
  final VirtualFile baseDir = project.getBaseDir();
  if (baseDir == null) {
    return false;
  }
  VirtualFile candidate = file;
  while (candidate != null && !baseDir.equals(candidate)) {
    if (isIOsDirectory(candidate)) {
      return true;
    }
    candidate = candidate.getParent();
  }
  return false;
}
 
Example 14
Source File: ProjectRootsUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static boolean isLibraryRoot(final VirtualFile directoryFile, final Project project) {
  final ProjectFileIndex projectFileIndex = ProjectRootManager.getInstance(project).getFileIndex();
  if (projectFileIndex.isInLibraryClasses(directoryFile)) {
    final VirtualFile parent = directoryFile.getParent();
    return parent == null || !projectFileIndex.isInLibraryClasses(parent);
  }
  return false;
}
 
Example 15
Source File: FileListRenderer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void customizeCellRenderer(@Nonnull JList list, Object value, int index, boolean selected, boolean hasFocus) {
  // paint selection only as a focus rectangle
  mySelected = false;
  setBackground(null);
  VirtualFile vf = (VirtualFile) value;
  setIcon(VirtualFilePresentation.getIcon(vf));
  append(vf.getName(), SimpleTextAttributes.REGULAR_ATTRIBUTES);
  VirtualFile parent = vf.getParent();
  if (parent != null) {
    append(" (" + FileUtil.toSystemDependentName(parent.getPath()) + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
  }
}
 
Example 16
Source File: EnvCompositePart.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
private VirtualFile scanParentsForFile(@NotNull VirtualFile initialDir, @NotNull String fileName) {
    VirtualFile prevParent;
    VirtualFile parent = initialDir;
    do {
        VirtualFile f = parent.findChild(fileName);
        if (f != null && f.exists()) {
            return getFileAt(parent.getPath(), fileName);
        }
        prevParent = parent;
        parent = parent.getParent();
    } while (parent != null && !parent.equals(prevParent));
    return null;
}
 
Example 17
Source File: ConvertAction.java    From AndroidLocalizePlugin with Apache License 2.0 5 votes vote down vote up
/**
 * Verify that the selected file is a strings.xml file.
 *
 * @param file selected file
 * @return true: indicating that the selected file is the strings.xml file.
 */
private boolean isSelectStringsFile(VirtualFile file) {
    if (file == null) return false;

    VirtualFile parent = file.getParent();
    if (parent == null) return false;

    String parentName = parent.getName();
    if (!"values".equals(parentName)) return false;

    return "strings.xml".equals(file.getName());
}
 
Example 18
Source File: MacPathChooserDialog.java    From consulo with Apache License 2.0 4 votes vote down vote up
@RequiredUIAccess
@Nonnull
@Override
public AsyncResult<VirtualFile[]> chooseAsync(@Nullable VirtualFile toSelect) {
  if (toSelect != null && toSelect.getParent() != null) {
    String directoryName;
    String fileName = null;
    if (toSelect.isDirectory()) {
      directoryName = toSelect.getCanonicalPath();
    }
    else {
      directoryName = toSelect.getParent().getCanonicalPath();
      fileName = toSelect.getPath();
    }
    myFileDialog.setDirectory(directoryName);
    myFileDialog.setFile(fileName);
  }


  myFileDialog.setFilenameFilter((dir, name) -> {
    File file = new File(dir, name);
    return myFileChooserDescriptor.isFileSelectable(fileToVirtualFile(file));
  });

  myFileDialog.setMultipleMode(myFileChooserDescriptor.isChooseMultiple());

  AsyncResult<VirtualFile[]> result = AsyncResult.undefined();
  SwingUtilities.invokeLater(() -> {
    final CommandProcessorEx commandProcessor = ApplicationManager.getApplication() != null ? (CommandProcessorEx)CommandProcessor.getInstance() : null;
    final boolean appStarted = commandProcessor != null;

    if (appStarted) {
      commandProcessor.enterModal();
      LaterInvocator.enterModal(myFileDialog);
    }

    Component parent = myParent.get();
    try {
      myFileDialog.setVisible(true);
    }
    finally {
      if (appStarted) {
        commandProcessor.leaveModal();
        LaterInvocator.leaveModal(myFileDialog);
        if (parent != null) {
          IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> {
            IdeFocusManager.getGlobalInstance().requestFocus(parent, true);
          });
        }
      }
    }

    File[] files = myFileDialog.getFiles();
    List<VirtualFile> virtualFileList = getChosenFiles(Stream.of(files));
    virtualFiles = virtualFileList.toArray(VirtualFile.EMPTY_ARRAY);

    if (!virtualFileList.isEmpty()) {
      try {
        if (virtualFileList.size() == 1) {
          myFileChooserDescriptor.isFileSelectable(virtualFileList.get(0));
        }
        myFileChooserDescriptor.validateSelectedFiles(virtualFiles);
      }
      catch (Exception e) {
        if (parent == null) {
          Messages.showErrorDialog(myProject, e.getMessage(), myTitle);
        }
        else {
          Messages.showErrorDialog(parent, e.getMessage(), myTitle);
        }

        result.setRejected();
        return;
      }

      if (!ArrayUtil.isEmpty(files)) {
        result.setDone(VfsUtil.toVirtualFileArray(virtualFileList));
      }
      else {
        result.setRejected();
      }
    }
  });
  return result;
}
 
Example 19
Source File: FileTree.java    From consulo with Apache License 2.0 4 votes vote down vote up
void add(VirtualFile file) {
  if (myFiles.contains(file)) {
    return;
  }

  VirtualFile dir = file.getParent();
  if (dir == null) {
    LOG.error(file);
    return;
  }

  myFiles.add(file);

  List<VirtualFile> children = myStrictDirectory2Children.get(dir);
  if (children != null) {
    LOG.assertTrue(!children.contains(file));
    children.add(file);
  }
  else {
    children = ContainerUtil.createConcurrentList();
    children.add(file);
    myStrictDirectory2Children.put(dir, children);
  }

  children = myDirectory2Children.get(dir);
  if (children != null) {
    LOG.assertTrue(!children.contains(file));
    children.add(file);
    return;
  }
  else {
    children = ContainerUtil.createConcurrentList();
    children.add(file);
    myDirectory2Children.put(dir, children);
  }

  VirtualFile parent = dir.getParent();
  while (parent != null) {
    children = myDirectory2Children.get(parent);
    if (children != null) {
      if ((!children.contains(dir))) {
        children.add(dir);
      }
      return;
    }
    else {
      children = ContainerUtil.createConcurrentList();
      children.add(dir);
      myDirectory2Children.put(parent, children);
    }
    dir = parent;
    parent = parent.getParent();
  }
}
 
Example 20
Source File: FileParentDirMacro.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static String parentPath(@Nullable VirtualFile vFile) {
  if(vFile != null) {
    vFile = vFile.getParent();
  }
  return vFile != null ? getPath(vFile) : null;
}