Example #1
0
 @Override
 @NotNull
 public Collection<AbstractTreeNode> getChildren() {
   Module module = getValue().getModule();
   final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
   final List<AbstractTreeNode> children = new ArrayList<AbstractTreeNode>();
   final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries();
   for (final OrderEntry orderEntry : orderEntries) {
     if (orderEntry instanceof LibraryOrderEntry) {
       final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry) orderEntry;
       final Library library = libraryOrderEntry.getLibrary();
       if (library == null) {
         continue;
       }
       final String libraryName = library.getName();
       if (libraryName == null || libraryName.length() == 0) {
         addLibraryChildren(libraryOrderEntry, children, getProject(), this);
       } else {
         children.add(
             new NamedLibraryElementNode(
                 getProject(), new NamedLibraryElement(module, libraryOrderEntry), getSettings()));
       }
     } else if (orderEntry instanceof SdkOrderEntry) {
       final SdkOrderEntry sdkOrderEntry = (SdkOrderEntry) orderEntry;
       final Sdk jdk = sdkOrderEntry.getSdk();
       if (jdk != null) {
         children.add(
             new NamedLibraryElementNode(
                 getProject(), new NamedLibraryElement(module, sdkOrderEntry), getSettings()));
       }
     }
   }
   return children;
 }
  @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;
  }
 private void appendChosenAnnotationsRoot(
     @NotNull final OrderEntry entry, @NotNull final VirtualFile vFile) {
   if (entry instanceof LibraryOrderEntry) {
     Library library = ((LibraryOrderEntry) entry).getLibrary();
     LOG.assertTrue(library != null);
     final ModifiableRootModel rootModel =
         ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel();
     final Library.ModifiableModel model = library.getModifiableModel();
     model.addRoot(vFile, AnnotationOrderRootType.getInstance());
     model.commit();
     rootModel.commit();
   } else if (entry instanceof ModuleSourceOrderEntry) {
     final ModifiableRootModel model =
         ModuleRootManager.getInstance(entry.getOwnerModule()).getModifiableModel();
     final JavaModuleExternalPaths extension =
         model.getModuleExtension(JavaModuleExternalPaths.class);
     extension.setExternalAnnotationUrls(
         ArrayUtil.mergeArrays(extension.getExternalAnnotationsUrls(), vFile.getUrl()));
     model.commit();
   } else if (entry instanceof JdkOrderEntry) {
     final SdkModificator sdkModificator = ((JdkOrderEntry) entry).getJdk().getSdkModificator();
     sdkModificator.addRoot(vFile, AnnotationOrderRootType.getInstance());
     sdkModificator.commitChanges();
   }
   myExternalAnnotations.clear();
 }
  @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;
  }
  @Nullable
  private Pair<Set<String>, Set<String>> getAllRoots(boolean includeSourceRoots) {
    if (myProject.isDefault()) return null;

    final Set<String> recursive = new HashSet<String>();
    final Set<String> flat = new HashSet<String>();

    final String projectFilePath = myProject.getProjectFilePath();
    final File projectDirFile = new File(projectFilePath).getParentFile();
    if (projectDirFile != null && projectDirFile.getName().equals(Project.DIRECTORY_STORE_FOLDER)) {
      recursive.add(projectDirFile.getAbsolutePath());
    } else {
      flat.add(projectFilePath);
      final VirtualFile workspaceFile = myProject.getWorkspaceFile();
      if (workspaceFile != null) {
        flat.add(workspaceFile.getPath());
      }
    }

    for (WatchedRootsProvider extension :
        Extensions.getExtensions(WatchedRootsProvider.EP_NAME, myProject)) {
      recursive.addAll(extension.getRootsToWatch());
    }

    final Module[] modules = ModuleManager.getInstance(myProject).getModules();
    for (Module module : modules) {
      flat.add(module.getModuleFilePath());

      final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);

      addRootsToTrack(moduleRootManager.getContentRootUrls(), recursive, flat);

      if (includeSourceRoots) {
        addRootsToTrack(moduleRootManager.getSourceRootUrls(), recursive, flat);
      }

      final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries();
      for (OrderEntry entry : orderEntries) {
        if (entry instanceof LibraryOrSdkOrderEntry) {
          final LibraryOrSdkOrderEntry libSdkEntry = (LibraryOrSdkOrderEntry) entry;
          for (OrderRootType orderRootType : OrderRootType.getAllTypes()) {
            addRootsToTrack(libSdkEntry.getRootUrls(orderRootType), recursive, flat);
          }
        }
      }
    }

    return Pair.create(recursive, flat);
  }
 public void testCompilerOutputInheritance() throws Exception {
   File moduleFile = new File(getTestRoot(), "test.iml");
   Module module = createModule(moduleFile);
   final ModuleRootManagerImpl moduleRootManager =
       (ModuleRootManagerImpl) ModuleRootManager.getInstance(module);
   final ModifiableRootModel rootModel = moduleRootManager.getModifiableModel();
   rootModel.getModuleExtension(CompilerModuleExtension.class).inheritCompilerOutputPath(true);
   ApplicationManager.getApplication()
       .runWriteAction(
           new Runnable() {
             @Override
             public void run() {
               rootModel.commit();
             }
           });
   Element element = new Element("root");
   moduleRootManager.getState().writeExternal(element);
   assertElementEquals(
       element,
       "<root inherit-compiler-output=\"true\">"
           + "<exclude-output />"
           + "<orderEntry type=\"sourceFolder\" forTests=\"false\" />"
           + "</root>",
       module);
 }
  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);
  }
  private void attachLibraries(
      @NotNull Collection<VirtualFile> libraryRoots, Set<VirtualFile> exclusions) {
    ApplicationManager.getApplication().assertIsDispatchThread();

    if (!libraryRoots.isEmpty()) {
      ApplicationManager.getApplication()
          .runWriteAction(
              () -> {
                ModuleRootManager model = ModuleRootManager.getInstance(myModule);
                LibraryOrderEntry goLibraryEntry =
                    OrderEntryUtil.findLibraryOrderEntry(model, getLibraryName());

                if (goLibraryEntry != null && goLibraryEntry.isValid()) {
                  Library library = goLibraryEntry.getLibrary();
                  if (library != null && !((LibraryEx) library).isDisposed()) {
                    fillLibrary(library, libraryRoots, exclusions);
                  }
                } else {
                  LibraryTable libraryTable =
                      LibraryTablesRegistrar.getInstance().getLibraryTable(myModule.getProject());
                  Library library = libraryTable.createLibrary(getLibraryName());
                  fillLibrary(library, libraryRoots, exclusions);
                  ModuleRootModificationUtil.addDependency(myModule, library);
                }
              });
      showNotification(myModule.getProject());
    } else {
      removeLibraryIfNeeded();
    }
  }
  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 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();
      }
    }
  }
 @Nullable
 protected VirtualFile findClassFile(String className) {
   final CompilerModuleExtension extension =
       ModuleRootManager.getInstance(myModule).getModuleExtension(CompilerModuleExtension.class);
   //noinspection ConstantConditions
   return extension.getCompilerOutputPath().findChild(className + ".class");
 }
  public boolean tryToSetUpGroovyFacetOnTheFly(final Module module) {
    final Project project = module.getProject();
    final Library[] libraries = getAllSDKLibraries(project);
    if (libraries.length > 0) {
      final Library library = libraries[0];
      int result =
          Messages.showOkCancelDialog(
              GroovyBundle.message(
                  "groovy.like.library.found.text",
                  module.getName(),
                  library.getName(),
                  getSDKLibVersion(library)),
              GroovyBundle.message("groovy.like.library.found"),
              JetgroovyIcons.Groovy.Groovy_32x32);
      if (result == Messages.OK) {
        AccessToken accessToken = WriteAction.start();

        try {
          ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel();
          LibraryOrderEntry entry = model.addLibraryEntry(libraries[0]);
          LibrariesUtil.placeEntryToCorrectPlace(model, entry);
          model.commit();
          return true;
        } finally {
          accessToken.finish();
        }
      }
    }
    return false;
  }
  public int compare(@NotNull VirtualFile file1, @NotNull VirtualFile file2) {
    List<OrderEntry> entries1 = myProjectFileIndex.getOrderEntriesForFile(file1);
    List<OrderEntry> entries2 = myProjectFileIndex.getOrderEntriesForFile(file2);
    if (entries1.size() != entries2.size()) return 0;

    int res = 0;
    for (OrderEntry entry1 : entries1) {
      Module module = entry1.getOwnerModule();
      ModuleFileIndex moduleFileIndex = ModuleRootManager.getInstance(module).getFileIndex();
      OrderEntry entry2 = moduleFileIndex.getOrderEntryForFile(file2);
      if (entry2 == null) {
        return 0;
      } else {
        int aRes = entry2.compareTo(entry1);
        if (aRes == 0) return 0;
        if (res == 0) {
          res = aRes;
        } else if (res != aRes) {
          return 0;
        }
      }
    }

    return res;
  }
Example #14
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);
    }
  }
  public AddModuleDependencyFix(
      Module currentModule, VirtualFile classVFile, PsiClass[] classes, PsiReference reference) {
    final PsiElement psiElement = reference.getElement();
    final Project project = psiElement.getProject();
    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
    final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();

    for (PsiClass aClass : classes) {
      if (!facade.getResolveHelper().isAccessible(aClass, psiElement, aClass)) continue;
      PsiFile psiFile = aClass.getContainingFile();
      if (psiFile == null) continue;
      VirtualFile virtualFile = psiFile.getVirtualFile();
      if (virtualFile == null) continue;
      final Module classModule = fileIndex.getModuleForFile(virtualFile);
      if (classModule != null
          && classModule != currentModule
          && !ModuleRootManager.getInstance(currentModule).isDependsOn(classModule)) {
        myModules.add(classModule);
      }
    }
    myCurrentModule = currentModule;
    myClassVFile = classVFile;
    myClasses = classes;
    myReference = reference;
  }
  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);
                }
              });
    }
  }
 private ModuleRootManagerImpl createTempModuleRootManager() throws IOException {
   File tmpModule = FileUtil.createTempFile("tst", ModuleFileType.DOT_DEFAULT_EXTENSION);
   myFilesToDelete.add(tmpModule);
   final Module module = createModule(tmpModule);
   final ModuleRootManagerImpl moduleRootManager =
       (ModuleRootManagerImpl) ModuleRootManager.getInstance(module);
   return moduleRootManager;
 }
 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));
     }
   }
 }
Example #19
0
 public static ContentEntry addContentRoot(final Module module, final VirtualFile vDir) {
   final ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
   new WriteCommandAction.Simple(module.getProject()) {
     @Override
     protected void run() throws Throwable {
       final ModifiableRootModel rootModel = rootManager.getModifiableModel();
       rootModel.addContentEntry(vDir);
       rootModel.commit();
     }
   }.execute().throwException();
   for (ContentEntry entry : rootManager.getContentEntries()) {
     if (entry.getFile() == vDir) {
       Assert.assertFalse(((ContentEntryImpl) entry).isDisposed());
       return entry;
     }
   }
   return null;
 }
 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 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);
     }
   }
 }
 @Nullable
 public static OrderEntry findLibraryEntry(@NotNull Module m, @NotNull MavenArtifact artifact) {
   String name = artifact.getLibraryName();
   for (OrderEntry each : ModuleRootManager.getInstance(m).getOrderEntries()) {
     if (each instanceof LibraryOrderEntry
         && name.equals(((LibraryOrderEntry) each).getLibraryName())) {
       return each;
     }
   }
   return null;
 }
  public void testContentWrite() throws Exception {
    File content = getTestRoot();
    File source = new File(content, "source");
    File testSource = new File(content, "testSource");
    File exclude = new File(content, "exclude");
    File classes = new File(content, "classes");
    File testClasses = new File(content, "testClasses");
    final VirtualFile contentFile = LocalFileSystem.getInstance().findFileByIoFile(content);
    assertNotNull(contentFile);
    final VirtualFile sourceFile = LocalFileSystem.getInstance().findFileByIoFile(source);
    assertNotNull(sourceFile);
    final VirtualFile testSourceFile = LocalFileSystem.getInstance().findFileByIoFile(testSource);
    assertNotNull(testSourceFile);
    final VirtualFile excludeFile = LocalFileSystem.getInstance().findFileByIoFile(exclude);

    assertNotNull(excludeFile);
    final VirtualFile classesFile = LocalFileSystem.getInstance().findFileByIoFile(classes);

    assertNotNull(classesFile);
    final VirtualFile testClassesFile = LocalFileSystem.getInstance().findFileByIoFile(testClasses);

    assertNotNull(testClassesFile);

    final File moduleFile = new File(content, "test.iml");
    final Module module = createModule(moduleFile);
    final ModuleRootManagerImpl moduleRootManager =
        (ModuleRootManagerImpl) ModuleRootManager.getInstance(module);

    PsiTestUtil.addContentRoot(module, contentFile);
    PsiTestUtil.addSourceRoot(module, sourceFile);
    PsiTestUtil.addSourceRoot(module, testSourceFile, true);
    ModuleRootModificationUtil.setModuleSdk(module, JavaSdkImpl.getMockJdk17());
    PsiTestUtil.addExcludedRoot(module, excludeFile);
    PsiTestUtil.setCompilerOutputPath(module, classesFile.getUrl(), false);
    PsiTestUtil.setCompilerOutputPath(module, testClassesFile.getUrl(), true);

    final Element element = new Element("root");
    moduleRootManager.getState().writeExternal(element);
    assertElementEquals(
        element,
        "<root inherit-compiler-output=\"false\">"
            + "<output url=\"file://$MODULE_DIR$/classes\" />"
            + "<output-test url=\"file://$MODULE_DIR$/testClasses\" />"
            + "<exclude-output />"
            + "<content url=\"file://$MODULE_DIR$\">"
            + "<sourceFolder url=\"file://$MODULE_DIR$/source\" isTestSource=\"false\" />"
            + "<sourceFolder url=\"file://$MODULE_DIR$/testSource\" isTestSource=\"true\" />"
            + "<excludeFolder url=\"file://$MODULE_DIR$/exclude\" />"
            + "</content>"
            + "<orderEntry type=\"jdk\" jdkName=\"java 1.7\" jdkType=\"JavaSDK\" />"
            + "<orderEntry type=\"sourceFolder\" forTests=\"false\" />"
            + "</root>",
        module);
  }
 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();
             }
           });
 }
Example #25
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;
  }
 @Nullable
 protected VirtualFile findClassFile(String className, Module module) {
   //noinspection ConstantConditions
   VirtualFile path =
       ModuleRootManager.getInstance(module)
           .getModuleExtension(CompilerModuleExtension.class)
           .getCompilerOutputPath();
   path.getChildren();
   assert path != null;
   path.refresh(false, true);
   return path.findChild(className + ".class");
 }
  private boolean isExcludeRoot(VirtualFile file) {
    VirtualFile parent = file.getParent();
    if (parent == null) return false;

    Module module = myProjectRootManager.getFileIndex().getModuleForFile(parent);
    if (module == null) return false;
    VirtualFile[] excludeRoots = ModuleRootManager.getInstance(module).getExcludeRoots();
    for (VirtualFile root : excludeRoots) {
      if (root.equals(file)) return true;
    }
    return false;
  }
  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;
  }
  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);
                              }
                            }
                          });
                }
              });
    }
  }
  public static void excludePackagesFolders(
      final Module module, final VirtualFile pubspecYamlFile) {
    final VirtualFile root = pubspecYamlFile.getParent();
    final VirtualFile contentRoot =
        root == null
            ? null
            : ProjectRootManager.getInstance(module.getProject())
                .getFileIndex()
                .getContentRootForFile(root);
    if (contentRoot == null) return;

    // http://pub.dartlang.org/doc/glossary.html#entrypoint-directory
    // Entrypoint directory: A directory inside your package that is allowed to contain Dart
    // entrypoints.
    // Pub will ensure all of these directories get a “packages” directory, which is needed for
    // “package:” imports to work.
    // Pub has a whitelist of these directories: benchmark, bin, example, test, tool, and web.
    // Any subdirectories of those (except bin) may also contain entrypoints.
    //
    // the same can be seen in the pub tool source code: [repo
    // root]/sdk/lib/_internal/pub/lib/src/entrypoint.dart

    final Collection<String> oldExcludedPackagesUrls =
        ContainerUtil.filter(
            ModuleRootManager.getInstance(module).getExcludeRootUrls(),
            new Condition<String>() {
              final String rootUrlPrefix = root.getUrl() + '/';

              public boolean value(final String url) {
                if (!url.startsWith(rootUrlPrefix)) return false;

                if (url.endsWith("/packages")) return true;

                // excluded subfolder of 'packages' folder
                final int lastSlashIndex = url.lastIndexOf('/');
                if (lastSlashIndex > 0 && url.substring(0, lastSlashIndex).endsWith("/packages"))
                  return true;

                return false;
              }
            });

    final THashSet<String> newExcludedPackagesUrls =
        collectFoldersToExclude(module, pubspecYamlFile);

    if (oldExcludedPackagesUrls.size() != newExcludedPackagesUrls.size()
        || !newExcludedPackagesUrls.containsAll(oldExcludedPackagesUrls)) {
      updateExcludedFolders(module, contentRoot, oldExcludedPackagesUrls, newExcludedPackagesUrls);
    }
  }