public void testRemoveSourceRoot() {
    final VirtualFile root = ModuleRootManager.getInstance(myModule).getContentRoots()[0];

    PsiTodoSearchHelper.SERVICE
        .getInstance(myProject)
        .findFilesWithTodoItems(); // to initialize caches

    new WriteCommandAction.Simple(getProject()) {
      @Override
      protected void run() throws Throwable {
        VirtualFile newFile = createChildData(root, "New.java");
        setFileText(newFile, "class A{ Exception e;} //todo");
      }
    }.execute().throwException();

    PsiDocumentManager.getInstance(myProject).commitAllDocuments();

    PsiTodoSearchHelper.SERVICE.getInstance(myProject).findFilesWithTodoItems(); // to update caches

    VirtualFile[] sourceRoots = ModuleRootManager.getInstance(myModule).getSourceRoots();
    LOG.assertTrue(sourceRoots.length == 1);
    PsiTestUtil.removeSourceRoot(myModule, sourceRoots[0]);

    PsiClass exceptionClass =
        myJavaFacade.findClass("java.lang.Exception", GlobalSearchScope.allScope(getProject()));
    assertNotNull(exceptionClass);
    // currently it actually finds usages by FQN due to Java PSI enabled for out-of-source java
    // files
    // so the following check is disabled
    // checkUsages(exceptionClass, new String[]{});
    checkTodos(new String[] {"2.java", "New.java"});
  }
 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
  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;
  }
Exemplo n.º 4
0
  public static boolean checkSourceRootsConfigured(
      final Module module, final boolean askUserToSetupSourceRoots) {
    List<VirtualFile> sourceRoots =
        ModuleRootManager.getInstance(module).getSourceRoots(JavaModuleSourceRootTypes.SOURCES);
    if (sourceRoots.isEmpty()) {
      if (!askUserToSetupSourceRoots) {
        return false;
      }

      Project project = module.getProject();
      Messages.showErrorDialog(
          project,
          ProjectBundle.message("module.source.roots.not.configured.error", module.getName()),
          ProjectBundle.message("module.source.roots.not.configured.title"));

      ProjectSettingsService.getInstance(project)
          .showModuleConfigurationDialog(module.getName(), CommonContentEntriesEditor.NAME);

      sourceRoots =
          ModuleRootManager.getInstance(module).getSourceRoots(JavaModuleSourceRootTypes.SOURCES);
      if (sourceRoots.isEmpty()) {
        return false;
      }
    }
    return true;
  }
  private void validateModule(@NotNull Module module) throws Exception {
    final String importedModulePath = getProject().getBaseDir().getPath();

    final Element actualImlElement = new Element("root");
    ((ModuleRootManagerImpl) ModuleRootManager.getInstance(module))
        .getState()
        .writeExternal(actualImlElement);
    PathMacros.getInstance().setMacro(MODULE_DIR, importedModulePath);
    PathMacroManager.getInstance(module).collapsePaths(actualImlElement);
    PathMacroManager.getInstance(getProject()).collapsePaths(actualImlElement);
    PathMacros.getInstance().removeMacro(MODULE_DIR);

    final String projectPath = getProject().getBaseDir().getPath();
    final File expectedImlFile = new File(projectPath + "/expected/" + module.getName() + ".iml");
    final Document expectedIml = JDOMUtil.loadDocument(expectedImlFile);
    final Element expectedImlElement = expectedIml.getRootElement();

    final String errorMsg =
        "Configuration of module "
            + module.getName()
            + " does not meet expectations.\nExpected:\n"
            + new String(JDOMUtil.printDocument(expectedIml, "\n"))
            + "\nBut got:\n"
            + new String(JDOMUtil.printDocument(new Document(actualImlElement), "\n"));
    Assert.assertTrue(errorMsg, JDOMUtil.areElementsEqual(expectedImlElement, actualImlElement));
    validateFacet(module);
  }
Exemplo n.º 6
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);
    }
  }
Exemplo n.º 7
0
  private Set<VirtualFile> enumerateGroovyFiles(final Module module) {
    final Set<VirtualFile> moduleClasses = new THashSet<VirtualFile>();
    ModuleRootManager.getInstance(module)
        .getFileIndex()
        .iterateContent(
            new ContentIterator() {
              public boolean processFile(final VirtualFile vfile) {
                if (!vfile.isDirectory()
                    && GroovyFileType.GROOVY_FILE_TYPE.equals(vfile.getFileType())) {

                  AccessToken accessToken =
                      ApplicationManager.getApplication().acquireReadActionLock();

                  try {
                    if (PsiManager.getInstance(myProject).findFile(vfile) instanceof GroovyFile) {
                      moduleClasses.add(vfile);
                    }
                  } finally {
                    accessToken.finish();
                  }
                }
                return true;
              }
            });
    return moduleClasses;
  }
  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 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;
  }
Exemplo n.º 11
0
 @Nullable
 public static PsiDirectory findPossiblePackageDirectoryInModule(
     Module module, String packageName) {
   PsiDirectory psiDirectory = null;
   if (!"".equals(packageName)) {
     PsiPackage rootPackage = findLongestExistingPackage(module.getProject(), packageName);
     if (rootPackage != null) {
       final PsiDirectory[] psiDirectories = getPackageDirectoriesInModule(rootPackage, module);
       if (psiDirectories.length > 0) {
         psiDirectory = psiDirectories[0];
       }
     }
   }
   if (psiDirectory == null) {
     if (checkSourceRootsConfigured(module)) {
       final List<VirtualFile> sourceRoots =
           ModuleRootManager.getInstance(module).getSourceRoots(JavaModuleSourceRootTypes.SOURCES);
       for (VirtualFile sourceRoot : sourceRoots) {
         final PsiDirectory directory =
             PsiManager.getInstance(module.getProject()).findDirectory(sourceRoot);
         if (directory != null) {
           psiDirectory = directory;
           break;
         }
       }
     }
   }
   return psiDirectory;
 }
Exemplo n.º 12
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
  @Override
  public Set<UsageDescriptor> getProjectUsages(@Nullable Project project) {
    if (project == null) return Collections.emptySet();

    final Set<LibraryKind> usedKinds = new HashSet<LibraryKind>();
    final Processor<Library> processor =
        new Processor<Library>() {
          @Override
          public boolean process(Library library) {
            usedKinds.addAll(LibraryPresentationManagerImpl.getLibraryKinds(library, null));
            return true;
          }
        };
    for (Module module : ModuleManager.getInstance(project).getModules()) {
      ModuleRootManager.getInstance(module)
          .orderEntries()
          .librariesOnly()
          .forEachLibrary(processor);
    }

    final HashSet<UsageDescriptor> usageDescriptors = new HashSet<UsageDescriptor>();
    for (LibraryKind kind : usedKinds) {
      usageDescriptors.add(new UsageDescriptor(kind.getKindId(), 1));
    }
    return usageDescriptors;
  }
  protected void setupRootModel(
      final String testDir, final VirtualFile[] sourceDir, final String sdkName) {
    VirtualFile projectDir =
        LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir));
    assertNotNull("could not find project dir " + testDir, projectDir);
    sourceDir[0] = projectDir.findChild("src");
    if (sourceDir[0] == null) {
      sourceDir[0] = projectDir;
    }
    final ModuleRootManager rootManager = ModuleRootManager.getInstance(myModule);
    final ModifiableRootModel rootModel = rootManager.getModifiableModel();
    rootModel.clear();
    // configure source and output path
    final ContentEntry contentEntry = rootModel.addContentEntry(projectDir);
    contentEntry.addSourceFolder(sourceDir[0], false);
    ext_src =
        LocalFileSystem.getInstance().refreshAndFindFileByIoFile(new File(testDir + "/ext_src"));
    if (ext_src != null) {
      contentEntry.addSourceFolder(ext_src, false);
    }

    // IMPORTANT! The jdk must be obtained in a way it is obtained in the normal program!
    // ProjectJdkEx jdk = ProjectJdkTable.getInstance().getInternalJdk();

    rootModel.setSdk(getTestProjectSdk());

    rootModel.commit();
  }
 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 calculateRoots() {
    final ModuleManager moduleManager = ModuleManager.getInstance(myProject);
    // assertion for read access inside
    final Module[] modules =
        ApplicationManager.getApplication()
            .runReadAction(
                new Computable<Module[]>() {
                  public Module[] compute() {
                    return moduleManager.getModules();
                  }
                });

    final TreeSet<VirtualFile> checkSet =
        new TreeSet<VirtualFile>(FilePathComparator.getInstance());
    myRoots = new HashSet<VirtualFile>();
    myRoots.addAll(myInitialRoots);
    checkSet.addAll(myInitialRoots);
    for (Module module : modules) {
      final VirtualFile[] files = ModuleRootManager.getInstance(module).getContentRoots();
      for (VirtualFile file : files) {
        final VirtualFile floor = checkSet.floor(file);
        if (floor != null) {
          myModulesSet.put(file, module.getName());
          myRoots.add(file);
        }
      }
    }
  }
 @Override
 @NotNull
 public Collection<PsiFileSystemItem> getRoots(@NotNull final Module module) {
   return ContainerUtil.mapNotNull(
       ModuleRootManager.getInstance(module).getContentRoots(),
       virtualFile -> PsiManager.getInstance(module.getProject()).findDirectory(virtualFile));
 }
Exemplo n.º 18
0
  @Override
  public VirtualFile[] getSourceRoots(Module module) {
    VirtualFile[] cachedRoots = myModuleToRootsCache.get(module);
    if (cachedRoots != null) {
      if (areFilesValid(cachedRoots)) {
        return cachedRoots;
      } else {
        myModuleToRootsCache.remove(
            module); // clear cache for this module and rebuild list of roots
      }
    }

    Set<VirtualFile> additionalRoots = myModuleToRootsMap.get(module);
    VirtualFile[] moduleRoots = ModuleRootManager.getInstance(module).getSourceRoots();
    if (additionalRoots == null || additionalRoots.isEmpty()) {
      myModuleToRootsCache.put(module, moduleRoots);
      return moduleRoots;
    }

    final VirtualFile[] allRoots = new VirtualFile[additionalRoots.size() + moduleRoots.length];
    System.arraycopy(moduleRoots, 0, allRoots, 0, moduleRoots.length);
    int index = moduleRoots.length;
    for (final VirtualFile additionalRoot : additionalRoots) {
      allRoots[index++] = additionalRoot;
    }
    myModuleToRootsCache.put(module, allRoots);
    return allRoots;
  }
  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;
  }
 private void buildScopeModulesSet(Module module) {
   ModuleRootManager.getInstance(module)
       .orderEntries()
       .recursively()
       .compileOnly()
       .forEachModule(new CommonProcessors.CollectProcessor<Module>(myScopeModules));
 }
  @NotNull
  private static String getPresentableElementPosition(
      @NotNull final CodeInsightTestFixture fixture, final @Nullable PsiElement element) {
    if (element == null) return "";

    final StringBuilder buf = new StringBuilder(element.getText());
    DartComponent component = PsiTreeUtil.getParentOfType(element, DartComponent.class);
    while (component != null) {
      final DartComponentName componentName = component.getComponentName();
      if (componentName != null && componentName != element) {
        buf.insert(0, component.getName() + " -> ");
      }
      component = PsiTreeUtil.getParentOfType(component, DartComponent.class);
    }
    String path =
        element instanceof PsiDirectoryImpl
            ? ((PsiDirectoryImpl) element).getVirtualFile().getPath()
            : element.getContainingFile().getVirtualFile().getPath();

    final String contentRoot =
        ModuleRootManager.getInstance(fixture.getModule()).getContentRoots()[0].getPath();
    if (path.equals(contentRoot)) path = "[content root]";

    final String contentRootWithSlash = contentRoot + "/";
    if (path.startsWith(contentRootWithSlash)) path = path.substring(contentRootWithSlash.length());

    final DartSdk sdk = DartSdk.getDartSdk(element.getProject());
    if (sdk != null && path.startsWith(sdk.getHomePath()))
      path = "[Dart SDK]" + path.substring(sdk.getHomePath().length());

    if (buf.length() > 0) buf.insert(0, " -> ");
    buf.insert(0, path);

    return buf.toString();
  }
Exemplo n.º 22
0
  public boolean isEnabled(AnActionEvent e) {
    PsiElement psiElement = e.getData(LangDataKeys.PSI_ELEMENT);
    if (psiElement == null || !(psiElement instanceof PsiDirectory)) {
      // Can be used only on package
      return false;
    }
    VirtualFile targetDir = ((PsiDirectory) psiElement).getVirtualFile();

    boolean isUnderSourceRoot = false;
    if (psiElement instanceof MPSPsiModel) {
      isUnderSourceRoot = true;
    } else {
      Module m = e.getData(LangDataKeys.MODULE);
      VirtualFile[] sourceRoots = ModuleRootManager.getInstance(m).getSourceRoots(true);
      for (VirtualFile root : sourceRoots) {
        if (targetDir.getPath().equals(root.getPath())) {
          // Can't be source or test folder
          return false;
        }
        isUnderSourceRoot =
            isUnderSourceRoot || FileUtil.isSubPath(root.getPath(), targetDir.getPath());
      }
    }

    return isUnderSourceRoot
        && myOperationContext != null
        && (myModelDescriptor != null || myNewModel)
        && myProject != null;
  }
 @Nullable
 protected VirtualFile findClassFile(String className) {
   final CompilerModuleExtension extension =
       ModuleRootManager.getInstance(myModule).getModuleExtension(CompilerModuleExtension.class);
   //noinspection ConstantConditions
   return extension.getCompilerOutputPath().findChild(className + ".class");
 }
Exemplo n.º 24
0
  @Override
  public Iterable<SDependency> getDeclaredDependencies() {
    if (myDependencies == null) {
      myDependencies = new ArrayList<SDependency>();

      ArrayList<Module> usedModules =
          new ArrayList<Module>(
              Arrays.asList(ModuleRootManager.getInstance(myModule).getDependencies()));
      for (Module usedModule : usedModules) {
        MPSFacet usedModuleMPSFacet =
            FacetManager.getInstance(usedModule).getFacetByType(MPSFacetType.ID);
        if (usedModuleMPSFacet != null && usedModuleMPSFacet.wasInitialized()) {
          myDependencies.add(
              new SDependencyImpl(
                  usedModuleMPSFacet.getSolution(), SDependencyScope.DEFAULT, false));
        }
      }

      addUsedSdk(myDependencies);
      addUsedLibraries(myDependencies);

      // adding JDK module to a set of dependencies
      // why, oh, why are we doing it?
      // FIXME, PLEASE!
      //      Solution jdkSolution = StubSolutionIdea.getJdkSolution();
      //      if (jdkSolution != null) {
      //        myDependencies.add(new Dependency(jdkSolution.getModuleReference(), false));
      //      }
    }
    return myDependencies;
  }
Exemplo n.º 25
0
 public OrderEntry[] getOrderEntries() {
   if (myModifiableRootModel == null) { // do not clone all model if not necessary
     return ModuleRootManager.getInstance(getModule()).getOrderEntries();
   } else {
     return myModifiableRootModel.getOrderEntries();
   }
 }
  private void createTreeModel() {
    final PsiManager psiManager = PsiManager.getInstance(myProject);
    final FileIndex fileIndex =
        myModule != null
            ? ModuleRootManager.getInstance(myModule).getFileIndex()
            : ProjectRootManager.getInstance(myProject).getFileIndex();
    fileIndex.iterateContent(
        new ContentIterator() {
          public boolean processFile(VirtualFile fileOrDir) {
            if (fileOrDir.isDirectory() && fileIndex.isInSourceContent(fileOrDir)) {
              final PsiDirectory psiDirectory = psiManager.findDirectory(fileOrDir);
              LOG.assertTrue(psiDirectory != null);
              PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory);
              if (aPackage != null) {
                addPackage(aPackage);
              }
            }
            return true;
          }
        });

    TreeUtil.sort(
        myModel,
        new Comparator() {
          public int compare(Object o1, Object o2) {
            DefaultMutableTreeNode n1 = (DefaultMutableTreeNode) o1;
            DefaultMutableTreeNode n2 = (DefaultMutableTreeNode) o2;
            PsiNamedElement element1 = (PsiNamedElement) n1.getUserObject();
            PsiNamedElement element2 = (PsiNamedElement) n2.getUserObject();
            return element1.getName().compareToIgnoreCase(element2.getName());
          }
        });
  }
  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;
  }
 private static String setCompilerOutput(Module module, String path, boolean testOutput) {
   VirtualFile output =
       ModuleRootManager.getInstance(module).getContentEntries()[0].getFile().findChild(path);
   assertNotNull(output);
   PsiTestUtil.setCompilerOutputPath(module, output.getUrl(), testOutput);
   return output.getPath().replace('/', File.separatorChar);
 }
  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();
    }
  }
Exemplo n.º 30
0
  @Nullable
  public static String getAnnotationProcessorsGenerationPath(Module module) {
    final CompilerConfiguration config = CompilerConfiguration.getInstance(module.getProject());

    final String sourceDirName = config.getGeneratedSourceDirName(module);
    if (sourceDirName != null && sourceDirName.length() > 0) {
      final String[] roots = ModuleRootManager.getInstance(module).getContentRootUrls();
      if (roots.length == 0) {
        return null;
      }
      if (roots.length > 1) {
        Arrays.sort(roots, URLS_COMPARATOR);
      }
      return VirtualFileManager.extractPath(roots[0]) + "/" + sourceDirName;
    }

    final CompilerProjectExtension extension =
        CompilerProjectExtension.getInstance(module.getProject());
    if (extension == null) {
      return null;
    }
    final String url = extension.getCompilerOutputUrl();
    if (url == null) {
      return null;
    }
    return VirtualFileManager.extractPath(url)
        + "/"
        + DEFAULT_GENERATED_DIR_NAME
        + "/"
        + module.getName().toLowerCase();
  }