Java Code Examples for com.intellij.openapi.vfs.VfsUtilCore#getRelativePath()

The following examples show how to use com.intellij.openapi.vfs.VfsUtilCore#getRelativePath() . 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: BaseIconProvider.java    From intellij-extra-icons-plugin with MIT License 6 votes vote down vote up
/**
 * Indicates if given file/folder should be ignored.
 * @param project project.
 * @param file current file or folder.
 */
private boolean isPatternIgnored(Project project, VirtualFile file) {
    SettingsService service = getSettingsService(project);
    if (service.getIgnoredPatternObj() == null || service.getIgnoredPattern() == null || service.getIgnoredPattern().isEmpty()) {
        return false;
    }
    VirtualFile contentRoot = ProjectFileIndex.SERVICE.getInstance(project).getContentRootForFile(file);
    if (contentRoot == null) {
        return false;
    }
    String relativePath = VfsUtilCore.getRelativePath(file, contentRoot);
    if (relativePath == null) {
        return false;
    }
    return service.getIgnoredPatternObj().matcher(relativePath).matches();
}
 
Example 2
Source File: MoveDirectoryWithClassesProcessor.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void collectFiles2Move(Map<PsiFile, TargetDirectoryWrapper> files2Move,
                                   PsiDirectory directory,
                                   PsiDirectory rootDirectory,
                                   @Nonnull TargetDirectoryWrapper targetDirectory) {
  final PsiElement[] children = directory.getChildren();
  final String relativePath = VfsUtilCore.getRelativePath(directory.getVirtualFile(), rootDirectory.getVirtualFile(), '/');

  final TargetDirectoryWrapper newTargetDirectory = relativePath.length() == 0
                                                    ? targetDirectory
                                                    : targetDirectory.findOrCreateChild(relativePath);
  for (PsiElement child : children) {
    if (child instanceof PsiFile) {
      files2Move.put((PsiFile)child, newTargetDirectory);
    }
    else if (child instanceof PsiDirectory){
      collectFiles2Move(files2Move, (PsiDirectory)child, directory, newTargetDirectory);
    }
  }
}
 
Example 3
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 4
Source File: FilePatternPackageSet.java    From consulo with Apache License 2.0 6 votes vote down vote up
@javax.annotation.Nullable
public static String getRelativePath(@Nonnull VirtualFile virtualFile,
                                     @Nonnull ProjectFileIndex index,
                                     final boolean useFQName,
                                     VirtualFile projectBaseDir) {
  final VirtualFile contentRootForFile = index.getContentRootForFile(virtualFile);
  if (contentRootForFile != null) {
    return VfsUtilCore.getRelativePath(virtualFile, contentRootForFile, '/');
  }
  final Module module = index.getModuleForFile(virtualFile);
  if (module != null) {
    if (projectBaseDir != null) {
      if (VfsUtilCore.isAncestor(projectBaseDir, virtualFile, false)){
        final String projectRelativePath = VfsUtilCore.getRelativePath(virtualFile, projectBaseDir, '/');
        return useFQName ? projectRelativePath : projectRelativePath.substring(projectRelativePath.indexOf('/') + 1);
      }
    }
    return virtualFile.getPath();
  } else {
    return getLibRelativePath(virtualFile, index);
  }
}
 
Example 5
Source File: PsiTypeUtils.java    From intellij-quarkus with Eclipse Public License 2.0 6 votes vote down vote up
public static String getLocation(Project project, VirtualFile directory) {
    String location = null;
    Module module = ProjectFileIndex.getInstance(project).getModuleForFile(directory);
    if (module != null) {
        VirtualFile moduleRoot = LocalFileSystem.getInstance().findFileByIoFile(new File(module.getModuleFilePath()).getParentFile());
        String path = VfsUtilCore.getRelativePath(directory, moduleRoot);
        if (path != null) {
            location = '/' + module.getName() + '/' + path;
        }
    }
    if (location == null) {
        location = directory.getPath();
    }
    if (location.endsWith("!/")) {
        location = location.substring(0, location.length() - 2);
    }
    return location;
}
 
Example 6
Source File: ArtifactUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String getRelativePathInSources(@Nonnull VirtualFile file,
                                               final @Nonnull ModuleOutputPackagingElement moduleElement,
                                               @Nonnull PackagingElementResolvingContext context) {
  for (VirtualFile sourceRoot : moduleElement.getSourceRoots(context)) {
    if (VfsUtil.isAncestor(sourceRoot, file, true)) {
      return VfsUtilCore.getRelativePath(file, sourceRoot, '/');
    }
  }
  return null;
}
 
Example 7
Source File: VcsImplUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String getShortVcsRootName(@Nonnull Project project, @Nonnull VirtualFile root) {
  VirtualFile projectDir = project.getBaseDir();

  String repositoryPath = root.getPresentableUrl();
  if (projectDir != null) {
    String relativePath = VfsUtilCore.getRelativePath(root, projectDir, File.separatorChar);
    if (relativePath != null) {
      repositoryPath = relativePath;
    }
  }

  return repositoryPath.isEmpty() ? root.getName() : repositoryPath;
}
 
Example 8
Source File: FileIncludeContextHectorPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
protected String getPath(final Object value) {
  final VirtualFile file = (VirtualFile)value;
  final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myFile.getProject()).getFileIndex();
  if (file != null) {
    VirtualFile root = fileIndex.getSourceRootForFile(file);
    if (root == null) {
      root = fileIndex.getContentRootForFile(file);
    }
    if (root != null) {
      return VfsUtilCore.getRelativePath(file, root, '/');
    }
  }
  return null;
}
 
Example 9
Source File: BlazeCppAutoImportHelper.java    From intellij with Apache License 2.0 5 votes vote down vote up
@Nullable
private static ImportSpecification findMatchingRoot(
    VirtualFile fileToImport, List<HeadersSearchRoot> roots, boolean asUserHeader) {
  for (HeadersSearchRoot root : roots) {
    if (!(root instanceof IncludedHeadersRoot)) {
      continue;
    }
    IncludedHeadersRoot includedHeadersRoot = (IncludedHeadersRoot) root;
    if (asUserHeader != includedHeadersRoot.isUserHeaders()) {
      continue;
    }
    VirtualFile rootBase = root.getVirtualFile();
    if (rootBase == null) {
      continue;
    }
    String relativePath = VfsUtilCore.getRelativePath(fileToImport, rootBase);
    if (relativePath == null) {
      continue;
    }
    return new ImportSpecification(
        relativePath,
        asUserHeader
            ? ImportSpecification.Kind.USER_HEADER_SEARCH_PATH
            : ImportSpecification.Kind.SYSTEM_HEADER_SEARCH_PATH);
  }
  return null;
}
 
Example 10
Source File: SymbolPresentationUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static String getFilePathPresentation(PsiFile psiFile) {
  ProjectFileIndex index = ProjectRootManager.getInstance(psiFile.getProject()).getFileIndex();
  VirtualFile file = psiFile.getOriginalFile().getVirtualFile();
  VirtualFile rootForFile = file != null ? index.getContentRootForFile(file):null;

  if (rootForFile != null) {
    String relativePath = VfsUtilCore.getRelativePath(file, rootForFile, File.separatorChar);
    if (relativePath != null) return relativePath;
  }

  return psiFile.getName();
}
 
Example 11
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 12
Source File: DirectoryNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
private String getContentRootName(final VirtualFile baseDir, final String dirName) {
  if (baseDir != null) {
    if (!Comparing.equal(myVDirectory, baseDir)) {
      if (VfsUtil.isAncestor(baseDir, myVDirectory, false)) {
        return VfsUtilCore.getRelativePath(myVDirectory, baseDir, '/');
      }
      else {
        return myVDirectory.getPresentableUrl();
      }
    }
  } else {
    return myVDirectory.getPresentableUrl();
  }
  return dirName;
}
 
Example 13
Source File: DirectoryNode.java    From consulo with Apache License 2.0 5 votes vote down vote up
public String getFQName() {
  final ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex();
  VirtualFile directory = myVDirectory;
  VirtualFile contentRoot = index.getContentRootForFile(directory);
  if (Comparing.equal(directory, contentRoot)) {
    return "";
  }
  if (contentRoot == null) {
    return "";
  }
  return VfsUtilCore.getRelativePath(directory, contentRoot, '/');
}
 
Example 14
Source File: DetectedRootsChooserDialog.java    From consulo with Apache License 2.0 4 votes vote down vote up
private static CheckboxTreeTable createTreeTable(List<SuggestedChildRootInfo> suggestedRoots) {
  final CheckedTreeNode root = createRoot(suggestedRoots);
  CheckboxTreeTable treeTable = new CheckboxTreeTable(root, new CheckboxTree.CheckboxTreeCellRenderer(true) {
    @Override
    public void customizeRenderer(JTree tree,
                                      Object value,
                                      boolean selected,
                                      boolean expanded,
                                      boolean leaf,
                                      int row,
                                      boolean hasFocus) {
      if (!(value instanceof VirtualFileCheckedTreeNode)) return;
      VirtualFileCheckedTreeNode node = (VirtualFileCheckedTreeNode)value;
      VirtualFile file = node.getFile();
      String text;
      SimpleTextAttributes attributes;
      Icon icon;
      boolean isValid = true;
      if (leaf) {
        VirtualFile ancestor = ((VirtualFileCheckedTreeNode)node.getParent()).getFile();
        if (ancestor != null) {
          text = VfsUtilCore.getRelativePath(file, ancestor, File.separatorChar);
          if (StringUtil.isEmpty(text)) {
            text = File.separator;
          }
        }
        else {
          text = file.getPresentableUrl();
        }
        if (text == null) {
          isValid = false;
          text = file.getPresentableUrl();
        }
        attributes = SimpleTextAttributes.REGULAR_ATTRIBUTES;
        icon = AllIcons.Nodes.TreeClosed;
      }
      else {
        text = file.getPresentableUrl();
        if (text == null) {
          isValid = false;
        }
        attributes = SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES;
        icon = AllIcons.Nodes.TreeClosed;
      }
      final ColoredTreeCellRenderer textRenderer = getTextRenderer();
      textRenderer.setIcon(icon);
      if (!isValid) {
        textRenderer.append("[INVALID] ", SimpleTextAttributes.ERROR_ATTRIBUTES);
      }
      if (text != null) {
        textRenderer.append(text, attributes);
      }
    }
  }, new ColumnInfo[]{ROOT_COLUMN, ROOT_TYPE_COLUMN});

  int max = 0;
  for (SuggestedChildRootInfo info : suggestedRoots) {
    for (String s : info.getRootTypeNames()) {
      max = Math.max(max, treeTable.getFontMetrics(treeTable.getFont()).stringWidth(s));
    }
  }
  final TableColumn column = treeTable.getColumnModel().getColumn(1);
  int width = max + 20;//add space for combobox button
  column.setPreferredWidth(width);
  column.setMaxWidth(width);
  treeTable.setRootVisible(false);
  TreeUtil.expandAll(treeTable.getTree());
  return treeTable;
}
 
Example 15
Source File: DirectoryNode.java    From consulo with Apache License 2.0 4 votes vote down vote up
public DirectoryNode(VirtualFile aDirectory,
                     Project project,
                     boolean compactPackages,
                     boolean showFQName,
                     VirtualFile baseDir, final VirtualFile[] contentRoots) {
  super(project);
  myVDirectory = aDirectory;
  final ProjectRootManager projectRootManager = ProjectRootManager.getInstance(project);
  final ProjectFileIndex index = projectRootManager.getFileIndex();
  String dirName = aDirectory.getName();
  if (showFQName) {
    final VirtualFile contentRoot = index.getContentRootForFile(myVDirectory);
    if (contentRoot != null) {
      if (Comparing.equal(myVDirectory, contentRoot)) {
        myFQName = dirName;
      }
      else {
        final VirtualFile sourceRoot = index.getSourceRootForFile(myVDirectory);
        if (Comparing.equal(myVDirectory, sourceRoot)) {
          myFQName = VfsUtilCore.getRelativePath(myVDirectory, contentRoot, '/');
        }
        else if (sourceRoot != null) {
          myFQName = VfsUtilCore.getRelativePath(myVDirectory, sourceRoot, '/');
        }
        else {
          myFQName = VfsUtilCore.getRelativePath(myVDirectory, contentRoot, '/');
        }
      }

      if (contentRoots.length > 1 && ProjectRootsUtil.isModuleContentRoot(myVDirectory, project)) {
        myFQName = getContentRootName(baseDir, myFQName);
      }
    }
    else {
      myFQName = FilePatternPackageSet.getLibRelativePath(myVDirectory, index);
    }
    dirName = myFQName;
  } else {
    if (contentRoots.length > 1 && ProjectRootsUtil.isModuleContentRoot(myVDirectory, project)) {
      dirName = getContentRootName(baseDir, dirName);
    }
  }
  myDirName = dirName;
  myCompactPackages = compactPackages;
}
 
Example 16
Source File: GotoFileCellRenderer.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nonnull
static String getRelativePathFromRoot(@Nonnull VirtualFile file, @Nonnull VirtualFile root) {
  return root.getName() + File.separatorChar + VfsUtilCore.getRelativePath(file, root, File.separatorChar);
}
 
Example 17
Source File: DuplicatesInspectionBase.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public ProblemDescriptor[] checkFile(@Nonnull final PsiFile psiFile, @Nonnull final InspectionManager manager, final boolean isOnTheFly) {
  final VirtualFile virtualFile = psiFile.getVirtualFile();
  if (!(virtualFile instanceof VirtualFileWithId) || /*!isOnTheFly || */!DuplicatesIndex.ourEnabled) return ProblemDescriptor.EMPTY_ARRAY;
  final DuplicatesProfile profile = DuplicatesIndex.findDuplicatesProfile(psiFile.getFileType());
  if (profile == null) return ProblemDescriptor.EMPTY_ARRAY;


  final FileASTNode node = psiFile.getNode();
  boolean usingLightProfile = profile instanceof LightDuplicateProfile &&
                              node.getElementType() instanceof ILightStubFileElementType &&
                              DuplicatesIndex.ourEnabledLightProfiles;
  final Project project = psiFile.getProject();
  DuplicatedCodeProcessor<?> processor;
  if (usingLightProfile) {
    processor = processLightDuplicates(node, virtualFile, (LightDuplicateProfile)profile, project);
  }
  else {
    processor = processPsiDuplicates(psiFile, virtualFile, profile, project);
  }
  if (processor == null) return null;

  final SmartList<ProblemDescriptor> descriptors = new SmartList<>();
  final VirtualFile baseDir = project.getBaseDir();
  for (Map.Entry<Integer, TextRange> entry : processor.reportedRanges.entrySet()) {
    final Integer offset = entry.getKey();
    if (!usingLightProfile && processor.fragmentSize.get(offset) < MIN_FRAGMENT_SIZE) continue;
    final VirtualFile file = processor.reportedFiles.get(offset);
    String path = null;

    if (file.equals(virtualFile)) {
      path = "this file";
    }
    else if (baseDir != null) {
      path = VfsUtilCore.getRelativePath(file, baseDir);
    }
    if (path == null) {
      path = file.getPath();
    }
    String message = "Found duplicated code in " + path;

    PsiElement targetElement = processor.reportedPsi.get(offset);
    TextRange rangeInElement = entry.getValue();
    final int offsetInOtherFile = processor.reportedOffsetInOtherFiles.get(offset);

    LocalQuickFix fix = isOnTheFly ? createNavigateToDupeFix(file, offsetInOtherFile) : null;
    long hash = processor.fragmentHash.get(offset);

    int hash2 = (int)(hash >> 32);
    LocalQuickFix viewAllDupesFix = isOnTheFly && hash != 0 ? createShowOtherDupesFix(virtualFile, offset, (int)hash, hash2) : null;

    boolean onlyExtractable = Registry.is("duplicates.inspection.only.extractable");
    LocalQuickFix extractMethodFix =
      (isOnTheFly || onlyExtractable) && hash != 0 ? createExtractMethodFix(targetElement, rangeInElement, (int)hash, hash2) : null;
    if (onlyExtractable) {
      if (extractMethodFix == null) return null;
      if (!isOnTheFly) extractMethodFix = null;
    }

    ProblemDescriptor descriptor = manager
      .createProblemDescriptor(targetElement, rangeInElement, message, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly, fix,
                               viewAllDupesFix, extractMethodFix);
    descriptors.add(descriptor);
  }

  return descriptors.isEmpty() ? null : descriptors.toArray(ProblemDescriptor.EMPTY_ARRAY);
}
 
Example 18
Source File: Utils.java    From idea-gitignore with MIT License 2 votes vote down vote up
/**
 * Gets relative path of given @{link VirtualFile} and root directory.
 *
 * @param directory root directory
 * @param file      file to get it's path
 * @return relative path
 */
@Nullable
public static String getRelativePath(@NotNull VirtualFile directory, @NotNull VirtualFile file) {
    final String path = VfsUtilCore.getRelativePath(file, directory, '/');
    return path == null ? null : path + (file.isDirectory() ? '/' : "");
}