Java Code Examples for com.intellij.openapi.module.ModuleUtil#findModuleForFile()
The following examples show how to use
com.intellij.openapi.module.ModuleUtil#findModuleForFile() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PsiPackageManagerImpl.java From consulo with Apache License 2.0 | 6 votes |
@Nullable private PsiPackage createPackageFromProviders(@Nonnull VirtualFile virtualFile, @Nonnull Class<? extends ModuleExtension> extensionClass, @Nonnull String qualifiedName) { final Module moduleForFile = ModuleUtil.findModuleForFile(virtualFile, myProject); if (moduleForFile == null) { return null; } ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(moduleForFile); final ModuleExtension extension = moduleRootManager.getExtension(extensionClass); if (extension == null) { return null; } for (PsiPackageSupportProvider p : PsiPackageSupportProvider.EP_NAME.getExtensionList()) { if (p.isSupported(extension) && p.acceptVirtualFile(moduleForFile, virtualFile)) { return p.createPackage(myPsiManager, this, extensionClass, qualifiedName); } } return null; }
Example 2
Source File: TestLaunchState.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Nullable @Override protected ConsoleView createConsole(@NotNull Executor executor) throws ExecutionException { if (!testConsoleEnabled) { return super.createConsole(executor); } // Create a console showing a test tree. final Project project = getEnvironment().getProject(); final DartUrlResolver resolver = DartUrlResolver.getInstance(project, testFileOrDir); final ConsoleProps props = ConsoleProps.forPub(config, executor, resolver); final BaseTestsOutputConsoleView console = SMTestRunnerConnectionUtil.createConsole(ConsoleProps.pubFrameworkName, props); final Module module = ModuleUtil.findModuleForFile(testFileOrDir, project); console.addMessageFilter(new DartConsoleFilter(project, getTestFileOrDir())); final String baseDir = getBaseDir(); if (baseDir != null) { console.addMessageFilter(new DartRelativePathsConsoleFilter(project, baseDir)); } console.addMessageFilter(new UrlFilter()); return console; }
Example 3
Source File: LogicalRootsManagerImpl.java From consulo with Apache License 2.0 | 6 votes |
@Override @Nullable public LogicalRoot findLogicalRoot(@Nonnull final VirtualFile file) { final Module module = ModuleUtil.findModuleForFile(file, myProject); if (module == null) return null; LogicalRoot result = null; final List<LogicalRoot> list = getLogicalRoots(module); for (final LogicalRoot root : list) { final VirtualFile rootFile = root.getVirtualFile(); if (rootFile != null && VfsUtil.isAncestor(rootFile, file, false)) { result = root; break; } } return result; }
Example 4
Source File: TestLaunchState.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Nullable @Override protected ConsoleView createConsole(@NotNull Executor executor) throws ExecutionException { if (!testConsoleEnabled) { return super.createConsole(executor); } // Create a console showing a test tree. final Project project = getEnvironment().getProject(); final DartUrlResolver resolver = DartUrlResolver.getInstance(project, testFileOrDir); final ConsoleProps props = ConsoleProps.forPub(config, executor, resolver); final BaseTestsOutputConsoleView console = SMTestRunnerConnectionUtil.createConsole(ConsoleProps.pubFrameworkName, props); final Module module = ModuleUtil.findModuleForFile(testFileOrDir, project); console.addMessageFilter(new DartConsoleFilter(project, getTestFileOrDir())); final String baseDir = getBaseDir(); if (baseDir != null) { console.addMessageFilter(new DartRelativePathsConsoleFilter(project, baseDir)); } console.addMessageFilter(new UrlFilter()); return console; }
Example 5
Source File: HaxeCompilerCompletionContributor.java From intellij-haxe with Apache License 2.0 | 5 votes |
private boolean useCompilerCompletion(PsiFile file) { VirtualFile vFile = file.getVirtualFile(); if (null != vFile) { // Can't use in-memory file. TODO: Allow in-memory file for compiler completion. Module module = ModuleUtil.findModuleForFile(vFile, file.getProject()); HaxeSdkAdditionalDataBase sdkData = HaxeSdkUtil.getSdkData(module); if (null != sdkData) { return sdkData.getUseCompilerCompletionFlag(); } } return false; }
Example 6
Source File: ModuleRule.java From consulo with Apache License 2.0 | 5 votes |
@Override public Module getData(@Nonnull DataProvider dataProvider) { Module moduleContext = dataProvider.getDataUnchecked(LangDataKeys.MODULE_CONTEXT); if (moduleContext != null) { return moduleContext; } Project project = dataProvider.getDataUnchecked(CommonDataKeys.PROJECT); if (project == null) { PsiElement element = dataProvider.getDataUnchecked(LangDataKeys.PSI_ELEMENT); if (element == null || !element.isValid()) return null; project = element.getProject(); } VirtualFile virtualFile = dataProvider.getDataUnchecked(PlatformDataKeys.VIRTUAL_FILE); if (virtualFile == null) { GetDataRule<VirtualFile> dataRule = ((BaseDataManager)DataManager.getInstance()).getDataRule(PlatformDataKeys.VIRTUAL_FILE); if (dataRule != null) { virtualFile = dataRule.getData(dataProvider); } } if (virtualFile == null) { return null; } return ModuleUtil.findModuleForFile(virtualFile, project); }
Example 7
Source File: AbstractCreateElementActionBase.java From attic-polygene-java with Apache License 2.0 | 5 votes |
@NotNull protected final PsiElement[] invokeDialog( Project project, PsiDirectory directory ) { Module module = ModuleUtil.findModuleForFile( directory.getVirtualFile(), project ); if( module == null ) { return PsiElement.EMPTY_ARRAY; } MyInputValidator validator = doInvokeDialog( project, directory ); return validator.getCreatedElements(); }
Example 8
Source File: GraphQLConfigManager.java From js-graphql-intellij-plugin with MIT License | 5 votes |
@Nullable public Set<VirtualFile> getContentRoots(VirtualFile virtualFile) { final Module module = ModuleUtil.findModuleForFile(virtualFile, myProject); if (module != null) { return Sets.newHashSet(ModuleRootManager.getInstance(module).getContentRoots()); } else { return Sets.newHashSet(myProject.getBaseDir()); } }
Example 9
Source File: OneProjectItemCompileScope.java From consulo with Apache License 2.0 | 5 votes |
@Nonnull public Module[] getAffectedModules() { final Module module = ModuleUtil.findModuleForFile(myFile, myProject); if (module == null) { LOG.error("Module is null for file " + myFile.getPresentableUrl()); return Module.EMPTY_ARRAY; } return new Module[] {module}; }
Example 10
Source File: ExtractSuperClassUtil.java From intellij-haxe with Apache License 2.0 | 5 votes |
public static void checkSuperAccessible(PsiDirectory targetDirectory, MultiMap<PsiElement, String> conflicts, final PsiClass subclass) { final VirtualFile virtualFile = subclass.getContainingFile().getVirtualFile(); if (virtualFile != null) { final boolean inTestSourceContent = ProjectRootManager.getInstance(subclass.getProject()).getFileIndex().isInTestSourceContent(virtualFile); final Module module = ModuleUtil.findModuleForFile(virtualFile, subclass.getProject()); if (targetDirectory != null && module != null && !GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, inTestSourceContent).contains(targetDirectory.getVirtualFile())) { conflicts.putValue(subclass, "Superclass won't be accessible in subclass"); } } }
Example 11
Source File: ORVirtualFileListener.java From reasonml-idea-plugin with MIT License | 5 votes |
private static void handleBsConfigContentChange(VirtualFile bsConfigFile) { for (Project project : ProjectManager.getInstance().getOpenProjects()) { Module module = ModuleUtil.findModuleForFile(bsConfigFile, project); if (module != null) { ServiceManager.getService(project, InsightManager.class).downloadRincewindIfNeeded(bsConfigFile); OREditorTracker.getInstance(project).updateQueues(); } } }
Example 12
Source File: ProjectUtil.java From consulo with Apache License 2.0 | 4 votes |
@Nonnull public static String calcRelativeToProjectPath(@Nonnull final VirtualFile file, @Nullable final Project project, final boolean includeFilePath, final boolean includeUniqueFilePath, final boolean keepModuleAlwaysOnTheLeft) { if (file instanceof VirtualFilePathWrapper) { return includeFilePath ? ((VirtualFilePathWrapper)file).getPresentablePath() : file.getName(); } String url; if (includeFilePath) { url = file.getPresentableUrl(); } else if (includeUniqueFilePath) { url = UniqueVFilePathBuilder.getInstance().getUniqueVirtualFilePath(project, file); } else { url = file.getName(); } if (project == null) { return url; } else { final VirtualFile baseDir = project.getBaseDir(); if (baseDir != null && includeFilePath) { //noinspection ConstantConditions final String projectHomeUrl = baseDir.getPresentableUrl(); if (url.startsWith(projectHomeUrl)) { url = "..." + url.substring(projectHomeUrl.length()); } } if (SystemInfo.isMac && file.getFileSystem() instanceof ArchiveFileSystem) { final VirtualFile fileForJar = ((ArchiveFileSystem)file.getFileSystem()).getLocalVirtualFileFor(file); if (fileForJar != null) { final OrderEntry libraryEntry = LibraryUtil.findLibraryEntry(file, project); if (libraryEntry != null) { if (libraryEntry instanceof ModuleExtensionWithSdkOrderEntry) { url = url + " - [" + ((ModuleExtensionWithSdkOrderEntry)libraryEntry).getSdkName() + "]"; } else { url = url + " - [" + libraryEntry.getPresentableName() + "]"; } } else { url = url + " - [" + fileForJar.getName() + "]"; } } } final Module module = ModuleUtil.findModuleForFile(file, project); if (module == null) return url; return !keepModuleAlwaysOnTheLeft && SystemInfo.isMac ? url + " - [" + module.getName() + "]" : "[" + module.getName() + "] - " + url; } }
Example 13
Source File: FlutterSaveActionsManager.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 4 votes |
private void handleBeforeDocumentSaving(@NotNull Document document) { final FlutterSettings settings = FlutterSettings.getInstance(); if (!settings.isFormatCodeOnSave()) { return; } if (!myProject.isInitialized() || myProject.isDisposed()) { return; } final VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file == null) { return; } if (!FlutterUtils.isDartFile(file)) { return; } final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); if (psiFile == null || !psiFile.isValid()) { return; } final Module module = ModuleUtil.findModuleForFile(file, myProject); if (module == null) { return; } if (!DartPlugin.isDartSdkEnabled(module)) { return; } // check for errors if (PsiErrorElementUtil.hasErrors(myProject, psiFile.getVirtualFile())) { return; } if (DartAnalysisServerService.getInstance(myProject).serverReadyForRequest()) { if (settings.isOrganizeImportsOnSave()) { performOrganizeThenFormat(document, file); } else { performFormat(document, file, false); } } }
Example 14
Source File: PantsCompileActionGroup.java From intellij-pants-plugin with Apache License 2.0 | 4 votes |
@NotNull @Override public AnAction[] getChildren(@Nullable AnActionEvent event) { // Deletes existing make and compile options. ActionManager actionManager = ActionManager.getInstance(); // TODO: don't remove these actions or put on our own unless we're in a // pants project, so we don't clobber these actions in a non-pants project DefaultActionGroup actionGroup = (DefaultActionGroup) actionManager.getAction(PantsConstants.ACTION_COMPILE_GROUP_ID); actionGroup.remove(actionManager.getAction(IdeActions.ACTION_MAKE_MODULE)); actionGroup.remove(actionManager.getAction(IdeActions.ACTION_COMPILE)); final AnAction[] emptyAction = new AnAction[0]; if (event == null) { return emptyAction; } Project project = event.getProject(); Optional<VirtualFile> eventFile = PantsUtil.getFileForEvent(event); // TODO: signal if no project found? if (project == null || !eventFile.isPresent()) { return emptyAction; } VirtualFile file = eventFile.get(); List<AnAction> actions = new LinkedList<>(); Module module = ModuleUtil.findModuleForFile(file, project); if (module == null) { return emptyAction; } List<String> targetAddresses = PantsUtil.getNonGenTargetAddresses(module); // TODO: signal if no addresses found? if (targetAddresses.isEmpty()) { return emptyAction; } actions.add(new PantsLintTargetAction(targetAddresses)); // Adds compile all option for modules with multiple targets. if (targetAddresses.size() > 1) { actions.add(new PantsCompileAllTargetsInModuleAction(Optional.of(module))); } targetAddresses.forEach(target -> actions.add(new PantsCompileTargetAction(target))); return actions.toArray(emptyAction); }
Example 15
Source File: ModuleHelper.java From Intellij-Plugin with Apache License 2.0 | 4 votes |
public Module getModule(VirtualFile file, Project project) { return ModuleUtil.findModuleForFile(file, project); }
Example 16
Source File: FlutterSaveActionsManager.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 4 votes |
private void handleBeforeDocumentSaving(@NotNull Document document) { final FlutterSettings settings = FlutterSettings.getInstance(); if (!settings.isFormatCodeOnSave()) { return; } if (!myProject.isInitialized() || myProject.isDisposed()) { return; } final VirtualFile file = FileDocumentManager.getInstance().getFile(document); if (file == null) { return; } if (!FlutterUtils.isDartFile(file)) { return; } final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(document); if (psiFile == null || !psiFile.isValid()) { return; } final Module module = ModuleUtil.findModuleForFile(file, myProject); if (module == null) { return; } if (!DartPlugin.isDartSdkEnabled(module)) { return; } // check for errors if (PsiErrorElementUtil.hasErrors(myProject, psiFile.getVirtualFile())) { return; } if (DartAnalysisServerService.getInstance(myProject).serverReadyForRequest()) { if (settings.isOrganizeImportsOnSave()) { performOrganizeThenFormat(document, file); } else { performFormat(document, file, false); } } }
Example 17
Source File: HaxeCompilerServices.java From intellij-haxe with Apache License 2.0 | 4 votes |
@NotNull public List<HaxeCompilerCompletionItem> getPossibleCompletions(@NotNull PsiFile file, @NotNull PsiElement element, @NotNull Editor editor) { HaxeDebugTimeLog timeLog = HaxeDebugTimeLog.startNew("HaxeCompilerCompletionContributor", HaxeDebugTimeLog.Since.StartAndPrevious); List<HaxeCompilerCompletionItem> completions = HaxeCompilerCompletionItem.EMPTY_LIST; try { Project project = file.getProject(); VirtualFile vfile = file.getVirtualFile(); VirtualFile compileRoot = HaxeCompilerUtil.findCompileRoot(file); if (null == vfile || null == compileRoot) { // Can't run a completion on an in-memory file (at least for now). // TODO: Allow completion on in-memory files for 3.4 compilers. return completions; } Module moduleForFile = ModuleUtil.findModuleForFile(vfile, project); ArrayList<String> commandLineArguments = new ArrayList<String>(); //Make sure module is Haxe Module if (moduleForFile != null && ModuleUtil.getModuleType(moduleForFile).equals(HaxeModuleType.getInstance())) { //Get module settings HaxeModuleSettings moduleSettings = HaxeModuleSettings.getInstance(moduleForFile); HaxeConfiguration buildConfig = moduleSettings.getBuildConfiguration(); VirtualFile projectFile = null; switch (buildConfig) { case HXML: projectFile = verifyProjectFile(moduleForFile, "HXML", moduleSettings.getHxmlPath(), myErrorNotifier); if (null == projectFile) { break; } commandLineArguments.add(HaxeHelpUtil.getHaxePath(moduleForFile)); commandLineArguments.add(projectFile.getPath()); completions = collectCompletionsFromCompiler(file, element, editor, commandLineArguments, timeLog); break; case NMML: projectFile = verifyProjectFile(moduleForFile, "NMML", moduleSettings.getNmmlPath(), myErrorNotifier); if (null == projectFile) { break; } formatAndAddCompilerArguments(commandLineArguments, moduleSettings.getNmeFlags()); completions = collectCompletionsFromNME(file, element, editor, commandLineArguments, timeLog); break; case OPENFL: //projectFile = verifyProjectFile(moduleForFile, "OpenFL", moduleSettings.getOpenFLPath(), myErrorNotifier); //if (null == projectFile) { // break; //} List<String> compilerArgsFromProjectFile = getLimeProjectConfiguration(moduleForFile, timeLog); commandLineArguments.add(HaxeHelpUtil.getHaxePath(moduleForFile)); formatAndAddCompilerArguments(commandLineArguments, compilerArgsFromProjectFile); completions = collectCompletionsFromCompiler(file, element, editor, commandLineArguments, timeLog); break; case CUSTOM: commandLineArguments.add(HaxeHelpUtil.getHaxePath(moduleForFile)); formatAndAddCompilerArguments(commandLineArguments, moduleSettings.getArguments()); completions = collectCompletionsFromCompiler(file, element, editor, commandLineArguments, timeLog); break; } } } finally { timeLog.stamp("Finished"); timeLog.print(); } return completions; }
Example 18
Source File: HaxeCompilerServices.java From intellij-haxe with Apache License 2.0 | 4 votes |
@NotNull private List<HaxeCompilerCompletionItem> collectCompletionsFromCompiler(@NotNull PsiFile file, @NotNull PsiElement element, @NotNull Editor editor, ArrayList<String> commandLineArguments, HaxeDebugTimeLog timeLog) { // There is a problem here in that the current buffer may not have been saved. // If that is the case, then the position is also incorrect, and the compiler // doesn't have access to the correct sources. If the haxe compiler is version 3.4 or // later, then it has the -D display-stdin parameter available and we can pump the // unsaved buffer through to the compiler. (Though that does nothing for completion // from related but also unsaved buffers.) Doing so will also require the compiler // server (if used) to be started with the "--wait stdin" parameter. if (null == file) { // TODO: Handle in-memory files for Haxe 3.4. advertiseError("Error: Compiler completion requested for in-memory-only file."); // TODO: Externalize string. return HaxeCompilerCompletionItem.EMPTY_LIST; } Project project = file.getProject(); Module moduleForFile = ModuleUtil.findModuleForFile(file.getVirtualFile(), project); int offset = recalculateFileOffset(file, element, editor); // TODO: Add libraries that could be referenced. // Source roots need to be in the classpath, too. for (VirtualFile root : ModuleRootManager.getInstance(moduleForFile).getSourceRoots()) { commandLineArguments.add("-cp"); commandLineArguments.add(root.getPath()); } // Add all of the definitions, so that the compiler can see the code we are dealing with. HaxeProjectSettings settings = HaxeProjectSettings.getInstance(project); for (String define : settings.getUserCompilerDefinitions()) { commandLineArguments.add("-D"); commandLineArguments.add(define); } // Tell the compiler we want field completion, adding the type (var or method) commandLineArguments.add("-D"); commandLineArguments.add("display-details"); commandLineArguments.add("--display"); commandLineArguments.add(file.getVirtualFile().getPath() + "@" + Integer.toString(offset)); timeLog.stamp("Calling compiler"); List<String> stderr = new ArrayList<String>(); List<String> stdout = new ArrayList<String>(); int status = HaxeCompilerUtil.runInterruptibleCompileProcess(commandLineArguments, false, HaxeCompilerUtil.findCompileRoot(file), HaxeSdkUtilBase.getSdkData(moduleForFile), stdout, stderr, timeLog); timeLog.stamp("Compiler finished. Output found on " + (stdout.isEmpty() ? "" : "stdout ") + (stderr.isEmpty() ? "" : "stderr")); // LOG.debug("Compiler finished. Output found on " + (stdout.isEmpty() ? "" : "stdout ") + (stderr.isEmpty() ? "" : "stderr")); if (0 != status) { return handleCompilerError(project, stderr); } return parseCompletionFromXml(project, stderr); }
Example 19
Source File: ProjectViewProjectNode.java From consulo with Apache License 2.0 | 4 votes |
@RequiredReadAction @Override @Nonnull public Collection<AbstractTreeNode> getChildren() { List<VirtualFile> topLevelContentRoots = BaseProjectViewDirectoryHelper.getTopLevelRoots(myProject); Set<Module> modules = new LinkedHashSet<>(topLevelContentRoots.size()); Project project = getProject(); for (VirtualFile root : topLevelContentRoots) { final Module module = ModuleUtil.findModuleForFile(root, project); if (module != null) { // Some people exclude module's content roots... modules.add(module); } } ArrayList<AbstractTreeNode> nodes = new ArrayList<>(); final PsiManager psiManager = PsiManager.getInstance(project); nodes.addAll(modulesAndGroups(modules.toArray(new Module[modules.size()]))); final VirtualFile baseDir = project.getBaseDir(); if (baseDir == null) return nodes; final VirtualFile[] files = baseDir.getChildren(); for (VirtualFile file : files) { if (ModuleUtil.findModuleForFile(file, project) == null) { if (!file.isDirectory()) { PsiFile psiFile = psiManager.findFile(file); if(psiFile != null) { nodes.add(new PsiFileNode(project, psiFile, getSettings())); } } } } if (getSettings().isShowLibraryContents()) { nodes.add(new ExternalLibrariesNode(project, getSettings())); } return nodes; }
Example 20
Source File: NewFileAction.java From crud-intellij-plugin with Apache License 2.0 | 4 votes |
@Override public void actionPerformed(AnActionEvent e) { Project project = e.getProject(); VirtualFile virtualFile = e.getData(DataKeys.VIRTUAL_FILE); if (!virtualFile.isDirectory()) { virtualFile = virtualFile.getParent(); } Module module = ModuleUtil.findModuleForFile(virtualFile, project); String moduleRootPath = ModuleRootManager.getInstance(module).getContentRoots()[0].getPath(); String actionDir = virtualFile.getPath(); String str = StringUtils.substringAfter(actionDir, moduleRootPath + "/src/main/java/"); String basePackage = StringUtils.replace(str, "/", "."); SelectionContext.clearAllSet(); SelectionContext.setPackage(basePackage); if (StringUtils.isNotBlank(basePackage)) { basePackage += "."; } SelectionContext.setControllerPackage(basePackage + "controller"); SelectionContext.setServicePackage(basePackage + "service"); SelectionContext.setDaoPackage(basePackage + "dao"); SelectionContext.setModelPackage(basePackage + "model"); SelectionContext.setMapperDir(moduleRootPath + "/src/main/resources/mapper"); CrudActionDialog dialog = new CrudActionDialog(project, module); if (!dialog.showAndGet()) { return; } DumbService.getInstance(project).runWhenSmart((DumbAwareRunnable) () -> new WriteCommandAction(project) { @Override protected void run(@NotNull Result result) { Selection selection = SelectionContext.copyToSelection(); SelectionContext.clearAllSet(); try { PsiFileUtils.createCrud(project, selection, moduleRootPath); } catch (Exception ex) { ex.printStackTrace(); } //优化生成的所有Java类 CrudUtils.doOptimize(project); } }.execute()); }