下面列出了org.jetbrains.annotations.SystemIndependent#com.intellij.openapi.roots.ModuleRootManager 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public List<VirtualFile>[] getDeploymentFiles(Module module) {
List<VirtualFile>[] result = ToolDelegate.initDeploymentFiles();
ModuleRootManager manager = ModuleRootManager.getInstance(module);
Set<String> deploymentIds = new HashSet<>();
try {
manager.orderEntries().forEachLibrary(library -> {
processLibrary(library, manager, deploymentIds);
return true;
});
if (!deploymentIds.isEmpty()) {
processDownload(module, deploymentIds, result);
}
} catch (IOException e) {
LOGGER.error(e.getLocalizedMessage(), e);
}
return result;
}
@Override
public void processImport(Module module) {
Project project = module.getProject();
File gradleFile = null;
for(VirtualFile virtualFile : ModuleRootManager.getInstance(module).getContentRoots()) {
File baseDir = VfsUtilCore.virtualToIoFile(virtualFile);
File file = new File(baseDir, "build.gradle");
if (file.exists()) {
gradleFile = file;
break;
}
}
if (gradleFile != null) {
ProjectImportProvider gradleProjectImportProvider = getGradleProjectImportProvider();
ProjectImportBuilder gradleProjectImportBuilder = gradleProjectImportProvider.getBuilder();
AddModuleWizard wizard = new AddModuleWizard(project, gradleFile.getPath(), new ProjectImportProvider[]{gradleProjectImportProvider});
if (wizard.getStepCount() == 0 || wizard.showAndGet()) {
gradleProjectImportBuilder.commit(project, (ModifiableModuleModel)null, (ModulesProvider)null);
}
}
}
@Nonnull
@Override
public Set<UsageDescriptor> getProjectUsages(@Nonnull Project project) {
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;
}
@Override
public void processImport(Module module) {
Project project = module.getProject();
VirtualFile pomFile = null;
VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();
for(VirtualFile contentRoot : contentRoots) {
VirtualFile child = contentRoot.findChild("pom.xml");
if (child != null) {
pomFile = child;
break;
}
}
if (pomFile != null) {
MavenProjectsManager mavenProjectsManager = MavenProjectsManager.getInstance(project);
mavenProjectsManager.addManagedFiles(Collections.singletonList(pomFile));
}
}
/**
* Returns the target/classes/$configFile and null otherwise.
*
* <p>
* Using this file instead of using src/main/resources/$configFile gives the
* capability to get the filtered value.
* </p>
*
* @return the target/classes/$configFile and null otherwise.
*/
private VirtualFile getConfigFile() {
if (configFile != null && configFile.exists()) {
return configFile;
}
if (javaProject.isLoaded()) {
VirtualFile[] sourceRoots = ModuleRootManager.getInstance(javaProject).getSourceRoots();
for (VirtualFile sourceRoot : sourceRoots) {
VirtualFile file = sourceRoot.findFileByRelativePath(configFileName);
if (file != null && file.exists()) {
return file;
}
}
return null;
}
return null;
}
@Nullable
private ListWithSelection<String> getLayers() {
VirtualFile file = getSelectedFile();
Project project = getProject();
Module moduleForFile = file == null ? null : ModuleUtilCore.findModuleForFile(file, project);
if (moduleForFile == null) {
return null;
}
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(moduleForFile);
Map<String, ModuleRootLayer> layers = moduleRootManager.getLayers();
if (layers.size() == 1) {
return null;
}
String currentLayerName = moduleRootManager.getCurrentLayerName();
return new ListWithSelection<>(layers.keySet(), currentLayerName);
}
/**
* Returns true if the project has a module for the "android" directory.
*/
public boolean hasAndroidModule(Project project) {
final VirtualFile androidDir = getAndroidDir();
if (androidDir == null) {
return false;
}
for (Module module : ModuleManager.getInstance(project).getModules()) {
for (VirtualFile contentRoot : ModuleRootManager.getInstance(module).getContentRoots()) {
if (contentRoot.equals(androidDir)) {
return true;
}
}
}
return false;
}
public boolean canUnmark(AnActionEvent e) {
Module module = e.getData(LangDataKeys.MODULE);
VirtualFile[] vFiles = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY);
if (module == null || vFiles == null) {
return false;
}
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
final ContentEntry[] contentEntries = moduleRootManager.getContentEntries();
for (VirtualFile vFile : vFiles) {
if (!vFile.isDirectory()) {
continue;
}
for (ContentEntry contentEntry : contentEntries) {
for (ContentFolder contentFolder : contentEntry.getFolders(ContentFolderScopes.all())) {
if (Comparing.equal(contentFolder.getFile(), vFile)) {
return true;
}
}
}
}
return false;
}
protected static void removeFlutterLibraryDependency(@NotNull Module module, @NotNull Library library) {
final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();
try {
boolean wasFound = false;
for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
if (orderEntry instanceof LibraryOrderEntry &&
LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)orderEntry).getLibraryLevel()) &&
StringUtil.equals(library.getName(), ((LibraryOrderEntry)orderEntry).getLibraryName())) {
wasFound = true;
modifiableModel.removeOrderEntry(orderEntry);
}
}
if (wasFound) {
ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(modifiableModel::commit));
}
}
finally {
if (!modifiableModel.isDisposed()) {
modifiableModel.dispose();
}
}
}
private static List<String> getLibrariesName(Project project) {
Module[] modules = ModuleManager.getInstance(project).getModules();
final List<String> libraryNames = new ArrayList<String>();
for (Module module : modules) {
ModuleRootManager.getInstance(module).orderEntries().forEachLibrary(new Processor<Library>() {
@Override
public boolean process(Library library) {
libraryNames.add(library.getName());
return true;
}
});
}
return libraryNames;
}
protected static void findFiles(final Module module, final List<PsiFile> files) {
final ModuleFileIndex idx = ModuleRootManager.getInstance(module).getFileIndex();
final VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots();
for (VirtualFile root : roots) {
idx.iterateContentUnderDirectory(root, new ContentIterator() {
public boolean processFile(final VirtualFile dir) {
if (dir.isDirectory()) {
final PsiDirectory psiDir = PsiManager.getInstance(module.getProject()).findDirectory(dir);
if (psiDir != null) {
findFiles(files, psiDir, false);
}
}
return true;
}
});
}
}
/**
* Attempt to locate a file in the module directories that may not be a direct source
* file (like the .hxml files). If the given file is absolute, then module (.iml) directory,
* source and classpaths will not be searched.
*
* @param module
* @param haxeProjectPath
* @return
*/
@Nullable
private VirtualFile locateModuleFile(Module module, String haxeProjectPath) {
// Try to find the file. If it's absolute, we either get it the first time or give up.
VirtualFile projectFile = HaxeFileUtil.locateFile(haxeProjectPath);
if ( ! HaxeFileUtil.isAbsolutePath(haxeProjectPath)) {
if (null == projectFile) {
ModuleRootManager rootMgr = ModuleRootManager.getInstance(module);
projectFile = HaxeFileUtil.locateFile(haxeProjectPath, rootMgr.getSourceRootUrls());
}
if (null == projectFile) {
projectFile = HaxeFileUtil.locateFile(haxeProjectPath, module.getModuleFilePath());
}
}
return projectFile;
}
@NotNull
public List<PubRoot> getRoots(Module module) {
final List<PubRoot> result = new ArrayList<>();
for (VirtualFile dir : ModuleRootManager.getInstance(module).getContentRoots()) {
PubRoot root = cache.get(dir);
if (root == null) {
cache.put(dir, PubRoot.forDirectory(dir));
root = cache.get(dir);
}
if (root != null) {
result.add(root);
}
}
return result;
}
@Nullable
public static VirtualFile findResourceFile(final String name, final Module inModule) {
final VirtualFile[] sourceRoots = ModuleRootManager.getInstance(inModule).getContentFolderFiles(ContentFolderScopes.productionAndTest());
final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(inModule.getProject()).getFileIndex();
for (final VirtualFile sourceRoot : sourceRoots) {
final String packagePrefix = fileIndex.getPackageNameByDirectory(sourceRoot);
final String prefix = packagePrefix == null || packagePrefix.isEmpty() ? null : packagePrefix.replace('.', '/') + "/";
final String relPath = prefix != null && name.startsWith(prefix) && name.length() > prefix.length() ? name.substring(prefix.length()) : name;
final String fullPath = sourceRoot.getPath() + "/" + relPath;
final VirtualFile fileByPath = LocalFileSystem.getInstance().findFileByPath(fullPath);
if (fileByPath != null) {
return fileByPath;
}
}
return null;
}
private Sdk getJdkToRunModule(Module module) {
final Sdk moduleSdk = ModuleRootManager.getInstance(module).getSdk();
if (moduleSdk == null) {
return null;
}
final Set<Sdk> sdksFromDependencies = new LinkedHashSet<>();
OrderEnumerator enumerator = OrderEnumerator.orderEntries(module).runtimeOnly().recursively();
enumerator = enumerator.productionOnly();
enumerator.forEachModule(module1 -> {
Sdk sdk = ModuleRootManager.getInstance(module1).getSdk();
if (sdk != null && sdk.getSdkType().equals(moduleSdk.getSdkType())) {
sdksFromDependencies.add(sdk);
}
return true;
});
return findLatestVersion(moduleSdk, sdksFromDependencies);
}
protected static void addFlutterLibraryDependency(@NotNull Module module, @NotNull 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()) &&
StringUtil.equals(library.getName(), ((LibraryOrderEntry)orderEntry).getLibraryName())) {
return; // dependency already exists
}
}
modifiableModel.addLibraryEntry(library);
ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(modifiableModel::commit));
}
finally {
if (!modifiableModel.isDisposed()) {
modifiableModel.dispose();
}
}
}
protected static void removeFlutterLibraryDependency(@NotNull Module module, @NotNull Library library) {
final ModifiableRootModel modifiableModel = ModuleRootManager.getInstance(module).getModifiableModel();
try {
boolean wasFound = false;
for (final OrderEntry orderEntry : modifiableModel.getOrderEntries()) {
if (orderEntry instanceof LibraryOrderEntry &&
LibraryTablesRegistrar.PROJECT_LEVEL.equals(((LibraryOrderEntry)orderEntry).getLibraryLevel()) &&
StringUtil.equals(library.getName(), ((LibraryOrderEntry)orderEntry).getLibraryName())) {
wasFound = true;
modifiableModel.removeOrderEntry(orderEntry);
}
}
if (wasFound) {
ApplicationManager.getApplication().invokeAndWait(() -> WriteAction.run(modifiableModel::commit));
}
}
finally {
if (!modifiableModel.isDisposed()) {
modifiableModel.dispose();
}
}
}
@Nonnull
private static List<Pair<VirtualFile, String>> getProjectRoots(GotoFileModel model) {
Set<VirtualFile> roots = new HashSet<>();
for (Module module : ModuleManager.getInstance(model.getProject()).getModules()) {
Collections.addAll(roots, ModuleRootManager.getInstance(module).getContentRoots());
for (OrderEntry entry : ModuleRootManager.getInstance(module).getOrderEntries()) {
if (entry instanceof OrderEntryWithTracking) {
Collections.addAll(roots, entry.getFiles(OrderRootType.CLASSES));
Collections.addAll(roots, entry.getFiles(OrderRootType.SOURCES));
}
}
}
return roots.stream().map(root -> {
VirtualFile top = model.getTopLevelRoot(root);
return top != null ? top : root;
}).distinct().map(r -> Pair.create(r, StringUtil.notNullize(model.getFullName(r)))).collect(Collectors.toList());
}
/**
* Add global protobuf library to given module. Visible for testing.
*/
public void addLibrary(Module module) {
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
ModifiableRootModel modifiableRootModel = moduleRootManager.getModifiableModel();
AtomicBoolean found = new AtomicBoolean(false);
OrderEnumerator.orderEntries(module).forEachLibrary(library1 -> {
if (LIB_NAME.equals(library1.getName())) {
found.set(true);
return false;
}
return true;
});
if (!found.get()) {
ApplicationManager.getApplication().runWriteAction(() -> {
modifiableRootModel.addLibraryEntry(globalLibrary);
modifiableRootModel.commit();
});
}
}
@Nullable
private PsiFile loadInMemoryDescriptorProto() {
if (inm == null) {
for (Module module : ModuleManager.getInstance(project).getModules()) {
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
VirtualFile[] allSourceRoots = moduleRootManager.orderEntries().getAllSourceRoots();
for (VirtualFile allSourceRoot : allSourceRoots) {
PsiDirectory directory = PsiManager.getInstance(project).findDirectory(allSourceRoot);
if (directory != null && directory.isValid()) {
String relPath = "google/protobuf/descriptor.proto";
VirtualFile file = directory.getVirtualFile().findFileByRelativePath(relPath);
if (file != null) {
PsiManager psiManager = PsiManager.getInstance(project);
PsiFile psiFile = psiManager.findFile(file);
if (psiFile instanceof ProtoPsiFileRoot) {
inm = psiFile;
return (ProtoPsiFileRoot) psiFile;
}
}
}
}
}
}
return inm;
}
@RequiredUIAccess
private void execute0(final NamespaceReference namespaceReference)
{
PsiDocumentManager.getInstance(myProject).commitAllDocuments();
WriteCommandAction.runWriteCommandAction(myProject, () ->
{
addUsing(namespaceReference.getNamespace());
String libraryName = namespaceReference.getLibraryName();
if(libraryName != null)
{
Module moduleForFile = ModuleUtilCore.findModuleForPsiElement(myFile);
if(moduleForFile != null)
{
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(moduleForFile);
final ModifiableRootModel modifiableModel = moduleRootManager.getModifiableModel();
modifiableModel.addOrderEntry(new DotNetLibraryOrderEntryImpl((ModuleRootLayerImpl) moduleRootManager.getCurrentLayer(), libraryName));
WriteAction.run(modifiableModel::commit);
}
}
});
}
@Nonnull
private static String calcDescription(Module module) {
String basePath = module.getProject().getBasePath();
if (basePath != null) {
String modulePath = module.getModuleDirPath();
if (modulePath == null) {
VirtualFile[] contentRoots = ModuleRootManager.getInstance(module).getContentRoots();
if (contentRoots.length == 1) {
modulePath = contentRoots[0].getPath();
}
}
if (modulePath != null) {
String relativePath = FileUtil.getRelativePath(basePath, modulePath, '/');
if (relativePath != null) {
return relativePath;
}
}
}
return "undefined";
}
public static boolean isRoboVmModule(Module module) {
// HACK! to identify if the module uses a robovm sdk
if (ModuleRootManager.getInstance(module).getSdk() != null) {
if (ModuleRootManager.getInstance(module).getSdk().getSdkType().getName().toLowerCase().contains("robovm")) {
return true;
}
}
// check if there's any RoboVM RT libs in the classpath
OrderEnumerator classes = ModuleRootManager.getInstance(module).orderEntries().recursively().withoutSdk().compileOnly();
for (String path : classes.getPathsList().getPathList()) {
if (isSdkLibrary(path)) {
return true;
}
}
// check if there's a robovm.xml file in the root of the module
for(VirtualFile file: ModuleRootManager.getInstance(module).getContentRoots()) {
if(file.findChild("robovm.xml") != null) {
return true;
}
}
return false;
}
@RequiredReadAction
public static boolean isPackageSupported(@Nonnull Project project) {
return CachedValuesManager.getManager(project).getCachedValue(project, () -> {
boolean result = false;
PsiPackageSupportProvider[] extensions = PsiPackageSupportProvider.EP_NAME.getExtensions();
ModuleManager moduleManager = ModuleManager.getInstance(project);
loop:
for (Module module : moduleManager.getModules()) {
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
for (ModuleExtension moduleExtension : rootManager.getExtensions()) {
for (PsiPackageSupportProvider extension : extensions) {
if (extension.isSupported(moduleExtension)) {
result = true;
break loop;
}
}
}
}
return CachedValueProvider.Result.create(result, ProjectRootManager.getInstance(project));
});
}
@Override
public String expand(DataContext dataContext) {
final Module module = dataContext.getData(LangDataKeys.MODULE);
if(module == null) {
return null;
}
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
return rootManager.getCurrentLayerName();
}
private void buildScopeModulesSet(Module module) {
myScopeModules.add(module);
final Module[] dependencies = ModuleRootManager.getInstance(module).getDependencies();
for (Module dependency : dependencies) {
if (!myScopeModules.contains(dependency)) { // may be in case of module circular dependencies
buildScopeModulesSet(dependency);
}
}
}
private static Integer computeHash(Module module) {
ModuleRootManager manager = ModuleRootManager.getInstance(module);
Set<String> files = manager.processOrder(new RootPolicy<Set<String>>() {
@Override
public Set<String> visitLibraryOrderEntry(@NotNull LibraryOrderEntry libraryOrderEntry, Set<String> value) {
if (!libraryOrderEntry.getLibraryName().equalsIgnoreCase(QuarkusConstants.QUARKUS_DEPLOYMENT_LIBRARY_NAME) && isQuarkusExtensionWithDeploymentArtifact(libraryOrderEntry.getLibrary())) {
for(VirtualFile file : libraryOrderEntry.getFiles(OrderRootType.CLASSES)) {
value.add(file.getPath());
}
}
return value;
}
}, new HashSet<>());
return files.isEmpty()?null:files.hashCode();
}
@NotNull
public ProcessingItem[] getProcessingItems(final CompileContext compileContext) {
final List<ProcessingItem> processingItems = new ArrayList<ProcessingItem>();
boolean doneSave = false;
Module[] affectedModules = ApplicationManager.getApplication().runReadAction(new Computable<Module[]>() {
public Module[] compute() {
return compileContext.getCompileScope().getAffectedModules();
}
});
for(Module module: affectedModules) {
Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (ModuleType.get(module) == CppModuleType.getInstance() ||
(sdk != null && sdk.getSdkType() == CppSdkType.getInstance())) {
processingItems.add(new MyProcessingItem(module));
if (!doneSave) {
BuildState.saveDocuments();
doneSave = true;
}
VirtualFile moduleFile = module.getModuleFile();
if (moduleFile == null) {
BuildState.saveAll();
}
}
}
return processingItems.toArray(new ProcessingItem[processingItems.size()]);
}
@Override
public void actionPerformed(AnActionEvent event) {
languageResolver = new KotlinResolver();
textResources = new TextResources();
Project project = event.getProject();
if (project == null) return;
DataContext dataContext = event.getDataContext();
final Module module = DataKeys.MODULE.getData(dataContext);
if (module == null) return;
final Navigatable navigatable = DataKeys.NAVIGATABLE.getData(dataContext);
if (navigatable != null) {
if (navigatable instanceof PsiDirectory) {
directory = (PsiDirectory) navigatable;
}
}
if (directory == null) {
ModuleRootManager root = ModuleRootManager.getInstance(module);
for (VirtualFile file : root.getSourceRoots()) {
directory = PsiManager.getInstance(project).findDirectory(file);
}
}
JSONEditDialog dialog = new JSONEditDialog(this, textResources);
dialog.addComponentListener(new ComponentAdapter() {
public void componentMoved(ComponentEvent e) {
lastDialogLocation = dialog.getLocation();
}
});
dialog.setSize(640, 480);
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
}
private Optional<VirtualFile> getWebModule(@NotNull Module module) {
VirtualFile[] sourceRoots = ModuleRootManager.getInstance(module).getSourceRoots(false);
Optional<VirtualFile> webmodule = Stream.of(sourceRoots).map(VirtualFile::getParent).distinct().flatMap(f ->
Stream.of(f.getChildren()).filter(c -> {
Path path = Paths.get(c.getCanonicalPath(), "WEB-INF");
return path.toFile().exists();
})).distinct().findFirst();
return webmodule;
}