@NotNull
  public static Collection<String> collectPythonPath(
      @Nullable Module module, boolean addContentRoots, boolean addSourceRoots) {
    Collection<String> pythonPathList = Sets.newLinkedHashSet();
    if (module != null) {
      Set<Module> dependencies = new HashSet<Module>();
      ModuleUtilCore.getDependencies(module, dependencies);

      if (addContentRoots) {
        addRoots(pythonPathList, ModuleRootManager.getInstance(module).getContentRoots());
        for (Module dependency : dependencies) {
          addRoots(pythonPathList, ModuleRootManager.getInstance(dependency).getContentRoots());
        }
      }
      if (addSourceRoots) {
        addRoots(pythonPathList, ModuleRootManager.getInstance(module).getSourceRoots());
        for (Module dependency : dependencies) {
          addRoots(pythonPathList, ModuleRootManager.getInstance(dependency).getSourceRoots());
        }
      }

      addLibrariesFromModule(module, pythonPathList);
      addRootsFromModule(module, pythonPathList);
      for (Module dependency : dependencies) {
        addLibrariesFromModule(dependency, pythonPathList);
        addRootsFromModule(dependency, pythonPathList);
      }
    }
    return pythonPathList;
  }
  @NotNull
  private Map<VirtualFile, OrderEntry[]> getOrderEntries() {
    Map<VirtualFile, OrderEntry[]> result = myOrderEntries;
    if (result != null) return result;

    MultiMap<VirtualFile, OrderEntry> libClassRootEntries = MultiMap.createSmart();
    MultiMap<VirtualFile, OrderEntry> libSourceRootEntries = MultiMap.createSmart();
    MultiMap<VirtualFile, OrderEntry> depEntries = MultiMap.createSmart();

    for (final Module module : ModuleManager.getInstance(myProject).getModules()) {
      final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
      for (OrderEntry orderEntry : moduleRootManager.getOrderEntries()) {
        if (orderEntry instanceof ModuleOrderEntry) {
          final Module depModule = ((ModuleOrderEntry) orderEntry).getModule();
          if (depModule != null) {
            VirtualFile[] importedClassRoots =
                OrderEnumerator.orderEntries(depModule)
                    .exportedOnly()
                    .recursively()
                    .classes()
                    .usingCache()
                    .getRoots();
            for (VirtualFile importedClassRoot : importedClassRoots) {
              depEntries.putValue(importedClassRoot, orderEntry);
            }
          }
          for (VirtualFile sourceRoot : orderEntry.getFiles(OrderRootType.SOURCES)) {
            depEntries.putValue(sourceRoot, orderEntry);
          }
        } else if (orderEntry instanceof LibraryOrSdkOrderEntry) {
          final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry) orderEntry;
          for (final VirtualFile sourceRoot : entry.getRootFiles(OrderRootType.SOURCES)) {
            libSourceRootEntries.putValue(sourceRoot, orderEntry);
          }
          for (final VirtualFile classRoot : entry.getRootFiles(OrderRootType.CLASSES)) {
            libClassRootEntries.putValue(classRoot, orderEntry);
          }
        }
      }
    }

    RootInfo rootInfo = buildRootInfo(myProject);
    result = ContainerUtil.newHashMap();
    Set<VirtualFile> allRoots = rootInfo.getAllRoots();
    for (VirtualFile file : allRoots) {
      List<VirtualFile> hierarchy = getHierarchy(file, allRoots, rootInfo);
      result.put(
          file,
          hierarchy == null
              ? OrderEntry.EMPTY_ARRAY
              : calcOrderEntries(
                  rootInfo, depEntries, libClassRootEntries, libSourceRootEntries, hierarchy));
    }
    myOrderEntries = result;
    return result;
  }
Пример #3
0
  public void collectCommonPluginRoots(
      Map<String, VirtualFile> result, @NotNull Module module, boolean refresh) {
    if (isCommonPluginsModule(module)) {
      for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) {
        String pluginName = getInstalledPluginNameByPath(module.getProject(), root);
        if (pluginName != null) {
          result.put(pluginName, root);
        }
      }
    } else {
      VirtualFile root = findAppRoot(module);
      if (root == null) return;

      extractPlugins(
          module.getProject(), root.findChild(MvcModuleStructureUtil.PLUGINS_DIRECTORY), result);
      extractPlugins(
          module.getProject(),
          MvcModuleStructureUtil.findFile(getCommonPluginsDir(module), refresh),
          result);
      extractPlugins(
          module.getProject(),
          MvcModuleStructureUtil.findFile(getGlobalPluginsDir(module), refresh),
          result);
    }
  }
  private static void addDependencyOnDartPackagesLibrary(
      @NotNull final Module module, @NotNull final Library library) {
    final ModifiableRootModel modifiableModel =
        ModuleRootManager.getInstance(module).getModifiableModel();
    try {
      for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
        if (orderEntry instanceof LibraryOrderEntry
            && LibraryTablesRegistrar.PROJECT_LEVEL.equals(
                ((LibraryOrderEntry) orderEntry).getLibraryLevel())
            && DartPackagesLibraryType.DART_PACKAGES_LIBRARY_NAME.equals(
                ((LibraryOrderEntry) orderEntry).getLibraryName())) {
          return; // dependency already exists
        }
      }

      modifiableModel.addLibraryEntry(library);

      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                @Override
                public void run() {
                  modifiableModel.commit();
                }
              });
    } finally {
      if (!modifiableModel.isDisposed()) {
        modifiableModel.dispose();
      }
    }
  }
  private void initPubListPackageDirsMap(final @NotNull VirtualFile contextFile) {
    final Module module = ModuleUtilCore.findModuleForFile(contextFile, myProject);

    final List<OrderEntry> orderEntries =
        module != null
            ? Arrays.asList(ModuleRootManager.getInstance(module).getOrderEntries())
            : ProjectRootManager.getInstance(myProject)
                .getFileIndex()
                .getOrderEntriesForFile(contextFile);
    for (OrderEntry orderEntry : orderEntries) {
      if (orderEntry instanceof LibraryOrderEntry
          && LibraryTablesRegistrar.PROJECT_LEVEL.equals(
              ((LibraryOrderEntry) orderEntry).getLibraryLevel())
          && PubListPackageDirsAction.PUB_LIST_PACKAGE_DIRS_LIB_NAME.equals(
              ((LibraryOrderEntry) orderEntry).getLibraryName())) {
        final LibraryEx library = (LibraryEx) ((LibraryOrderEntry) orderEntry).getLibrary();
        final LibraryProperties properties = library == null ? null : library.getProperties();

        if (properties instanceof DartListPackageDirsLibraryProperties) {
          myPubListPackageDirsMap.putAll(
              ((DartListPackageDirsLibraryProperties) properties).getPackageNameToDirsMap());
          return;
        }
      }
    }
  }
  private void buildEntries(
      @NotNull final Module module,
      @NotNull final Set<Module> processedModules,
      @NotNull final Set<Library> processedLibraries,
      @NotNull final Set<Sdk> processedSdk,
      Condition<OrderEntry> condition) {
    if (!processedModules.add(module)) return;

    ModuleRootManager.getInstance(module)
        .orderEntries()
        .recursively()
        .satisfying(condition)
        .process(
            new RootPolicy<LinkedHashSet<VirtualFile>>() {
              @Override
              public LinkedHashSet<VirtualFile> visitLibraryOrderEntry(
                  final LibraryOrderEntry libraryOrderEntry,
                  final LinkedHashSet<VirtualFile> value) {
                final Library library = libraryOrderEntry.getLibrary();
                if (library != null && processedLibraries.add(library)) {
                  ContainerUtil.addAll(
                      value, libraryOrderEntry.getFiles(BinariesOrderRootType.getInstance()));
                }
                return value;
              }

              @Override
              public LinkedHashSet<VirtualFile> visitModuleSourceOrderEntry(
                  final ModuleSourceOrderEntry moduleSourceOrderEntry,
                  final LinkedHashSet<VirtualFile> value) {
                processedModules.add(moduleSourceOrderEntry.getOwnerModule());
                ContainerUtil.addAll(value, moduleSourceOrderEntry.getRootModel().getSourceRoots());
                return value;
              }

              @Override
              public LinkedHashSet<VirtualFile> visitModuleOrderEntry(
                  ModuleOrderEntry moduleOrderEntry, LinkedHashSet<VirtualFile> value) {
                final Module depModule = moduleOrderEntry.getModule();
                if (depModule != null) {
                  ContainerUtil.addAll(
                      value, ModuleRootManager.getInstance(depModule).getSourceRoots());
                }
                return value;
              }

              @Override
              public LinkedHashSet<VirtualFile> visitModuleExtensionSdkOrderEntry(
                  final ModuleExtensionWithSdkOrderEntry sdkOrderEntry,
                  final LinkedHashSet<VirtualFile> value) {
                final Sdk jdk = sdkOrderEntry.getSdk();
                if (jdk != null && processedSdk.add(jdk)) {
                  ContainerUtil.addAll(
                      value, sdkOrderEntry.getFiles(BinariesOrderRootType.getInstance()));
                }
                return value;
              }
            },
            myEntries);
  }
  public static void createSourceRootIfNotExist(
      @NotNull final String path, @NotNull final Module module) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    final File rootFile = new File(path);
    final boolean created;
    if (!rootFile.exists()) {
      if (!rootFile.mkdirs()) return;
      created = true;
    } else {
      created = false;
    }

    final Project project = module.getProject();
    Module genModule = module;

    final AndroidFacet facet = AndroidFacet.getInstance(genModule);

    if (facet != null && facet.getConfiguration().LIBRARY_PROJECT) {
      removeGenModule(module);
    }

    if (project.isDisposed() || genModule.isDisposed()) {
      return;
    }

    final VirtualFile root;
    if (created) {
      root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(rootFile);
    } else {
      root = LocalFileSystem.getInstance().findFileByIoFile(rootFile);
    }
    if (root != null) {
      final ModuleRootManager manager = ModuleRootManager.getInstance(genModule);
      unexcludeRootIfNeccessary(root, manager);
      for (VirtualFile existingRoot : manager.getSourceRoots()) {
        if (existingRoot == root) return;
      }
      ApplicationManager.getApplication()
          .runWriteAction(
              new Runnable() {
                public void run() {
                  addSourceRoot(manager, root);
                }
              });
    }
  }
 public static void addJavaHome(@NotNull JavaParameters params, @NotNull Module module) {
   final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
   if (sdk != null && sdk.getSdkType() instanceof JavaSdkType) {
     String path = StringUtil.trimEnd(sdk.getHomePath(), File.separator);
     if (StringUtil.isNotEmpty(path)) {
       params.addEnv("JAVA_HOME", FileUtil.toSystemDependentName(path));
     }
   }
 }
 private static void collectModules(Module module, Set<Module> result, Module[] allModules) {
   if (!result.add(module)) {
     return;
   }
   for (Module otherModule : allModules) {
     if (ModuleRootManager.getInstance(otherModule).isDependsOn(module)) {
       collectModules(otherModule, result, allModules);
     }
   }
 }
 public static void addSourceRoot(
     final ModuleRootManager manager, @NotNull final VirtualFile root) {
   final ModifiableRootModel model = manager.getModifiableModel();
   ContentEntry contentEntry = findContentEntryForRoot(model, root);
   if (contentEntry == null) {
     contentEntry = model.addContentEntry(root);
   }
   contentEntry.addSourceFolder(root, false);
   model.commit();
 }
 private static void unexcludeRootIfNeccessary(
     @NotNull VirtualFile root, @NotNull ModuleRootManager manager) {
   Set<VirtualFile> excludedRoots =
       new HashSet<VirtualFile>(Arrays.asList(manager.getExcludeRoots()));
   VirtualFile excludedRoot = root;
   while (excludedRoot != null && !excludedRoots.contains(excludedRoot)) {
     excludedRoot = excludedRoot.getParent();
   }
   if (excludedRoot == null) {
     return;
   }
   Set<VirtualFile> rootsToExclude = new HashSet<VirtualFile>();
   collectChildrenRecursively(excludedRoot, root, rootsToExclude);
   final ModifiableRootModel model = manager.getModifiableModel();
   ContentEntry contentEntry = findContentEntryForRoot(model, excludedRoot);
   if (contentEntry != null) {
     ExcludeFolder excludedFolder = null;
     for (ExcludeFolder folder : contentEntry.getExcludeFolders()) {
       if (folder.getFile() == excludedRoot) {
         excludedFolder = folder;
         break;
       }
     }
     if (excludedFolder != null) {
       contentEntry.removeExcludeFolder(excludedFolder);
     }
     for (VirtualFile rootToExclude : rootsToExclude) {
       if (!excludedRoots.contains(rootToExclude)) {
         contentEntry.addExcludeFolder(rootToExclude);
       }
     }
   }
   ApplicationManager.getApplication()
       .runWriteAction(
           new Runnable() {
             @Override
             public void run() {
               model.commit();
             }
           });
 }
Пример #12
0
  public static ContentEntry addContentRoot(Module module, VirtualFile vDir) {
    ModuleRootModificationUtil.updateModel(module, model -> model.addContentEntry(vDir));

    for (ContentEntry entry : ModuleRootManager.getInstance(module).getContentEntries()) {
      if (Comparing.equal(entry.getFile(), vDir)) {
        Assert.assertFalse(((ContentEntryImpl) entry).isDisposed());
        return entry;
      }
    }

    return null;
  }
Пример #13
0
  @Nullable
  public VirtualFile findAppRoot(@Nullable Module module) {
    if (module == null) return null;

    String appDirName = getApplicationDirectoryName();

    for (VirtualFile root : ModuleRootManager.getInstance(module).getContentRoots()) {
      if (root.findChild(appDirName) != null) return root;
    }

    return null;
  }
  private static void removeGenModule(@NotNull final Module libModule) {
    final String genModuleName = getGenModuleName(libModule);
    final ModuleManager moduleManager = ModuleManager.getInstance(libModule.getProject());
    final ModifiableRootModel model = ModuleRootManager.getInstance(libModule).getModifiableModel();

    for (OrderEntry entry : model.getOrderEntries()) {
      if (entry instanceof ModuleOrderEntry
          && genModuleName.equals(((ModuleOrderEntry) entry).getModuleName())) {
        model.removeOrderEntry(entry);
      }
    }

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              @Override
              public void run() {
                model.commit();
              }
            });

    final Module genModule = moduleManager.findModuleByName(genModuleName);
    if (genModule == null) {
      return;
    }
    moduleManager.disposeModule(genModule);

    final VirtualFile moduleFile = genModule.getModuleFile();

    if (moduleFile != null) {
      ApplicationManager.getApplication()
          .invokeLater(
              new Runnable() {
                @Override
                public void run() {
                  ApplicationManager.getApplication()
                      .runWriteAction(
                          new Runnable() {
                            @Override
                            public void run() {
                              try {
                                moduleFile.delete(libModule.getProject());
                              } catch (IOException e) {
                                LOG.error(e);
                              }
                            }
                          });
                }
              });
    }
  }
 @Nullable
 private ModuleSourceOrderEntry getModuleSourceEntry(
     @NotNull List<VirtualFile> hierarchy,
     @NotNull VirtualFile moduleContentRoot,
     @NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries) {
   Module module = contentRootOf.get(moduleContentRoot);
   for (VirtualFile root : hierarchy) {
     if (sourceRootOf.get(root).contains(module)) {
       return ContainerUtil.findInstance(
           ModuleRootManager.getInstance(module).getOrderEntries(),
           ModuleSourceOrderEntry.class);
     }
     if (libClassRootEntries.containsKey(root)) {
       return null;
     }
   }
   return null;
 }
  public void createApplicationIfNeeded(@NotNull final Module module) {
    if (findAppRoot(module) == null && module.getUserData(CREATE_APP_STRUCTURE) == Boolean.TRUE) {
      while (ModuleRootManager.getInstance(module).getSdk() == null) {
        if (Messages.showYesNoDialog(
                module.getProject(),
                "Cannot generate "
                    + getDisplayName()
                    + " project structure because JDK is not specified for module \""
                    + module.getName()
                    + "\".\n"
                    + getDisplayName()
                    + " project will not be created if you don't specify JDK.\nDo you want to specify JDK?",
                "Error",
                Messages.getErrorIcon())
            == Messages.NO) {
          return;
        }
        ProjectSettingsService.getInstance(module.getProject())
            .showModuleConfigurationDialog(module.getName(), ClasspathEditor.NAME);
      }
      module.putUserData(CREATE_APP_STRUCTURE, null);
      final GeneralCommandLine commandLine = getCreationCommandLine(module);
      if (commandLine == null) return;

      MvcConsole.executeProcess(
          module,
          commandLine,
          new Runnable() {
            public void run() {
              VirtualFile root = findAppRoot(module);
              if (root == null) return;

              PsiDirectory psiDir = PsiManager.getInstance(module.getProject()).findDirectory(root);
              IdeView ide =
                  LangDataKeys.IDE_VIEW.getData(DataManager.getInstance().getDataContext());
              if (ide != null) ide.selectElement(psiDir);

              // also here comes fileCreated(application.properties) which manages roots and run
              // configuration
            }
          },
          true);
    }
  }
  FindInProjectTask(
      @NotNull final FindModel findModel,
      @NotNull final Project project,
      @Nullable final PsiDirectory psiDirectory) {
    myFindModel = findModel;
    myProject = project;
    myPsiDirectory = psiDirectory;
    myPsiManager = PsiManager.getInstance(project);

    final String moduleName = findModel.getModuleName();
    myModule =
        moduleName == null
            ? null
            : ApplicationManager.getApplication()
                .runReadAction(
                    new Computable<Module>() {
                      @Override
                      public Module compute() {
                        return ModuleManager.getInstance(project).findModuleByName(moduleName);
                      }
                    });
    myFileIndex =
        myModule == null
            ? ProjectRootManager.getInstance(project).getFileIndex()
            : ModuleRootManager.getInstance(myModule).getFileIndex();

    final String filter = findModel.getFileFilter();
    final Pattern pattern = FindInProjectUtil.createFileMaskRegExp(filter);

    //noinspection unchecked
    myFileMask =
        pattern == null
            ? Condition.TRUE
            : new Condition<VirtualFile>() {
              @Override
              public boolean value(VirtualFile file) {
                return file != null && pattern.matcher(file.getName()).matches();
              }
            };

    final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
    myProgress = progress != null ? progress : new EmptyProgressIndicator();
  }
  private static void removeSourceRoot(@NotNull Module module, @NotNull final VirtualFile root) {
    final ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel();
    final ContentEntry contentEntry = findContentEntryForRoot(model, root);

    if (contentEntry != null) {
      for (SourceFolder sourceFolder : contentEntry.getSourceFolders()) {
        if (sourceFolder.getFile() == root) {
          contentEntry.removeSourceFolder(sourceFolder);
        }
      }
    }

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              @Override
              public void run() {
                model.commit();
              }
            });
  }
 private static void addLibrariesFromModule(Module module, Collection<String> list) {
   final OrderEntry[] entries = ModuleRootManager.getInstance(module).getOrderEntries();
   for (OrderEntry entry : entries) {
     if (entry instanceof LibraryOrderEntry) {
       final String name = ((LibraryOrderEntry) entry).getLibraryName();
       if (name != null
           && name.endsWith(LibraryContributingFacet.PYTHON_FACET_LIBRARY_NAME_SUFFIX)) {
         // skip libraries from Python facet
         continue;
       }
       for (VirtualFile root : ((LibraryOrderEntry) entry).getRootFiles(OrderRootType.CLASSES)) {
         final Library library = ((LibraryOrderEntry) entry).getLibrary();
         if (!PlatformUtils.isPyCharm()) {
           addToPythonPath(root, list);
         } else if (library instanceof LibraryImpl) {
           final PersistentLibraryKind<?> kind = ((LibraryImpl) library).getKind();
           if (kind == PythonLibraryType.getInstance().getKind()) {
             addToPythonPath(root, list);
           }
         }
       }
     }
   }
 }
  // currently only one level here..
  public boolean contains(@NotNull String name, @NotNull final VirtualFile vFile) {
    final ProjectFileIndex projectFileIndex =
        ProjectRootManager.getInstance(myProject).getFileIndex();
    final Set<Boolean> find = new HashSet<Boolean>();
    final ContentIterator contentIterator =
        new ContentIterator() {
          public boolean processFile(VirtualFile fileOrDir) {
            if (fileOrDir != null && fileOrDir.getPath().equals(vFile.getPath())) {
              find.add(Boolean.TRUE);
            }
            return true;
          }
        };

    Collection<TreeItem<Pair<AbstractUrl, String>>> urls = getFavoritesListRootUrls(name);
    for (TreeItem<Pair<AbstractUrl, String>> pair : urls) {
      AbstractUrl abstractUrl = pair.getData().getFirst();
      if (abstractUrl == null) {
        continue;
      }
      final Object[] path = abstractUrl.createPath(myProject);
      if (path == null || path.length < 1 || path[0] == null) {
        continue;
      }
      Object element = path[path.length - 1];
      if (element instanceof SmartPsiElementPointer) {
        final VirtualFile virtualFile =
            PsiUtilBase.getVirtualFile(((SmartPsiElementPointer) element).getElement());
        if (virtualFile == null) continue;
        if (vFile.getPath().equals(virtualFile.getPath())) {
          return true;
        }
        if (!virtualFile.isDirectory()) {
          continue;
        }
        projectFileIndex.iterateContentUnderDirectory(virtualFile, contentIterator);
      }

      if (element instanceof PsiElement) {
        final VirtualFile virtualFile = PsiUtilBase.getVirtualFile((PsiElement) element);
        if (virtualFile == null) continue;
        if (vFile.getPath().equals(virtualFile.getPath())) {
          return true;
        }
        if (!virtualFile.isDirectory()) {
          continue;
        }
        projectFileIndex.iterateContentUnderDirectory(virtualFile, contentIterator);
      }
      if (element instanceof Module) {
        ModuleRootManager.getInstance((Module) element)
            .getFileIndex()
            .iterateContent(contentIterator);
      }
      if (element instanceof LibraryGroupElement) {
        final boolean inLibrary =
            ModuleRootManager.getInstance(((LibraryGroupElement) element).getModule())
                    .getFileIndex()
                    .isInContent(vFile)
                && projectFileIndex.isInLibraryClasses(vFile);
        if (inLibrary) {
          return true;
        }
      }
      if (element instanceof NamedLibraryElement) {
        NamedLibraryElement namedLibraryElement = (NamedLibraryElement) element;
        final VirtualFile[] files =
            namedLibraryElement.getOrderEntry().getRootFiles(OrderRootType.CLASSES);
        if (files != null && ArrayUtil.find(files, vFile) > -1) {
          return true;
        }
      }
      if (element instanceof ModuleGroup) {
        ModuleGroup group = (ModuleGroup) element;
        final Collection<Module> modules = group.modulesInGroup(myProject, true);
        for (Module module : modules) {
          ModuleRootManager.getInstance(module).getFileIndex().iterateContent(contentIterator);
        }
      }

      for (FavoriteNodeProvider provider :
          Extensions.getExtensions(FavoriteNodeProvider.EP_NAME, myProject)) {
        if (provider.elementContainsFile(element, vFile)) {
          return true;
        }
      }

      if (!find.isEmpty()) {
        return true;
      }
    }
    return false;
  }
Пример #21
0
 private ModuleRootManager getRootManager(String module) {
   return ModuleRootManager.getInstance(getModule(module));
 }
Пример #22
0
 private CompilerModuleExtension getCompilerExtension(String module) {
   ModuleRootManager m = getRootManager(module);
   return CompilerModuleExtension.getInstance(m.getModule());
 }
  @NotNull
  private RootInfo buildRootInfo(@NotNull Project project) {
    final RootInfo info = new RootInfo();
    for (final Module module : ModuleManager.getInstance(project).getModules()) {
      final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);

      for (final VirtualFile contentRoot : moduleRootManager.getContentRoots()) {
        if (!info.contentRootOf.containsKey(contentRoot)) {
          info.contentRootOf.put(contentRoot, module);
        }
      }

      for (ContentEntry contentEntry : moduleRootManager.getContentEntries()) {
        if (!(contentEntry instanceof ContentEntryImpl)
            || !((ContentEntryImpl) contentEntry).isDisposed()) {
          for (VirtualFile excludeRoot : contentEntry.getExcludeFolderFiles()) {
            info.excludedFromModule.put(excludeRoot, module);
          }
        }

        // Init module sources
        for (final SourceFolder sourceFolder : contentEntry.getSourceFolders()) {
          final VirtualFile sourceFolderRoot = sourceFolder.getFile();
          if (sourceFolderRoot != null) {
            info.rootTypeId.put(sourceFolderRoot, getRootTypeId(sourceFolder.getRootType()));
            info.classAndSourceRoots.add(sourceFolderRoot);
            info.sourceRootOf.putValue(sourceFolderRoot, module);
            info.packagePrefix.put(sourceFolderRoot, sourceFolder.getPackagePrefix());
          }
        }
      }

      for (OrderEntry orderEntry : moduleRootManager.getOrderEntries()) {
        if (orderEntry instanceof LibraryOrSdkOrderEntry) {
          final LibraryOrSdkOrderEntry entry = (LibraryOrSdkOrderEntry) orderEntry;
          final VirtualFile[] sourceRoots = entry.getRootFiles(OrderRootType.SOURCES);
          final VirtualFile[] classRoots = entry.getRootFiles(OrderRootType.CLASSES);

          // Init library sources
          for (final VirtualFile sourceRoot : sourceRoots) {
            info.classAndSourceRoots.add(sourceRoot);
            info.libraryOrSdkSources.add(sourceRoot);
            info.packagePrefix.put(sourceRoot, "");
          }

          // init library classes
          for (final VirtualFile classRoot : classRoots) {
            info.classAndSourceRoots.add(classRoot);
            info.libraryOrSdkClasses.add(classRoot);
            info.packagePrefix.put(classRoot, "");
          }

          if (orderEntry instanceof LibraryOrderEntry) {
            Library library = ((LibraryOrderEntry) orderEntry).getLibrary();
            if (library != null) {
              for (VirtualFile root : ((LibraryEx) library).getExcludedRoots()) {
                info.excludedFromLibraries.putValue(root, library);
              }
              for (VirtualFile root : sourceRoots) {
                info.sourceOfLibraries.putValue(root, library);
              }
              for (VirtualFile root : classRoots) {
                info.classOfLibraries.putValue(root, library);
              }
            }
          }
        }
      }
    }

    for (DirectoryIndexExcludePolicy policy :
        Extensions.getExtensions(DirectoryIndexExcludePolicy.EP_NAME, project)) {
      Collections.addAll(info.excludedFromProject, policy.getExcludeRootsForProject());
    }
    return info;
  }
  private static DFSTBuilder<RootModelImpl> createDFSTBuilder(
      List<RootModelImpl> rootModels, final ModifiableModuleModel moduleModel) {
    final Map<String, RootModelImpl> nameToModel = ContainerUtil.newHashMap();
    for (RootModelImpl rootModel : rootModels) {
      String name = rootModel.getModule().getName();
      LOG.assertTrue(!nameToModel.containsKey(name), name);
      nameToModel.put(name, rootModel);
    }

    Module[] modules = moduleModel.getModules();
    for (Module module : modules) {
      String name = module.getName();
      if (!nameToModel.containsKey(name)) {
        RootModelImpl rootModel =
            ((ModuleRootManagerImpl) ModuleRootManager.getInstance(module)).getRootModel();
        nameToModel.put(name, rootModel);
      }
    }

    final Collection<RootModelImpl> allRootModels = nameToModel.values();
    GraphGenerator.SemiGraph<RootModelImpl> graph =
        new GraphGenerator.SemiGraph<RootModelImpl>() {
          @Override
          public Collection<RootModelImpl> getNodes() {
            return allRootModels;
          }

          @Override
          public Iterator<RootModelImpl> getIn(RootModelImpl rootModel) {
            OrderEnumerator entries =
                rootModel
                    .orderEntries()
                    .withoutSdk()
                    .withoutLibraries()
                    .withoutModuleSourceEntries();
            List<String> namesList =
                entries.process(
                    new RootPolicy<List<String>>() {
                      @Override
                      public List<String> visitModuleOrderEntry(
                          ModuleOrderEntry moduleOrderEntry, List<String> strings) {
                        Module module = moduleOrderEntry.getModule();
                        if (module != null && !module.isDisposed()) {
                          strings.add(module.getName());
                        } else {
                          final Module moduleToBeRenamed =
                              moduleModel.getModuleToBeRenamed(moduleOrderEntry.getModuleName());
                          if (moduleToBeRenamed != null && !moduleToBeRenamed.isDisposed()) {
                            strings.add(moduleToBeRenamed.getName());
                          }
                        }
                        return strings;
                      }
                    },
                    new ArrayList<String>());

            String[] names = ArrayUtil.toStringArray(namesList);
            List<RootModelImpl> result = new ArrayList<RootModelImpl>();
            for (String name : names) {
              RootModelImpl depRootModel = nameToModel.get(name);
              if (depRootModel != null) { // it is ok not to find one
                result.add(depRootModel);
              }
            }
            return result.iterator();
          }
        };
    return new DFSTBuilder<RootModelImpl>(
        new GraphGenerator<RootModelImpl>(new CachingSemiGraph<RootModelImpl>(graph)));
  }
  @Override
  public List<Module> commit(
      @NotNull Project project,
      @Nullable ModifiableModuleModel moduleModel,
      @NotNull ModulesProvider modulesProvider,
      @Nullable ModifiableArtifactModel modifiableArtifactModel) {
    Set<String> selectedAppNames = ContainerUtil.newHashSet();
    for (ImportedOtpApp importedOtpApp : mySelectedOtpApps) {
      selectedAppNames.add(importedOtpApp.getName());
    }
    Sdk projectSdk = fixProjectSdk(project);
    List<Module> createdModules = new ArrayList<Module>();
    final List<ModifiableRootModel> createdRootModels = new ArrayList<ModifiableRootModel>();
    final ModifiableModuleModel obtainedModuleModel =
        moduleModel != null ? moduleModel : ModuleManager.getInstance(project).getModifiableModel();
    for (ImportedOtpApp importedOtpApp : mySelectedOtpApps) {
      VirtualFile ideaModuleDir = importedOtpApp.getRoot();
      String ideaModuleFile =
          ideaModuleDir.getCanonicalPath() + File.separator + importedOtpApp.getName() + ".iml";
      Module module =
          obtainedModuleModel.newModule(ideaModuleFile, ErlangModuleType.getInstance().getId());
      createdModules.add(module);
      importedOtpApp.setModule(module);
      if (importedOtpApp.getIdeaModuleFile() == null) {
        ModifiableRootModel rootModel = ModuleRootManager.getInstance(module).getModifiableModel();
        // Make it inherit SDK from the project.
        rootModel.inheritSdk();
        // Initialize source and test paths.
        ContentEntry content = rootModel.addContentEntry(importedOtpApp.getRoot());
        addSourceDirToContent(content, ideaModuleDir, "src", false);
        addSourceDirToContent(content, ideaModuleDir, "test", true);
        addIncludeDirectories(content, importedOtpApp);
        // Exclude standard folders
        excludeDirFromContent(content, ideaModuleDir, "doc");
        // Initialize output paths according to Rebar conventions.
        CompilerModuleExtension compilerModuleExt =
            rootModel.getModuleExtension(CompilerModuleExtension.class);
        compilerModuleExt.inheritCompilerOutputPath(false);
        compilerModuleExt.setCompilerOutputPath(ideaModuleDir + File.separator + "ebin");
        compilerModuleExt.setCompilerOutputPathForTests(ideaModuleDir + File.separator + ".eunit");
        createdRootModels.add(rootModel);
        // Set inter-module dependencies
        resolveModuleDeps(rootModel, importedOtpApp, projectSdk, selectedAppNames);
      }
    }
    // Commit project structure.
    LOG.info("Commit project structure");
    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              public void run() {
                for (ModifiableRootModel rootModel : createdRootModels) {
                  rootModel.commit();
                }
                obtainedModuleModel.commit();
              }
            });

    addErlangFacets(mySelectedOtpApps);
    RebarSettings.getInstance(project).setRebarPath(myRebarPath);
    if (myIsImportingProject) {
      ErlangCompilerSettings.getInstance(project).setUseRebarCompilerEnabled(true);
    }
    CompilerWorkspaceConfiguration.getInstance(project).CLEAR_OUTPUT_DIRECTORY = false;

    return createdModules;
  }
Пример #26
0
  private void buildOutputItemsList(
      final String outputDir,
      final Module module,
      VirtualFile from,
      final FileTypeManager typeManager,
      final VirtualFile sourceRoot,
      final String packagePrefix,
      final List<File> filesToRefresh,
      final Map<String, Collection<TranslatingCompiler.OutputItem>> results)
      throws CacheCorruptedException {
    final Ref<CacheCorruptedException> exRef = new Ref<CacheCorruptedException>(null);
    final ModuleFileIndex fileIndex = ModuleRootManager.getInstance(module).getFileIndex();
    final GlobalSearchScope srcRootScope =
        GlobalSearchScope.moduleScope(module)
            .intersectWith(GlobalSearchScopes.directoryScope(myProject, sourceRoot, true));

    final Collection<FileType> registeredInputTypes =
        CompilerManager.getInstance(myProject).getRegisteredInputTypes(myTranslatingCompiler);

    final ContentIterator contentIterator =
        new ContentIterator() {
          public boolean processFile(final VirtualFile child) {
            try {
              if (child.isValid()) {
                if (!child.isDirectory() && registeredInputTypes.contains(child.getFileType())) {
                  updateOutputItemsList(
                      outputDir,
                      child,
                      sourceRoot,
                      packagePrefix,
                      filesToRefresh,
                      results,
                      srcRootScope);
                }
              }
              return true;
            } catch (CacheCorruptedException e) {
              exRef.set(e);
              return false;
            }
          }
        };
    if (fileIndex.isInContent(from)) {
      // use file index for iteration to handle 'inner modules' and excludes properly
      fileIndex.iterateContentUnderDirectory(from, contentIterator);
    } else {
      // seems to be a root for generated sources
      VfsUtilCore.visitChildrenRecursively(
          from,
          new VirtualFileVisitor() {
            @Override
            public boolean visitFile(@NotNull VirtualFile file) {
              if (!file.isDirectory()) {
                contentIterator.processFile(file);
              }
              return true;
            }
          });
    }
    final CacheCorruptedException exc = exRef.get();
    if (exc != null) {
      throw exc;
    }
  }
 private static void removeModuleOutput(Module module, List<VirtualFile> from) {
   final CompilerModuleExtension extension =
       ModuleRootManager.getInstance(module).getModuleExtension(CompilerModuleExtension.class);
   from.remove(extension.getCompilerOutputPath());
   from.remove(extension.getCompilerOutputPathForTests());
 }