@Override
  @NotNull
  public LogData readAllHashes(
      @NotNull VirtualFile root, @NotNull final Consumer<TimedVcsCommit> commitConsumer)
      throws VcsException {
    if (!isRepositoryReady(root)) {
      return LogDataImpl.empty();
    }

    List<String> parameters = new ArrayList<String>(GitHistoryUtils.LOG_ALL);
    parameters.add("--sparse");

    final GitBekParentFixer parentFixer = GitBekParentFixer.prepare(root, this);
    Set<VcsUser> userRegistry = ContainerUtil.newHashSet();
    Set<VcsRef> refs = ContainerUtil.newHashSet();
    GitHistoryUtils.readCommits(
        myProject,
        root,
        parameters,
        new CollectConsumer<VcsUser>(userRegistry),
        new CollectConsumer<VcsRef>(refs),
        new Consumer<TimedVcsCommit>() {
          @Override
          public void consume(TimedVcsCommit commit) {
            commitConsumer.consume(parentFixer.fixCommit(commit));
          }
        });
    return new LogDataImpl(refs, userRegistry);
  }
  public void moveMembersToBase() throws IncorrectOperationException {
    myMovedMembers = ContainerUtil.newHashSet();
    myMembersAfterMove = ContainerUtil.newHashSet();

    // build aux sets
    for (MemberInfo info : myMembersToMove) {
      myMovedMembers.add(info.getMember());
    }

    final PsiSubstitutor substitutor = upDownSuperClassSubstitutor();

    for (MemberInfo info : myMembersToMove) {
      PullUpHelper<MemberInfo> processor = getProcessor(info);

      LOG.assertTrue(processor != null, info.getMember());
      if (!(info.getMember() instanceof PsiClass) || info.getOverrides() == null) {
        processor.setCorrectVisibility(info);
        processor.encodeContextInfo(info);
      }

      processor.move(info, substitutor);
    }

    for (PsiMember member : myMembersAfterMove) {
      PullUpHelper<MemberInfo> processor = getProcessor(member);
      LOG.assertTrue(processor != null, member);

      processor.postProcessMember(member);

      final JavaRefactoringListenerManager listenerManager =
          JavaRefactoringListenerManager.getInstance(myProject);
      ((JavaRefactoringListenerManagerImpl) listenerManager).fireMemberMoved(mySourceClass, member);
    }
  }
  public void annotate(
      @NotNull final VirtualFile contentRoot,
      @NotNull final CoverageSuitesBundle suite,
      final @NotNull CoverageDataManager dataManager,
      @NotNull final ProjectData data,
      final Project project,
      final Annotator annotator) {
    if (!contentRoot.isValid()) {
      return;
    }

    // TODO: check name filter!!!!!

    final ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();

    @SuppressWarnings("unchecked")
    final Set<String> files = data.getClasses().keySet();
    final Map<String, String> normalizedFiles2Files = ContainerUtil.newHashMap();
    for (final String file : files) {
      normalizedFiles2Files.put(normalizeFilePath(file), file);
    }
    collectFolderCoverage(
        contentRoot,
        dataManager,
        annotator,
        data,
        suite.isTrackTestFolders(),
        index,
        suite.getCoverageEngine(),
        ContainerUtil.newHashSet(),
        Collections.unmodifiableMap(normalizedFiles2Files));
  }
  @Nullable
  Font getFontAbleToDisplay(LookupElementPresentation p) {
    String sampleString = p.getItemText() + p.getTailText() + p.getTypeText();

    // assume a single font can display all lookup item chars
    Set<Font> fonts = ContainerUtil.newHashSet();
    for (int i = 0; i < sampleString.length(); i++) {
      fonts.add(
          EditorUtil.fontForChar(sampleString.charAt(i), Font.PLAIN, myLookup.getEditor())
              .getFont());
    }

    eachFont:
    for (Font font : fonts) {
      if (font.equals(myNormalFont)) continue;

      for (int i = 0; i < sampleString.length(); i++) {
        if (!font.canDisplay(sampleString.charAt(i))) {
          continue eachFont;
        }
      }
      return font;
    }
    return null;
  }
  @Nullable
  private PsiAnnotation findNullabilityAnnotation(
      @NotNull PsiModifierListOwner owner, boolean checkBases, boolean nullable) {
    Set<String> qNames = ContainerUtil.newHashSet(nullable ? getNullables() : getNotNulls());
    PsiAnnotation annotation =
        checkBases && (owner instanceof PsiClass || owner instanceof PsiMethod)
            ? AnnotationUtil.findAnnotationInHierarchy(owner, qNames)
            : AnnotationUtil.findAnnotation(owner, qNames);
    if (annotation != null) {
      return annotation;
    }

    if (owner instanceof PsiParameter
        && !TypeConversionUtil.isPrimitiveAndNotNull(((PsiParameter) owner).getType())) {
      // even if javax.annotation.Nullable is not configured, it should still take precedence over
      // ByDefault annotations
      if (AnnotationUtil.isAnnotated(
          owner,
          nullable ? Arrays.asList(DEFAULT_NOT_NULLS) : Arrays.asList(DEFAULT_NULLABLES),
          checkBases,
          false)) {
        return null;
      }
      return findContainerAnnotation(
          owner,
          nullable
              ? "javax.annotation.ParametersAreNullableByDefault"
              : "javax.annotation.ParametersAreNonnullByDefault");
    }
    return null;
  }
  private Set<String> getDuplicateProjectNames(Set<String> openedPaths, Set<String> recentPaths) {
    Set<String> names = ContainerUtil.newHashSet();
    Set<String> duplicates = ContainerUtil.newHashSet();
    for (String path : openedPaths) {
      if (!names.add(getProjectName(path))) {
        duplicates.add(path);
      }
    }
    for (String path : recentPaths) {
      if (!names.add(getProjectName(path))) {
        duplicates.add(path);
      }
    }

    return duplicates;
  }
Example #7
0
    @NotNull
    @Override
    public GroovyResolveResult[] getCandidates() {
      if (!hasCandidates()) return GroovyResolveResult.EMPTY_ARRAY;
      final GroovyResolveResult[] results =
          ResolveUtil.filterSameSignatureCandidates(getCandidatesInternal());
      List<GroovyResolveResult> list = new ArrayList<GroovyResolveResult>(results.length);
      myPropertyNames.removeAll(myPreferredFieldNames);

      Set<String> usedFields = ContainerUtil.newHashSet();
      for (GroovyResolveResult result : results) {
        final PsiElement element = result.getElement();
        if (element instanceof PsiField) {
          final String name = ((PsiField) element).getName();
          if (myPropertyNames.contains(name)
              || myLocalVars.contains(name)
              || usedFields.contains(name)) {
            continue;
          } else {
            usedFields.add(name);
          }
        }

        list.add(result);
      }
      return list.toArray(new GroovyResolveResult[list.size()]);
    }
 @NotNull
 private static Collection<VirtualFile> gatherIncludeRoots(
     Collection<VirtualFile> goPathSourcesRoots, Set<VirtualFile> excludeRoots) {
   Collection<VirtualFile> includeRoots = ContainerUtil.newHashSet();
   for (VirtualFile goPathSourcesDirectory : goPathSourcesRoots) {
     ProgressIndicatorProvider.checkCanceled();
     boolean excludedRootIsAncestor = false;
     for (VirtualFile excludeRoot : excludeRoots) {
       ProgressIndicatorProvider.checkCanceled();
       if (VfsUtilCore.isAncestor(excludeRoot, goPathSourcesDirectory, false)) {
         excludedRootIsAncestor = true;
         break;
       }
     }
     if (excludedRootIsAncestor) {
       continue;
     }
     for (VirtualFile file : goPathSourcesDirectory.getChildren()) {
       ProgressIndicatorProvider.checkCanceled();
       if (file.isDirectory() && !excludeRoots.contains(file)) {
         includeRoots.add(file);
       }
     }
   }
   return includeRoots;
 }
 @NotNull
 @Override
 protected Collection<String> getTextValues(@Nullable VcsLogUserFilter filter) {
   if (filter == null) {
     return Collections.emptySet();
   }
   return ContainerUtil.newHashSet(((VcsLogUserFilterImpl) filter).getUserNamesForPresentation());
 }
 private static void hideActionFromMainMenu(
     @NotNull final DefaultMutableTreeNode root,
     @NotNull final CustomActionsSchema schema,
     DefaultMutableTreeNode mainMenu) {
   final HashSet<String> menuItems =
       ContainerUtil.newHashSet("Tools", "VCS", "Refactor", "Window", "Run");
   hideActions(schema, root, mainMenu, menuItems);
 }
 @NotNull
 private static <T> Set<T> remove(@NotNull Set<T> original, @NotNull Set<T>... toRemove) {
   Set<T> result = ContainerUtil.newHashSet(original);
   for (Set<T> set : toRemove) {
     result.removeAll(set);
   }
   return result;
 }
 public void setDefaultTemplate(String name) {
   Set<String> fullNames = ContainerUtil.newHashSet(toEqualsName(name), toHashCodeName(name));
   for (TemplateResource resource : getAllTemplates()) {
     if (fullNames.contains(resource.getFileName())) {
       setDefaultTemplate(resource);
       break;
     }
   }
 }
 @NotNull
 private Set<VirtualFile> safeGetAndClear(@NotNull Set<VirtualFile> unsafeRefs) {
   Set<VirtualFile> safeRefs = ContainerUtil.newHashSet();
   synchronized (REFRESH_LOCK) {
     safeRefs.addAll(unsafeRefs);
     unsafeRefs.clear();
   }
   return safeRefs;
 }
 protected PantsBuildTarget(
     @NotNull String pantsExecutable,
     @NotNull Set<String> addresses,
     @NotNull Set<TargetAddressInfo> targetAddressInfoSet) {
   super(PantsBuildTargetType.INSTANCE);
   myPantsExecutable = pantsExecutable;
   myTargetAddresses = addresses;
   myTargetAddressInfoSet = targetAddressInfoSet;
   myAffectedModules = ContainerUtil.newHashSet();
 }
 private static void suggestGeneratedMethods(CompletionResultSet result, PsiElement position) {
   PsiClass parent =
       CompletionUtil.getOriginalElement(
           ObjectUtils.assertNotNull(PsiTreeUtil.getParentOfType(position, PsiClass.class)));
   if (parent != null) {
     Set<MethodSignature> addedSignatures = ContainerUtil.newHashSet();
     addGetterSetterElements(result, parent, addedSignatures);
     addSuperSignatureElements(parent, true, result, addedSignatures);
     addSuperSignatureElements(parent, false, result, addedSignatures);
   }
 }
Example #16
0
 private static Set<String> collectPathsMetadata(Class<?> testCaseClass) {
   return ContainerUtil.newHashSet(
       ContainerUtil.map(
           collectMethodsMetadata(testCaseClass),
           new Function<String, String>() {
             @Override
             public String fun(String pathData) {
               return FileUtil.nameToCompare(pathData);
             }
           }));
 }
 @NotNull
 public static Set<VcsRef> readAllRefs(
     @NotNull VirtualFile root, @NotNull VcsLogObjectsFactory objectsFactory) {
   String[] refs =
       StringUtil.splitByLines(
           git("log --branches --tags --no-walk --format=%H%d --decorate=full"));
   Set<VcsRef> result = ContainerUtil.newHashSet();
   for (String ref : refs) {
     result.addAll(new RefParser(objectsFactory).parseCommitRefs(ref, root));
   }
   return result;
 }
  public AndroidPostfixTemplateProvider() {
    templates =
        ContainerUtil.<PostfixTemplate>newHashSet(
            new ToastTemplate(), new LogTemplate(), new LogDTemplate());

    templates.add(new DynamicTemplate("ll", "Log.d($TAG$, $expr$)$END$ " + "// ll"));
    templates.add(new DynamicTemplate("l", "Log.d($TAG$, $expr$)$END$ // " + "1"));
    templates.add(new DynamicTemplate("l2", "Log.d(TAG, expr); // l2"));
    templates.add(new DynamicTemplate("l3", "Log.d(TAG, expr); // l3"));
    templates.add(new DynamicTemplate("l4", "Log.d(TAG, expr); // l4"));
    templates.add(new DynamicTemplate("l5", "Log.d(TAG, expr); // l5"));
  }
  private static boolean varsAreEqual(List<VariableInfo> toAdd, VariableInfo[] outputVars) {
    if (toAdd.size() != outputVars.length) return false;
    Set<String> names = ContainerUtil.newHashSet();
    for (VariableInfo info : toAdd) {
      names.add(info.getName());
    }

    for (VariableInfo var : outputVars) {
      if (!names.contains(var.getName())) return false;
    }

    return true;
  }
  public void updateContextHints(@NotNull DiffRequest request, @NotNull DiffContext context) {
    if (!isEnabled()) return;

    Set<String> updated = ContainerUtil.newHashSet();

    for (BinaryEditorHolder holder : myHolders) {
      TransferableFileEditorState state = getEditorState(holder.getEditor());
      if (state != null) {
        boolean processed = !updated.add(state.getEditorId());
        if (!processed) writeContextData(context, state);
      }
    }
  }
    @Override
    public void run() {
      Project project = myModule.getProject();
      if (GoSdkService.getInstance(project).isGoModule(myModule)) {
        synchronized (myLastHandledGoPathSourcesRoots) {
          Collection<VirtualFile> goPathSourcesRoots =
              GoSdkUtil.getGoPathSources(project, myModule);
          Set<VirtualFile> excludeRoots =
              ContainerUtil.newHashSet(ProjectRootManager.getInstance(project).getContentRoots());
          ProgressIndicatorProvider.checkCanceled();
          if (!myLastHandledGoPathSourcesRoots.equals(goPathSourcesRoots)
              || !myLastHandledExclusions.equals(excludeRoots)) {
            Collection<VirtualFile> includeRoots =
                gatherIncludeRoots(goPathSourcesRoots, excludeRoots);
            ApplicationManager.getApplication()
                .invokeLater(
                    () -> {
                      if (!myModule.isDisposed()
                          && GoSdkService.getInstance(project).isGoModule(myModule)) {
                        attachLibraries(includeRoots, excludeRoots);
                      }
                    });

            myLastHandledGoPathSourcesRoots.clear();
            myLastHandledGoPathSourcesRoots.addAll(goPathSourcesRoots);

            myLastHandledExclusions.clear();
            myLastHandledExclusions.addAll(excludeRoots);

            List<String> paths = ContainerUtil.map(goPathSourcesRoots, VirtualFile::getPath);
            myWatchedRequests.clear();
            myWatchedRequests.addAll(LocalFileSystem.getInstance().addRootsToWatch(paths, true));
          }
        }
      } else {
        synchronized (myLastHandledGoPathSourcesRoots) {
          LocalFileSystem.getInstance().removeWatchedRoots(myWatchedRequests);
          myLastHandledGoPathSourcesRoots.clear();
          myLastHandledExclusions.clear();
          ApplicationManager.getApplication()
              .invokeLater(
                  () -> {
                    if (!myModule.isDisposed()
                        && GoSdkService.getInstance(project).isGoModule(myModule)) {
                      removeLibraryIfNeeded();
                    }
                  });
        }
      }
    }
 @NotNull
 @Override
 public Condition<CommitId> getContainedInBranchCondition(
     @NotNull final Collection<CommitId> heads) {
   List<Integer> headIds =
       ContainerUtil.map(
           heads,
           new Function<CommitId, Integer>() {
             @Override
             public Integer fun(CommitId head) {
               return myPermanentCommitsInfo.getNodeId(head);
             }
           });
   if (!heads.isEmpty() && ContainerUtil.getFirstItem(heads) instanceof Integer) {
     final TIntHashSet branchNodes = new TIntHashSet();
     myReachableNodes.walk(
         headIds,
         new Consumer<Integer>() {
           @Override
           public void consume(Integer node) {
             branchNodes.add((Integer) myPermanentCommitsInfo.getCommitId(node));
           }
         });
     return new Condition<CommitId>() {
       @Override
       public boolean value(CommitId commitId) {
         return branchNodes.contains((Integer) commitId);
       }
     };
   } else {
     final Set<CommitId> branchNodes = ContainerUtil.newHashSet();
     myReachableNodes.walk(
         headIds,
         new Consumer<Integer>() {
           @Override
           public void consume(Integer node) {
             branchNodes.add(myPermanentCommitsInfo.getCommitId(node));
           }
         });
     return new Condition<CommitId>() {
       @Override
       public boolean value(CommitId commitId) {
         return branchNodes.contains(commitId);
       }
     };
   }
 }
  private static void registerExtensionPointsAndExtensions(
      ExtensionsArea area, List<IdeaPluginDescriptorImpl> loadedPlugins) {
    for (IdeaPluginDescriptorImpl descriptor : loadedPlugins) {
      descriptor.registerExtensionPoints(area);
    }

    Set<String> epNames = ContainerUtil.newHashSet();
    for (ExtensionPoint point : area.getExtensionPoints()) {
      epNames.add(point.getName());
    }

    for (IdeaPluginDescriptorImpl descriptor : loadedPlugins) {
      for (String epName : epNames) {
        descriptor.registerExtensions(area, epName);
      }
    }
  }
    @Override
    public void invoke(@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) {
      SelectionModel selectionModel = editor.getSelectionModel();
      if (!selectionModel.hasSelection()) {
        selectionModel.selectLineAtCaret();
      }

      ZenCodingTemplate emmetCustomTemplate =
          CustomLiveTemplate.EP_NAME.findExtension(ZenCodingTemplate.class);
      if (emmetCustomTemplate != null) {
        new WrapWithCustomTemplateAction(
                emmetCustomTemplate, editor, file, ContainerUtil.newHashSet())
            .actionPerformed(null);
      } else if (!ApplicationManager.getApplication().isUnitTestMode()) {
        HintManager.getInstance()
            .showErrorHint(editor, "Cannot invoke Surround with Emmet in the current context");
      }
    }
 @NotNull
 private static GroovyResolveResult[] collapseReflectedMethods(GroovyResolveResult[] candidates) {
   Set<GrMethod> visited = ContainerUtil.newHashSet();
   List<GroovyResolveResult> collapsed = ContainerUtil.newArrayList();
   for (GroovyResolveResult result : candidates) {
     PsiElement element = result.getElement();
     if (element instanceof GrReflectedMethod) {
       GrMethod baseMethod = ((GrReflectedMethod) element).getBaseMethod();
       if (visited.add(baseMethod)) {
         collapsed.add(
             PsiImplUtil.reflectedToBase(result, baseMethod, (GrReflectedMethod) element));
       }
     } else {
       collapsed.add(result);
     }
   }
   return collapsed.toArray(new GroovyResolveResult[collapsed.size()]);
 }
 @Nullable
 private VirtualFile findLibraryRootInfo(@NotNull List<VirtualFile> hierarchy, boolean source) {
   Set<Library> librariesToIgnore = ContainerUtil.newHashSet();
   for (VirtualFile root : hierarchy) {
     librariesToIgnore.addAll(excludedFromLibraries.get(root));
     if (source
         && libraryOrSdkSources.contains(root)
         && (!sourceOfLibraries.containsKey(root)
             || !librariesToIgnore.containsAll(sourceOfLibraries.get(root)))) {
       return root;
     } else if (!source
         && libraryOrSdkClasses.contains(root)
         && (!classOfLibraries.containsKey(root)
             || !librariesToIgnore.containsAll(classOfLibraries.get(root)))) {
       return root;
     }
   }
   return null;
 }
 @NotNull
 private static Set<String> resolveModuleDeps(
     @NotNull ModifiableRootModel rootModel,
     @NotNull ImportedOtpApp importedOtpApp,
     @Nullable Sdk projectSdk,
     @NotNull Set<String> allImportedAppNames) {
   HashSet<String> unresolvedAppNames = ContainerUtil.newHashSet();
   for (String depAppName : importedOtpApp.getDeps()) {
     if (allImportedAppNames.contains(depAppName)) {
       rootModel.addInvalidModuleEntry(depAppName);
     } else if (projectSdk != null && isSdkOtpApp(depAppName, projectSdk)) {
       // SDK is already a dependency
     } else {
       rootModel.addInvalidModuleEntry(depAppName);
       unresolvedAppNames.add(depAppName);
     }
   }
   return unresolvedAppNames;
 }
  @NotNull
  private static Set<String> sortMatching(
      @NotNull PrefixMatcher matcher, @NotNull Collection<String> names, @NotNull GoFile file) {
    ProgressManager.checkCanceled();
    String prefix = matcher.getPrefix();
    if (prefix.isEmpty()) return ContainerUtil.newLinkedHashSet(names);

    Set<String> packagesWithAliases = ContainerUtil.newHashSet();
    for (Map.Entry<String, Collection<GoImportSpec>> entry : file.getImportMap().entrySet()) {
      for (GoImportSpec spec : entry.getValue()) {
        String alias = spec.getAlias();
        if (spec.isDot() || alias != null) {
          packagesWithAliases.add(entry.getKey());
          break;
        }
      }
    }

    List<String> sorted = ContainerUtil.newArrayList();
    for (String name : names) {
      if (matcher.prefixMatches(name) || packagesWithAliases.contains(substringBefore(name, '.'))) {
        sorted.add(name);
      }
    }

    ProgressManager.checkCanceled();
    Collections.sort(sorted, String.CASE_INSENSITIVE_ORDER);
    ProgressManager.checkCanceled();

    LinkedHashSet<String> result = new LinkedHashSet<String>();
    for (String name : sorted) {
      if (matcher.isStartMatch(name)) {
        result.add(name);
      }
    }

    ProgressManager.checkCanceled();

    result.addAll(sorted);
    return result;
  }
 private static Set<String> calcDevPatternClassNames(@NotNull final Project project) {
   final List<String> roots = ContainerUtil.createLockFreeCopyOnWriteList();
   JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
   PsiClass beanClass =
       psiFacade.findClass(PatternClassBean.class.getName(), GlobalSearchScope.allScope(project));
   if (beanClass != null) {
     GlobalSearchScope scope =
         GlobalSearchScope.getScopeRestrictedByFileTypes(
             GlobalSearchScope.allScope(project), StdFileTypes.XML);
     final TextOccurenceProcessor occurenceProcessor =
         new TextOccurenceProcessor() {
           @Override
           public boolean execute(@NotNull PsiElement element, int offsetInElement) {
             XmlTag tag = PsiTreeUtil.getParentOfType(element, XmlTag.class);
             String className = tag == null ? null : tag.getAttributeValue("className");
             if (StringUtil.isNotEmpty(className) && tag.getLocalName().endsWith("patternClass")) {
               roots.add(className);
             }
             return true;
           }
         };
     final StringSearcher searcher = new StringSearcher("patternClass", true, true);
     CacheManager.SERVICE
         .getInstance(beanClass.getProject())
         .processFilesWithWord(
             new Processor<PsiFile>() {
               @Override
               public boolean process(PsiFile psiFile) {
                 LowLevelSearchUtil.processElementsContainingWordInElement(
                     occurenceProcessor, psiFile, searcher, true, new EmptyProgressIndicator());
                 return true;
               }
             },
             searcher.getPattern(),
             UsageSearchContext.IN_FOREIGN_LANGUAGES,
             scope,
             searcher.isCaseSensitive());
   }
   return ContainerUtil.newHashSet(roots);
 }
 @NotNull
 @Override
 public Object[] getElementsByName(
     String name, boolean checkBoxState, String pattern, @NotNull ProgressIndicator canceled) {
   List<T> classes =
       myTreeClassChooserDialog.getClassesByName(
           name, checkBoxState, pattern, myTreeClassChooserDialog.getScope());
   if (classes.size() == 0) return ArrayUtil.EMPTY_OBJECT_ARRAY;
   if (classes.size() == 1) {
     return isAccepted(classes.get(0))
         ? ArrayUtil.toObjectArray(classes)
         : ArrayUtil.EMPTY_OBJECT_ARRAY;
   }
   Set<String> qNames = ContainerUtil.newHashSet();
   List<T> list = new ArrayList<T>(classes.size());
   for (T aClass : classes) {
     if (qNames.add(getFullName(aClass)) && isAccepted(aClass)) {
       list.add(aClass);
     }
   }
   return ArrayUtil.toObjectArray(list);
 }