Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compact middle packages in project tree #3992

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import com.alecstrong.sql.psi.core.SqlFileBase
import com.alecstrong.sql.psi.core.SqlParserUtil
import com.intellij.icons.AllIcons
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.projectView.ProjectView
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
Expand All @@ -50,9 +51,11 @@ import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.PsiDocumentManagerImpl
import org.jetbrains.kotlin.idea.util.projectStructure.getModule
import timber.log.Timber
import java.io.PrintStream
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.reflect.jvm.jvmName

class ProjectService(val project: Project) : SqlDelightProjectService, Disposable {
Expand All @@ -71,6 +74,7 @@ class ProjectService(val project: Project) : SqlDelightProjectService, Disposabl
}

if (!ApplicationManager.getApplication().isUnitTestMode) {
val currentProjectViewPane = ProjectView.getInstance(project).currentProjectViewPane
project.messageBus.connect()
.subscribe(
VirtualFileManager.VFS_CHANGES,
Expand All @@ -85,12 +89,36 @@ class ProjectService(val project: Project) : SqlDelightProjectService, Disposabl
event.file?.let { generateDatabaseOnSync(it) }
}
}
events.mapNotNull { it.file }
.filter { it.findConfiguredFileIndex() != null }
.forEach { virtualFile ->
val index = requireNotNull(virtualFile.findConfiguredFileIndex())
val filePath = try {
virtualFile.toNioPath().toAbsolutePath()
} catch (exception: UnsupportedOperationException) {
Paths.get("").toAbsolutePath()
}
val sourceFolder = index.sourceFolders(true)
.flatten()
.firstOrNull { sourceFolder ->
filePath.startsWith(sourceFolder.folder.toPath())
}
if (sourceFolder != null) {
currentProjectViewPane?.updateFromRoot(true)
}
}
}
},
)
}
}

private fun VirtualFile.findConfiguredFileIndex(): SqlDelightFileIndex? {
val module = getModule(project) ?: return null
val fileIndex = SqlDelightFileIndex.getInstance(module)
return fileIndex.takeIf { it.isConfigured }
}

override fun dispose() {
Timber.uproot(loggingTree)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
package app.cash.sqldelight.intellij

import app.cash.sqldelight.core.SqlDelightFileIndex
import com.intellij.icons.AllIcons
import com.intellij.ide.DeleteProvider
import com.intellij.ide.projectView.PresentationData
import com.intellij.ide.projectView.TreeStructureProvider
import com.intellij.ide.projectView.ViewSettings
import com.intellij.ide.projectView.impl.ProjectRootsUtil
import com.intellij.ide.projectView.impl.ProjectTreeStructure
import com.intellij.ide.projectView.impl.nodes.ProjectViewDirectoryHelper
import com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode
import com.intellij.ide.util.DeleteHandler
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.konan.file.File

internal class SqlDelightTreeStructureProvider(
private val project: Project,
) : TreeStructureProvider {
override fun modify(
parent: AbstractTreeNode<*>,
children: MutableCollection<AbstractTreeNode<*>>,
settings: ViewSettings?,
): MutableCollection<AbstractTreeNode<*>> {
if (settings !is ProjectTreeStructure || !settings.isHideEmptyMiddlePackages) {
return children
}
if (parent !is PsiDirectoryNode || ProjectRootsUtil.isSourceRoot(parent.value)) {
return children
}

val module = ModuleUtil.findModuleForPsiElement(parent.value) ?: return children
val fileIndex = SqlDelightFileIndex.getInstance(module)
if (!fileIndex.isConfigured) {
return children
}
val packagePrefix = fileIndex.packageName.substringBefore(".")
if (packagePrefix.isEmpty()) {
return children
}
val srcPaths = fileIndex.sourceFolders(true)
.flatMap { sourceFolders -> sourceFolders.map { it.folder.toPath() } }

val path = try {
parent.value.virtualFile.toNioPath().toAbsolutePath()
} catch (exception: UnsupportedOperationException) {
return children
}
if (srcPaths.none { path.startsWith(it) }) {
return children
}
val srcDirName = parent.value.name

val result = mutableListOf<AbstractTreeNode<*>>()
val psiManager = PsiManager.getInstance(project)
for (child in children) {
if (child is PsiDirectoryNode && child.value.name == packagePrefix) {
val leafDir = findLeafDirectory(child)
val psiFile = psiManager.findDirectory(leafDir) ?: return children
result.add(SqlDelightPackageNode(srcDirName, project, psiFile, settings))
} else {
result.add(child)
}
}
return result
}

private fun findLeafDirectory(node: PsiDirectoryNode): VirtualFile {
var virtualFile = node.value.virtualFile
VfsUtilCore.iterateChildrenRecursively(virtualFile, VirtualFileFilter.ALL) { file ->
virtualFile = file
val filteredChildren = file.children.filter { !it.name.startsWith(".") }
if (filteredChildren.size == 1) {
filteredChildren.first().isDirectory
} else {
false
}
}
return virtualFile
}

override fun getData(selected: MutableCollection<AbstractTreeNode<*>>, dataId: String): Any? {
if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.`is`(dataId)) {
if (selected.any { it is SqlDelightPackageNode }) {
return SqlDelightDeleteProvider(selected)
}
}
return null
}

private class SqlDelightDeleteProvider(
selected: Collection<AbstractTreeNode<*>>,
) : DeleteProvider {

private val elements = collectPsiElements(selected)
override fun deleteElement(dataContext: DataContext) {
val project = CommonDataKeys.PROJECT.getData(dataContext)
DeleteHandler.deletePsiElement(elements, project)
}

override fun canDeleteElement(dataContext: DataContext): Boolean {
return DeleteHandler.shouldEnableDeleteAction(elements)
}

private fun collectPsiElements(selected: Collection<AbstractTreeNode<*>>): Array<PsiElement> {
val result = mutableSetOf<PsiElement>()
for (node in selected) {
if (node is SqlDelightPackageNode) {
result.addAll(node.children.map { it.value as PsiElement })
generateSequence(node.value) { it.parent }
.takeWhile { it.name != node.srcDirName }
.forEach { result.add(it) }
} else if (node.value is PsiElement) {
result.add(node.value as PsiElement)
}
}
return result.toTypedArray()
}
}

private class SqlDelightPackageNode(
val srcDirName: String,
project: Project,
value: PsiDirectory,
viewSettings: ViewSettings?,
) : PsiDirectoryNode(project, value, viewSettings) {

override fun updateImpl(data: PresentationData) {
data.presentableText = value.virtualFile.path.substringAfterLast(srcDirName)
.replace(File.separator, ".")
.removePrefix(".")
data.locationString =
ProjectViewDirectoryHelper.getInstance(project).getLocationString(value, false, false)
data.setIcon(AllIcons.Nodes.Package)
}
}
}
3 changes: 3 additions & 0 deletions sqldelight-idea-plugin/src/main/resources/META-INF/plugin.xml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@
<stubIndex implementation="com.alecstrong.sql.psi.core.psi.SchemaContributorIndexImpl"/>
<stubElementTypeHolder class="com.alecstrong.sql.psi.core.psi.SqlTypes"/>

<treeStructureProvider
implementation="app.cash.sqldelight.intellij.SqlDelightTreeStructureProvider"/>

<annotator language="SqlDelight"
implementationClass="com.alecstrong.sql.psi.core.SqlAnnotator"/>
<annotator language="SqlDelight"
Expand Down