PsiDirectory (Project project, String packageName, @Nullable PsiDirectory baseDir) { final PsiManager psiManager = PsiManager.getInstance(project); final PackageWrapper packageWrapper = new PackageWrapper(psiManager, packageName); final PsiPackage aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName); PsiDirectory directory; PsiDirectory[] directories = aPackage != null ? aPackage.getDirectories() : null; final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex(); final VirtualFile baseDirVirtualFile = baseDir != null ? baseDir.getVirtualFile() : null; final VirtualFile baseSourceRoot = baseDirVirtualFile != null ? fileIndex.getSourceRootForFile(baseDirVirtualFile) : null; if (directories != null && directories.length == 1 && baseSourceRoot != null && baseSourceRoot.equals(fileIndex.getSourceRootForFile(directories[0].getVirtualFile()))) { directory = directories[0]; } else { final List<VirtualFile> contentSourceRoots = JavaProjectRootsUtil.getSuitableDestinationSourceRoots(project); if (contentSourceRoots.size() == 1 && baseSourceRoot != null && baseSourceRoot.equals(contentSourceRoots.get(0))) { directory = WriteAction.compute(() -> CommonJavaRefactoringUtil.createPackageDirectoryInSourceRoot(packageWrapper, contentSourceRoots.get(0))); } else { final VirtualFile sourceRootForFile = chooseSourceRoot(packageWrapper, contentSourceRoots, baseDir); if (sourceRootForFile == null) return null; directory = WriteAction.compute( () -> new AutocreatingSingleSourceRootMoveDestination(packageWrapper, sourceRootForFile).getTargetDirectory((PsiDirectory)null)); } } return directory; }