1+ package lsp.utils
2+
3+ import java.nio.file.Files
4+ import kotlin.io.path.ExperimentalPathApi
5+ import kotlin.io.path.absolutePathString
6+ import kotlin.io.path.copyToRecursively
7+ import kotlin.io.path.deleteRecursively
8+ import kotlin.io.path.toPath
9+
10+ object WorkspaceUtils {
11+ private const val TEMPLATE_NAME = " root-template"
12+ private val workspacePath = this ::class .java.getResource(" /lsp/workspaces" )?.toURI()?.toPath()
13+ ? : error(" no workspaces folder found" )
14+
15+ private const val GENERATED_NAME_PREFIX = " lsp-workspace-root-"
16+
17+ @OptIn(ExperimentalPathApi ::class )
18+ fun withTempWorkspace (
19+ kotlinVersion : String ,
20+ block : suspend (localWorkspacePath: String , remoteWorkspacePath: String ) -> Unit
21+ ) {
22+ val template = workspacePath.resolve(TEMPLATE_NAME )
23+ require(Files .exists(template)) { " no template found" }
24+
25+ val dstWorkspaceName = " $GENERATED_NAME_PREFIX$kotlinVersion "
26+ val (dstDir, alreadyExists) = workspacePath.resolve(dstWorkspaceName).let {
27+ it to it.toFile().mkdirs()
28+ }
29+
30+ if (! alreadyExists) {
31+ template.copyToRecursively(target = dstDir, overwrite = false , followLinks = false )
32+
33+ val buildFile = dstDir.resolve(" build.gradle.kts" ).also {
34+ require(Files .exists(it)) { " no build file found in dst dir" }
35+ }.toFile()
36+
37+ val kotlinVersionPlaceholder = " {{kotlin_version}}"
38+ val pluginsPlaceholder = " {{plugins}}"
39+ val dependenciesPlaceholder = " {{dependencies}}"
40+
41+ val newContent: String = listOf (kotlinVersionPlaceholder, pluginsPlaceholder, dependenciesPlaceholder)
42+ .zip(listOf (setOf (kotlinVersion), emptySet(), emptySet()))
43+ .fold(buildFile.readText()) { acc, (placeholder, values) ->
44+ acc.replace(placeholder, values.joinToString(" \n " ))
45+ }
46+ buildFile.writeText(newContent)
47+ }
48+
49+ val localPath = dstDir.absolutePathString()
50+ val remotePath = " /workspaces/$dstWorkspaceName "
51+
52+ block(localPath, remotePath)
53+
54+ dstDir.deleteRecursively()
55+ }
56+ }
0 commit comments