@Nullable
  @Override
  public OrderEntry findIdeModuleOrderEntry(@NotNull DependencyData data) {
    Module ownerIdeModule = findIdeModule(data.getOwnerModule());
    if (ownerIdeModule == null) return null;

    LibraryDependencyData libraryDependencyData = null;
    ModuleDependencyData moduleDependencyData = null;
    if (data instanceof LibraryDependencyData) {
      libraryDependencyData = (LibraryDependencyData) data;
    } else if (data instanceof ModuleDependencyData) {
      moduleDependencyData = (ModuleDependencyData) data;
    } else {
      return null;
    }

    for (OrderEntry entry : getOrderEntries(ownerIdeModule)) {
      if (entry instanceof LibraryOrderEntry && libraryDependencyData != null) {
        if (((LibraryOrderEntry) entry).isModuleLevel()
            && libraryDependencyData.getLevel() != LibraryLevel.MODULE) continue;
        if (StringUtil.isEmpty(((LibraryOrderEntry) entry).getLibraryName())) {
          final Set<String> paths =
              ContainerUtil.map2Set(
                  libraryDependencyData.getTarget().getPaths(LibraryPathType.BINARY),
                  new Function<String, String>() {
                    @Override
                    public String fun(String path) {
                      return PathUtil.getLocalPath(path);
                    }
                  });
          final Set<String> entryPaths =
              ContainerUtil.map2Set(
                  entry.getUrls(OrderRootType.CLASSES),
                  new Function<String, String>() {
                    @Override
                    public String fun(String s) {
                      return PathUtil.getLocalPath(VfsUtilCore.urlToPath(s));
                    }
                  });
          if (entryPaths.equals(paths) && ((LibraryOrderEntry) entry).getScope() == data.getScope())
            return entry;
          continue;
        }
      }

      String entryName =
          libraryDependencyData != null
              ? libraryDependencyData.getInternalName()
              : moduleDependencyData.getInternalName();
      if (entryName.equals(entry.getPresentableName())
          && (!(entry instanceof ExportableOrderEntry)
              || ((ExportableOrderEntry) entry).getScope() == data.getScope())) {
        return entry;
      }
    }
    return null;
  }
  public void testDelayedTasksThatFiredAtTheSameTimeAreExecutedConcurrently()
      throws InterruptedException, ExecutionException {
    final AppScheduledExecutorService service = new AppScheduledExecutorService(getName());
    final List<LogInfo> log = Collections.synchronizedList(new ArrayList<>());
    int delay = 500;

    int N = 20;
    List<? extends Future<?>> futures =
        ContainerUtil.map(
            Collections.nCopies(N, ""),
            __ ->
                service.schedule(
                    () -> {
                      log.add(new LogInfo(0));
                      TimeoutUtil.sleep(10 * 1000);
                    },
                    delay,
                    TimeUnit.MILLISECONDS));

    for (Future<?> future : futures) {
      future.get();
    }

    assertEquals(N, log.size());
    Set<Thread> usedThreads = ContainerUtil.map2Set(log, logInfo -> logInfo.currentThread);

    assertEquals(N, usedThreads.size());
    service.shutdownAppScheduledExecutorService();
    assertTrue(service.awaitTermination(10, TimeUnit.SECONDS));
  }
  @NotNull
  @Override
  public List<? extends VcsCommitMetadata> readFirstBlock(
      @NotNull VirtualFile root, @NotNull Requirements requirements) throws VcsException {
    if (!isRepositoryReady(root)) {
      return Collections.emptyList();
    }

    int commitCount = requirements.getCommitCount();
    if (requirements.isOrdered()) {
      commitCount *=
          2; // need to query more to sort them manually; this doesn't affect performance: it is
      // equal for -1000 and -2000
    }

    String[] params =
        new String[] {"HEAD", "--branches", "--remotes", "--max-count=" + commitCount};
    // NB: not specifying --tags, because it introduces great slowdown if there are many tags,
    // but makes sense only if there are heads without branch or HEAD labels (rare case). Such cases
    // are partially handles below.
    List<VcsCommitMetadata> firstBlock = GitHistoryUtils.loadMetadata(myProject, root, params);

    if (requirements instanceof VcsLogProviderRequirementsEx) {
      VcsLogProviderRequirementsEx rex = (VcsLogProviderRequirementsEx) requirements;
      // on refresh: get new tags, which point to commits not from the first block; then get
      // history, walking down just from these tags
      // on init: just ignore such tagged-only branches. The price for speed-up.
      if (!rex.isOrdered()) {
        Collection<VcsRef> newTags = getNewTags(rex.getCurrentRefs(), rex.getPreviousRefs());
        if (!newTags.isEmpty()) {
          final Set<Hash> firstBlockHashes =
              ContainerUtil.map2Set(
                  firstBlock,
                  new Function<VcsCommitMetadata, Hash>() {
                    @Override
                    public Hash fun(VcsCommitMetadata metadata) {
                      return metadata.getHash();
                    }
                  });
          List<VcsRef> unmatchedHeads = getUnmatchedHeads(firstBlockHashes, newTags);
          if (!unmatchedHeads.isEmpty()) {
            List<VcsCommitMetadata> detailsFromTaggedBranches =
                loadSomeCommitsOnTaggedBranches(root, commitCount, unmatchedHeads);
            Collection<VcsCommitMetadata> unmatchedCommits =
                getUnmatchedCommits(firstBlockHashes, detailsFromTaggedBranches);
            firstBlock.addAll(unmatchedCommits);
          }
        }
      }
    }

    if (requirements.isOrdered()) {
      firstBlock = VcsLogSorter.sortByDateTopoOrder(firstBlock);
      firstBlock =
          new ArrayList<VcsCommitMetadata>(
              firstBlock.subList(0, Math.min(firstBlock.size(), requirements.getCommitCount())));
    }
    return firstBlock;
  }
  private static void validateDataAndReportError(
      @NotNull final VirtualFile root,
      @NotNull final Set<VcsRef> allRefs,
      @NotNull final List<VcsCommitMetadata> sortedCommits,
      @NotNull final DetailedLogData firstBlockSyncData,
      @NotNull final Set<VcsRef> manuallyReadBranches,
      @Nullable final Set<String> currentTagNames,
      @Nullable final DetailedLogData commitsFromTags) {
    StopWatch sw = StopWatch.start("validating data in " + root.getName());
    final Set<Hash> refs =
        ContainerUtil.map2Set(
            allRefs,
            new Function<VcsRef, Hash>() {
              @Override
              public Hash fun(VcsRef ref) {
                return ref.getCommitHash();
              }
            });

    PermanentGraphImpl.newInstance(
        sortedCommits,
        new GraphColorManager<Hash>() {
          @Override
          public int getColorOfBranch(@NotNull Hash headCommit) {
            return 0;
          }

          @Override
          public int getColorOfFragment(@NotNull Hash headCommit, int magicIndex) {
            return 0;
          }

          @Override
          public int compareHeads(@NotNull Hash head1, @NotNull Hash head2) {
            if (!refs.contains(head1) || !refs.contains(head2)) {
              LOG.error(
                  "GitLogProvider returned inconsistent data",
                  new Attachment(
                      "error-details.txt",
                      printErrorDetails(
                          root,
                          allRefs,
                          sortedCommits,
                          firstBlockSyncData,
                          manuallyReadBranches,
                          currentTagNames,
                          commitsFromTags)));
            }
            return 0;
          }
        },
        refs);
    sw.report();
  }
Exemplo n.º 5
0
 public static void runHighlightingTypeMigration(
     final Project project,
     final Editor editor,
     final TypeMigrationRules rules,
     final PsiElement[] roots,
     final Function<PsiElement, PsiType> migrationTypeFunction,
     final boolean optimizeImports) {
   final Set<PsiFile> containingFiles =
       ContainerUtil.map2Set(roots, element -> element.getContainingFile());
   final TypeMigrationProcessor processor =
       new TypeMigrationProcessor(project, roots, migrationTypeFunction, rules) {
         @Override
         public void performRefactoring(@NotNull final UsageInfo[] usages) {
           super.performRefactoring(usages);
           if (editor != null) {
             ApplicationManager.getApplication()
                 .invokeLater(
                     () -> {
                       final List<PsiElement> result = new ArrayList<>();
                       for (UsageInfo usage : usages) {
                         final PsiElement element = usage.getElement();
                         if (element == null
                             || !containingFiles.contains(element.getContainingFile())) continue;
                         if (element instanceof PsiMethod) {
                           result.add(((PsiMethod) element).getReturnTypeElement());
                         } else if (element instanceof PsiVariable) {
                           result.add(((PsiVariable) element).getTypeElement());
                         } else {
                           result.add(element);
                         }
                       }
                       RefactoringUtil.highlightAllOccurrences(
                           project, PsiUtilCore.toPsiElementArray(result), editor);
                     });
           }
           if (optimizeImports) {
             final JavaCodeStyleManager javaCodeStyleManager =
                 JavaCodeStyleManager.getInstance(myProject);
             final Set<PsiFile> affectedFiles = new THashSet<>();
             for (UsageInfo usage : usages) {
               final PsiFile usageFile = usage.getFile();
               if (usageFile != null) {
                 affectedFiles.add(usageFile);
               }
             }
             for (PsiFile file : affectedFiles) {
               javaCodeStyleManager.optimizeImports(file);
               javaCodeStyleManager.shortenClassReferences(file);
             }
           }
         }
       };
   processor.run();
 }
 @NotNull
 private Set<String> getFileNamesToCreate() {
   final String name = getBaseName();
   final String suffix = getPropertiesFileSuffix();
   return ContainerUtil.map2Set(
       myLocalesModel.getItems(),
       locale ->
           name
               + (locale == PropertiesUtil.DEFAULT_LOCALE ? "" : ("_" + locale.toString()))
               + suffix);
 }
 private static Map<GroupDescriptor, Set<PatchedUsage>> mapToPatchedUsagesMap(
     Map<GroupDescriptor, Set<UsageDescriptor>> allUsages) {
   Map<GroupDescriptor, Set<PatchedUsage>> patchedUsages =
       new LinkedHashMap<GroupDescriptor, Set<PatchedUsage>>();
   for (Map.Entry<GroupDescriptor, Set<UsageDescriptor>> entry : allUsages.entrySet()) {
     patchedUsages.put(
         entry.getKey(),
         ContainerUtil.map2Set(
             entry.getValue(),
             new Function<UsageDescriptor, PatchedUsage>() {
               @Override
               public PatchedUsage fun(UsageDescriptor usageDescriptor) {
                 return new PatchedUsage(usageDescriptor);
               }
             }));
   }
   return patchedUsages;
 }
  private void assertEvent(Class<? extends VFileEvent> type, String... paths) {
    List<VFileEvent> events = getEvents(type.getSimpleName(), null);
    assertEquals(events.toString(), paths.length, events.size());

    Set<String> pathSet =
        ContainerUtil.map2Set(
            paths,
            new Function<String, String>() {
              @Override
              public String fun(final String path) {
                return FileUtil.toSystemIndependentName(path);
              }
            });

    for (VFileEvent event : events) {
      assertTrue(event.toString(), type.isInstance(event));
      VirtualFile eventFile = event.getFile();
      assertNotNull(event.toString(), eventFile);
      assertTrue(
          eventFile + " not in " + Arrays.toString(paths), pathSet.remove(eventFile.getPath()));
    }
  }
  @NotNull
  public Set<UsageDescriptor> getProjectUsages(@NotNull Project project) {

    final Set<String> languageLevels = new HashSet<String>();
    for (Module module : ModuleManager.getInstance(project).getModules()) {
      final LanguageLevelModuleExtension instance =
          LanguageLevelModuleExtension.getInstance(module);
      final LanguageLevel languageLevel = instance.getLanguageLevel();
      if (languageLevel != null) {
        languageLevels.add(languageLevel.getPresentableText());
      }
    }
    languageLevels.add(
        LanguageLevelProjectExtension.getInstance(project).getLanguageLevel().getPresentableText());

    return ContainerUtil.map2Set(
        languageLevels,
        new Function<String, UsageDescriptor>() {
          @Override
          public UsageDescriptor fun(String languageLevel) {
            return new UsageDescriptor(languageLevel, 1);
          }
        });
  }
Exemplo n.º 10
0
  private List<TemplatesGroup> fillTemplatesMap(WizardContext context) {

    List<ModuleBuilder> builders = ModuleBuilder.getAllBuilders();
    if (context.isCreatingNewProject()) {
      builders.add(new EmptyModuleBuilder());
    }
    Map<String, TemplatesGroup> groupMap = new HashMap<String, TemplatesGroup>();
    for (ModuleBuilder builder : builders) {
      BuilderBasedTemplate template = new BuilderBasedTemplate(builder);
      if (builder.isTemplate()) {
        TemplatesGroup group = groupMap.get(builder.getGroupName());
        if (group == null) {
          group = new TemplatesGroup(builder);
        }
        myTemplatesMap.putValue(group, template);
      } else {
        TemplatesGroup group = new TemplatesGroup(builder);
        groupMap.put(group.getName(), group);
        myTemplatesMap.put(group, new ArrayList<ProjectTemplate>());
      }
    }

    MultiMap<TemplatesGroup, ProjectTemplate> map = CreateFromTemplateMode.getTemplatesMap(context);
    myTemplatesMap.putAllValues(map);

    for (ProjectCategory category : ProjectCategory.EXTENSION_POINT_NAME.getExtensions()) {
      TemplatesGroup group = new TemplatesGroup(category);
      myTemplatesMap.remove(group);
      myTemplatesMap.put(group, new ArrayList<ProjectTemplate>());
    }

    if (context.isCreatingNewProject()) {
      MultiMap<String, ProjectTemplate> localTemplates = loadLocalTemplates();
      for (TemplatesGroup group : myTemplatesMap.keySet()) {
        myTemplatesMap.putValues(group, localTemplates.get(group.getId()));
      }
    }

    // remove Static Web group in IDEA Community if no specific templates found (IDEA-120593)
    if (PlatformUtils.isIdeaCommunity()) {
      for (TemplatesGroup group : myTemplatesMap.keySet()) {
        if (WebModuleTypeBase.WEB_MODULE.equals(group.getId())
            && myTemplatesMap.get(group).isEmpty()) {
          myTemplatesMap.remove(group);
          break;
        }
      }
    }

    List<TemplatesGroup> groups = new ArrayList<TemplatesGroup>(myTemplatesMap.keySet());

    // sorting by module type popularity
    final MultiMap<ModuleType, TemplatesGroup> moduleTypes =
        new MultiMap<ModuleType, TemplatesGroup>();
    for (TemplatesGroup group : groups) {
      ModuleType type = getModuleType(group);
      moduleTypes.putValue(type, group);
    }
    Collections.sort(
        groups,
        new Comparator<TemplatesGroup>() {
          @Override
          public int compare(TemplatesGroup o1, TemplatesGroup o2) {
            int i = o2.getWeight() - o1.getWeight();
            if (i != 0) return i;
            int i1 =
                moduleTypes.get(getModuleType(o2)).size()
                    - moduleTypes.get(getModuleType(o1)).size();
            if (i1 != 0) return i1;
            return o1.compareTo(o2);
          }
        });

    Set<String> groupNames =
        ContainerUtil.map2Set(
            groups,
            new Function<TemplatesGroup, String>() {
              @Override
              public String fun(TemplatesGroup group) {
                return group.getParentGroup();
              }
            });

    // move subgroups
    MultiMap<String, TemplatesGroup> subGroups = new MultiMap<String, TemplatesGroup>();
    for (ListIterator<TemplatesGroup> iterator = groups.listIterator(); iterator.hasNext(); ) {
      TemplatesGroup group = iterator.next();
      String parentGroup = group.getParentGroup();
      if (parentGroup != null
          && groupNames.contains(parentGroup)
          && !group.getName().equals(parentGroup)
          && groupMap.containsKey(parentGroup)) {
        subGroups.putValue(parentGroup, group);
        iterator.remove();
      }
    }
    for (ListIterator<TemplatesGroup> iterator = groups.listIterator(); iterator.hasNext(); ) {
      TemplatesGroup group = iterator.next();
      for (TemplatesGroup subGroup : subGroups.get(group.getName())) {
        iterator.add(subGroup);
      }
    }
    return groups;
  }