public static boolean isInDartSdkOrDartPackagesFolder(
      final Project project, final VirtualFile file) {
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();

    if (!fileIndex.isInContent(file)
        && (fileIndex.isInLibrarySource(file) || fileIndex.isInLibraryClasses(file))) {
      return true; // file in SDK
    }

    if (fileIndex.isInContent(file) && isInDartPackagesFolder(fileIndex, file)) {
      return true; // symlinked child of 'packages' folder. Real location is in user cache folder
                   // for Dart packages, not in project
    }

    return false;
  }
  private static THashSet<String> collectFoldersToExclude(
      final Module module, final VirtualFile pubspecYamlFile) {
    final THashSet<String> newExcludedPackagesUrls = new THashSet<String>();
    final ProjectFileIndex fileIndex =
        ProjectRootManager.getInstance(module.getProject()).getFileIndex();
    final VirtualFile root = pubspecYamlFile.getParent();

    final VirtualFile binFolder = root.findChild("bin");
    if (binFolder != null && binFolder.isDirectory() && fileIndex.isInContent(binFolder)) {
      newExcludedPackagesUrls.add(binFolder.getUrl() + "/packages");
    }

    appendPackagesFolders(newExcludedPackagesUrls, root.findChild("benchmark"), fileIndex);
    appendPackagesFolders(newExcludedPackagesUrls, root.findChild("example"), fileIndex);
    appendPackagesFolders(newExcludedPackagesUrls, root.findChild("test"), fileIndex);
    appendPackagesFolders(newExcludedPackagesUrls, root.findChild("tool"), fileIndex);
    appendPackagesFolders(newExcludedPackagesUrls, root.findChild("web"), fileIndex);

    // Folder packages/ThisProject (where ThisProject is the name specified in pubspec.yaml) is a
    // symlink to local 'lib' folder. Exclude it in order not to have duplicates. Resolve goes to
    // local 'lib' folder.
    // Empty 'ThisProject (link to 'lib' folder)' node is added to Project Structure by
    // DartTreeStructureProvider
    final VirtualFile libFolder = root.findChild("lib");
    if (libFolder != null && libFolder.isDirectory()) {
      final String pubspecName = PubspecYamlUtil.getPubspecName(pubspecYamlFile);
      if (pubspecName != null) {
        newExcludedPackagesUrls.add(root.getUrl() + "/packages/" + pubspecName);
      }
    }

    return newExcludedPackagesUrls;
  }
  @Nullable
  public static PsiDirectory selectDirectory(
      Project project,
      PsiDirectory[] packageDirectories,
      PsiDirectory defaultDirectory,
      String postfixToShow) {
    ProjectFileIndex projectFileIndex = getInstance(project).getFileIndex();

    ArrayList<PsiDirectory> possibleDirs = new ArrayList<>();
    for (PsiDirectory dir : packageDirectories) {
      if (!dir.isValid()) continue;
      if (!dir.isWritable()) continue;
      if (possibleDirs.contains(dir)) continue;
      if (!projectFileIndex.isInContent(dir.getVirtualFile())) continue;
      possibleDirs.add(dir);
    }

    if (possibleDirs.isEmpty()) return null;
    if (possibleDirs.size() == 1) return possibleDirs.get(0);

    if (getApplication().isUnitTestMode()) return possibleDirs.get(0);

    DirectoryChooser chooser = new DirectoryChooser(project);
    chooser.setTitle(message("title.choose.destination.directory"));
    chooser.fillList(
        possibleDirs.toArray(new PsiDirectory[possibleDirs.size()]),
        defaultDirectory,
        project,
        postfixToShow);
    return chooser.showAndGet() ? chooser.getSelectedDirectory() : null;
  }
  private static boolean isInDartPackagesFolder(
      final ProjectFileIndex fileIndex, final VirtualFile file) {
    VirtualFile parent = file;
    while ((parent = parent.getParent()) != null && fileIndex.isInContent(parent)) {
      if ("packages".equals(parent.getName())) {
        return VfsUtilCore.findRelativeFile("../pubspec.yaml", parent) != null;
      }
    }

    return false;
  }
  private static boolean isInDartPackagesFolder(
      final ProjectFileIndex fileIndex, final VirtualFile file) {
    VirtualFile parent = file;
    while ((parent = parent.getParent()) != null && fileIndex.isInContent(parent)) {
      if (DartUrlResolver.PACKAGES_FOLDER_NAME.equals(parent.getName())) {
        return VfsUtilCore.findRelativeFile("../" + PUBSPEC_YAML, parent) != null;
      }
    }

    return false;
  }
 @Nullable
 private VirtualFile getFileRoot(VirtualFile file) {
   if (myIndex.isLibraryClassFile(file)) {
     return myIndex.getClassRootForFile(file);
   }
   if (myIndex.isInContent(file)) {
     return myIndex.getSourceRootForFile(file);
   }
   if (myIndex.isInLibraryClasses(file)) {
     return myIndex.getClassRootForFile(file);
   }
   return null;
 }
Ejemplo n.º 7
0
  private static boolean isPathOutsideProjectContent(
      @NotNull final ProjectFileIndex fileIndex, @NotNull String path) {
    while (!path.isEmpty()) {
      final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
      if (file == null) {
        path = PathUtil.getParentPath(path);
      } else {
        return !fileIndex.isInContent(file);
      }
    }

    return false;
  }
  @Override
  public boolean shouldInspect(@NotNull PsiElement psiRoot) {
    if (ApplicationManager.getApplication().isUnitTestMode()) return true;

    final FileHighlightingSetting settingForRoot = getHighlightingSettingForRoot(psiRoot);
    if (settingForRoot == FileHighlightingSetting.SKIP_HIGHLIGHTING
        || settingForRoot == FileHighlightingSetting.SKIP_INSPECTION) {
      return false;
    }
    final Project project = psiRoot.getProject();
    final VirtualFile virtualFile = psiRoot.getContainingFile().getVirtualFile();
    if (virtualFile == null || !virtualFile.isValid()) return false;

    if (ProjectCoreUtil.isProjectOrWorkspaceFile(virtualFile)) return false;

    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    if (ProjectScope.getLibrariesScope(project).contains(virtualFile)
        && !fileIndex.isInContent(virtualFile)) return false;

    return !SingleRootFileViewProvider.isTooLargeForIntelligence(virtualFile);
  }
 @Nullable
 private AnalysisScope getScope() {
   final Set<PsiFile> selectedScope = getSelectedScope(myRightTree);
   Set<PsiFile> result = new HashSet<PsiFile>();
   ((PackageDependenciesNode) myLeftTree.getModel().getRoot())
       .fillFiles(result, !mySettings.UI_FLATTEN_PACKAGES);
   selectedScope.removeAll(result);
   if (selectedScope.isEmpty()) return null;
   List<VirtualFile> files = new ArrayList<VirtualFile>();
   final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
   for (PsiFile psiFile : selectedScope) {
     final VirtualFile file = psiFile.getVirtualFile();
     LOG.assertTrue(file != null);
     if (fileIndex.isInContent(file)) {
       files.add(file);
     }
   }
   if (!files.isEmpty()) {
     return new AnalysisScope(myProject, files);
   }
   return null;
 }
  public static List<VirtualFile> findSuitableFilesFor(
      final String filePath, final Project project) {
    final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();

    // at first let's try to find file as is, by it's real path
    // and check that file belongs to current project
    // this location provider designed for tests thus we will check only project content
    // (we cannot check just sources or tests folders because RM doesn't use it
    final VirtualFile file = getByFullPath(filePath);
    final boolean inProjectContent = file != null && (index.isInContent(file));

    if (inProjectContent) {
      return Collections.singletonList(file);
    }

    // split file by "/" in parts
    final LinkedList<String> folders = new LinkedList<String>();
    final StringTokenizer st = new StringTokenizer(filePath, "/", false);
    String fileName = null;
    while (st.hasMoreTokens()) {
      final String pathComponent = st.nextToken();
      if (st.hasMoreTokens()) {
        folders.addFirst(pathComponent);
      } else {
        // last token
        fileName = pathComponent;
      }
    }
    if (fileName == null) {
      return Collections.emptyList();
    }
    final List<VirtualFile> target =
        findFilesClosestToTarget(
            folders, collectCandidates(project, fileName, true), MIN_PROXIMITY_THRESHOLD);
    return target.isEmpty() && file != null ? Collections.singletonList(file) : target;
  }
  @NotNull
  public static VirtualFile getTargetDirectoryFor(
      @NotNull Project project,
      @NotNull VirtualFile sourceFile,
      @Nullable String targetFile,
      @Nullable String targetPackage,
      boolean returnRoot) {
    boolean hasPackage = StringUtil.isNotEmpty(targetPackage);
    ProjectRootManager rootManager = ProjectRootManager.getInstance(project);
    ProjectFileIndex fileIndex = ProjectFileIndex.SERVICE.getInstance(project);
    Collection<VirtualFile> files =
        targetFile == null
            ? Collections.<VirtualFile>emptyList()
            : FilenameIndex.getVirtualFilesByName(
                project, targetFile, ProjectScope.getAllScope(project));

    VirtualFile existingFile = null;
    for (VirtualFile file : files) {
      String existingFilePackage = fileIndex.getPackageNameByDirectory(file.getParent());
      if (!hasPackage || existingFilePackage == null || targetPackage.equals(existingFilePackage)) {
        existingFile = file;
        break;
      }
    }

    VirtualFile existingFileRoot =
        existingFile == null
            ? null
            : fileIndex.isInSourceContent(existingFile)
                ? fileIndex.getSourceRootForFile(existingFile)
                : fileIndex.isInContent(existingFile)
                    ? fileIndex.getContentRootForFile(existingFile)
                    : null;

    boolean preferGenRoot =
        sourceFile.getFileType() == BnfFileType.INSTANCE
            || sourceFile.getFileType() == JFlexFileType.INSTANCE;
    boolean preferSourceRoot = hasPackage && !preferGenRoot;
    VirtualFile[] sourceRoots = rootManager.getContentSourceRoots();
    VirtualFile[] contentRoots = rootManager.getContentRoots();
    final VirtualFile virtualRoot =
        existingFileRoot != null
            ? existingFileRoot
            : preferSourceRoot && fileIndex.isInSource(sourceFile)
                ? fileIndex.getSourceRootForFile(sourceFile)
                : fileIndex.isInContent(sourceFile)
                    ? fileIndex.getContentRootForFile(sourceFile)
                    : getFirstElement(
                        preferSourceRoot && sourceRoots.length > 0 ? sourceRoots : contentRoots);
    if (virtualRoot == null) {
      fail(project, sourceFile, "Unable to guess target source root");
      throw new ProcessCanceledException();
    }
    try {
      String genDirName = Options.GEN_DIR.get();
      boolean newGenRoot = !fileIndex.isInSourceContent(virtualRoot);
      final String relativePath =
          (hasPackage && newGenRoot
                  ? genDirName + "/" + targetPackage
                  : hasPackage ? targetPackage : newGenRoot ? genDirName : "")
              .replace('.', '/');
      if (relativePath.isEmpty()) {
        return virtualRoot;
      } else {
        VirtualFile result =
            new WriteAction<VirtualFile>() {
              @Override
              protected void run(@NotNull Result<VirtualFile> result) throws Throwable {
                result.setResult(VfsUtil.createDirectoryIfMissing(virtualRoot, relativePath));
              }
            }.execute().throwException().getResultObject();
        VfsUtil.markDirtyAndRefresh(false, true, true, result);
        return returnRoot && newGenRoot
            ? ObjectUtils.assertNotNull(virtualRoot.findChild(genDirName))
            : returnRoot ? virtualRoot : result;
      }
    } catch (ProcessCanceledException ex) {
      throw ex;
    } catch (Exception ex) {
      fail(project, sourceFile, ex.getMessage());
      throw new ProcessCanceledException();
    }
  }
 private boolean isInRootModel(@NotNull VirtualFile file) {
   ProjectFileIndex index = ProjectFileIndex.SERVICE.getInstance(myProject);
   return index.isInContent(file)
       || index.isInLibraryClasses(file)
       || index.isInLibrarySource(file);
 }
  @Nullable
  protected DirCoverageInfo collectFolderCoverage(
      @NotNull final VirtualFile dir,
      final @NotNull CoverageDataManager dataManager,
      final Annotator annotator,
      final ProjectData projectInfo,
      boolean trackTestFolders,
      @NotNull final ProjectFileIndex index,
      @NotNull final CoverageEngine coverageEngine,
      Set<VirtualFile> visitedDirs,
      @NotNull final Map<String, String> normalizedFiles2Files) {
    if (!index.isInContent(dir)) {
      return null;
    }

    if (visitedDirs.contains(dir)) {
      return null;
    }

    if (!shouldCollectCoverageInsideLibraryDirs()) {
      if (index.isInLibrarySource(dir) || index.isInLibraryClasses(dir)) {
        return null;
      }
    }
    visitedDirs.add(dir);

    final boolean isInTestSrcContent = TestSourcesFilter.isTestSources(dir, getProject());

    // Don't count coverage for tests folders if track test folders is switched off
    if (!trackTestFolders && isInTestSrcContent) {
      return null;
    }

    final VirtualFile[] children = dataManager.doInReadActionIfProjectOpen(dir::getChildren);
    if (children == null) {
      return null;
    }

    final DirCoverageInfo dirCoverageInfo = new DirCoverageInfo();

    for (VirtualFile fileOrDir : children) {
      if (fileOrDir.isDirectory()) {
        final DirCoverageInfo childCoverageInfo =
            collectFolderCoverage(
                fileOrDir,
                dataManager,
                annotator,
                projectInfo,
                trackTestFolders,
                index,
                coverageEngine,
                visitedDirs,
                normalizedFiles2Files);

        if (childCoverageInfo != null) {
          dirCoverageInfo.totalFilesCount += childCoverageInfo.totalFilesCount;
          dirCoverageInfo.coveredFilesCount += childCoverageInfo.coveredFilesCount;
          dirCoverageInfo.totalLineCount += childCoverageInfo.totalLineCount;
          dirCoverageInfo.coveredLineCount += childCoverageInfo.coveredLineCount;
        }
      } else if (coverageEngine.coverageProjectViewStatisticsApplicableTo(fileOrDir)) {
        // let's count statistics only for ruby-based files

        final FileCoverageInfo fileInfo =
            collectBaseFileCoverage(fileOrDir, annotator, projectInfo, normalizedFiles2Files);

        if (fileInfo != null) {
          dirCoverageInfo.totalLineCount += fileInfo.totalLineCount;
          dirCoverageInfo.totalFilesCount++;

          if (fileInfo.coveredLineCount > 0) {
            dirCoverageInfo.coveredFilesCount++;
            dirCoverageInfo.coveredLineCount += fileInfo.coveredLineCount;
          }
        }
      }
    }

    // TODO - toplevelFilesCoverage - is unused variable!

    // no sense to include directories without ruby files
    if (dirCoverageInfo.totalFilesCount == 0) {
      return null;
    }

    final String dirPath = normalizeFilePath(dir.getPath());
    if (isInTestSrcContent) {
      annotator.annotateTestDirectory(dirPath, dirCoverageInfo);
    } else {
      annotator.annotateSourceDirectory(dirPath, dirCoverageInfo);
    }

    return dirCoverageInfo;
  }
Ejemplo n.º 14
0
  public HectorComponent(@NotNull PsiFile file) {
    super(new GridBagLayout());
    setBorder(BorderFactory.createEmptyBorder(0, 0, 7, 0));
    myFile = file;
    mySliders = new HashMap<Language, JSlider>();

    final Project project = myFile.getProject();
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
    final VirtualFile virtualFile = myFile.getContainingFile().getVirtualFile();
    LOG.assertTrue(virtualFile != null);
    final boolean notInLibrary =
        !fileIndex.isInLibrarySource(virtualFile) && !fileIndex.isInLibraryClasses(virtualFile)
            || fileIndex.isInContent(virtualFile);
    final FileViewProvider viewProvider = myFile.getViewProvider();
    List<Language> languages = new ArrayList<Language>(viewProvider.getLanguages());
    Collections.sort(languages, PsiUtilBase.LANGUAGE_COMPARATOR);
    for (Language language : languages) {
      @SuppressWarnings("UseOfObsoleteCollectionType")
      final Hashtable<Integer, JLabel> sliderLabels = new Hashtable<Integer, JLabel>();
      sliderLabels.put(1, new JLabel(EditorBundle.message("hector.none.slider.label")));
      sliderLabels.put(2, new JLabel(EditorBundle.message("hector.syntax.slider.label")));
      if (notInLibrary) {
        sliderLabels.put(3, new JLabel(EditorBundle.message("hector.inspections.slider.label")));
      }

      final JSlider slider = new JSlider(SwingConstants.VERTICAL, 1, notInLibrary ? 3 : 2, 1);
      if (UIUtil.isUnderGTKLookAndFeel()) {
        // default GTK+ slider UI is way too ugly
        slider.putClientProperty("Slider.paintThumbArrowShape", true);
        slider.setUI(new BasicSliderUI(slider));
      }
      slider.setLabelTable(sliderLabels);
      UIUtil.setSliderIsFilled(slider, true);
      slider.setPaintLabels(true);
      slider.setSnapToTicks(true);
      slider.addChangeListener(
          new ChangeListener() {
            @Override
            public void stateChanged(ChangeEvent e) {
              int value = slider.getValue();
              for (Enumeration<Integer> enumeration = sliderLabels.keys();
                  enumeration.hasMoreElements(); ) {
                Integer key = enumeration.nextElement();
                sliderLabels
                    .get(key)
                    .setForeground(
                        key.intValue() <= value
                            ? UIUtil.getLabelForeground()
                            : UIUtil.getLabelDisabledForeground());
              }
            }
          });

      final PsiFile psiRoot = viewProvider.getPsi(language);
      assert psiRoot != null : "No root in " + viewProvider + " for " + language;
      slider.setValue(
          getValue(
              HighlightLevelUtil.shouldHighlight(psiRoot),
              HighlightLevelUtil.shouldInspect(psiRoot)));
      mySliders.put(language, slider);
    }

    GridBagConstraints gc =
        new GridBagConstraints(
            0,
            GridBagConstraints.RELATIVE,
            1,
            1,
            0,
            0,
            GridBagConstraints.NORTHWEST,
            GridBagConstraints.NONE,
            new Insets(0, 5, 0, 0),
            0,
            0);

    JPanel panel = new JPanel(new GridBagLayout());
    panel.setBorder(IdeBorderFactory.createTitledBorder(myTitle, false));
    final boolean addLabel = mySliders.size() > 1;
    if (addLabel) {
      layoutVertical(panel);
    } else {
      layoutHorizontal(panel);
    }
    gc.gridx = 0;
    gc.gridy = 0;
    gc.weighty = 1.0;
    gc.fill = GridBagConstraints.BOTH;
    add(panel, gc);

    gc.gridy = GridBagConstraints.RELATIVE;
    gc.weighty = 0;

    final HyperlinkLabel configurator = new HyperlinkLabel("Configure inspections");
    gc.insets.right = 5;
    gc.insets.bottom = 10;
    gc.weightx = 0;
    gc.fill = GridBagConstraints.NONE;
    gc.anchor = GridBagConstraints.EAST;
    add(configurator, gc);
    configurator.addHyperlinkListener(
        new HyperlinkListener() {
          @Override
          public void hyperlinkUpdate(HyperlinkEvent e) {
            final JBPopup hector = getOldHector();
            if (hector != null) {
              hector.cancel();
            }
            if (!DaemonCodeAnalyzer.getInstance(myFile.getProject())
                .isHighlightingAvailable(myFile)) return;
            final Project project = myFile.getProject();
            final ErrorsConfigurable errorsConfigurable =
                ErrorsConfigurable.SERVICE.createConfigurable(project);
            assert errorsConfigurable != null;
            ShowSettingsUtil.getInstance().editConfigurable(project, errorsConfigurable);
          }
        });

    gc.anchor = GridBagConstraints.WEST;
    gc.weightx = 1.0;
    gc.insets.right = 0;
    gc.fill = GridBagConstraints.HORIZONTAL;
    myAdditionalPanels = new ArrayList<HectorComponentPanel>();
    for (HectorComponentPanelsProvider provider :
        Extensions.getExtensions(HectorComponentPanelsProvider.EP_NAME, project)) {
      final HectorComponentPanel componentPanel = provider.createConfigurable(file);
      if (componentPanel != null) {
        myAdditionalPanels.add(componentPanel);
        add(componentPanel.createComponent(), gc);
        componentPanel.reset();
      }
    }
  }
 public boolean contains(@NotNull VirtualFile file) {
   return myProjectFileIndex.isInContent(file)
       || myProjectFileIndex.isInLibraryClasses(file)
       || myProjectFileIndex.isInLibrarySource(file);
 }