Skip to content

Commit

Permalink
Compact middle packages in project tree
Browse files Browse the repository at this point in the history
  • Loading branch information
aperfilyev committed Mar 23, 2023
1 parent badc4ba commit 27cbe39
Show file tree
Hide file tree
Showing 5 changed files with 203 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ interface SqlDelightFileIndex {
*/
fun sourceFolders(file: SqlDelightFile, includeDependencies: Boolean = true): Collection<PsiDirectory>

/**
* @return The source roots of sqldelight files.
*/
fun sourceFolders(includeDependencies: Boolean): List<List<SqlDelightSourceFolder>> = emptyList()

companion object {
fun getInstance(module: Module) = SqlDelightProjectService.getInstance(module.project).fileIndex(module)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package app.cash.sqldelight.intellij
import app.cash.sqldelight.core.SqlDelightCompilationUnit
import app.cash.sqldelight.core.SqlDelightDatabaseProperties
import app.cash.sqldelight.core.SqlDelightFileIndex
import app.cash.sqldelight.core.SqlDelightSourceFolder
import app.cash.sqldelight.core.lang.SqlDelightFile
import app.cash.sqldelight.intellij.util.isAncestorOf
import com.intellij.openapi.vfs.LocalFileSystem
Expand Down Expand Up @@ -76,22 +77,20 @@ class FileIndex(
file: VirtualFile,
includeDependencies: Boolean,
): Collection<VirtualFile> {
return properties.compilationUnits.map {
it.sourceFolders
.filter { includeDependencies || !it.dependency }
.mapNotNull { sourceFolder -> sourceFolder.folder.localVirtualFile() }
}.fold(emptySet()) { currentSources: Collection<VirtualFile>, sourceSet ->
if (sourceSet.any { it.isAncestorOf(file) }) {
// File is in this source set.
if (currentSources.isEmpty()) {
return@fold sourceSet
} else {
// File also in another source set! The files available sources is the intersection.
return@fold currentSources.intersect(sourceSet)
return sourceFolders(includeDependencies)
.map { sourceFolders -> sourceFolders.mapNotNull { sourceFolder -> sourceFolder.folder.localVirtualFile() } }
.fold(emptySet()) { currentSources: Collection<VirtualFile>, sourceSet ->
if (sourceSet.any { it.isAncestorOf(file) }) {
// File is in this source set.
if (currentSources.isEmpty()) {
return@fold sourceSet
} else {
// File also in another source set! The files available sources is the intersection.
return@fold currentSources.intersect(sourceSet)
}
}
return@fold currentSources
}
return@fold currentSources
}
}

override fun sourceFolders(
Expand All @@ -102,6 +101,12 @@ class FileIndex(
.map { PsiManager.getInstance(file.project).findDirectory(it)!! }
}

override fun sourceFolders(includeDependencies: Boolean): List<List<SqlDelightSourceFolder>> {
return properties.compilationUnits.map {
it.sourceFolders.filter { includeDependencies || !it.dependency }
}
}

private fun File.localVirtualFile() = contentRoot.findFileByRelativePath(
this.relativeTo(
File(contentRoot.path),
Expand Down
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

0 comments on commit 27cbe39

Please sign in to comment.