aboutsummaryrefslogtreecommitdiff
path: root/common-util/src/main/kotlin/com/google/devtools/ksp/processing/impl/CodeGeneratorImpl.kt
blob: f9293bc6c0393e60cf0d4d2a0cc86052bff61cf9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
/*
 * Copyright 2020 Google LLC
 * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.devtools.ksp.processing.impl

import com.google.devtools.ksp.NoSourceFile
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Dependencies
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSFile
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream

class CodeGeneratorImpl(
    private val classDir: File,
    private val javaDir: File,
    private val kotlinDir: File,
    private val resourcesDir: File,
    private val projectBase: File,
    private val anyChangesWildcard: KSFile,
    private val allSources: List<KSFile>,
    private val isIncremental: Boolean
) : CodeGenerator {
    private val fileMap = mutableMapOf<String, File>()
    private val fileOutputStreamMap = mutableMapOf<String, FileOutputStream>()

    private val separator = File.separator

    val sourceToOutputs: MutableMap<File, MutableSet<File>> = mutableMapOf()

    // This function will also clear `fileOutputStreamMap` which will change the result of `generatedFile`
    fun closeFiles() {
        fileOutputStreamMap.keys.forEach {
            fileOutputStreamMap[it]!!.close()
        }
        fileOutputStreamMap.clear()
    }

    fun pathOf(packageName: String, fileName: String, extensionName: String): String {
        val packageDirs = if (packageName != "") "${packageName.split(".").joinToString(separator)}$separator" else ""
        val extension = if (extensionName != "") ".$extensionName" else ""
        return "$packageDirs$fileName$extension"
    }

    override fun createNewFile(
        dependencies: Dependencies,
        packageName: String,
        fileName: String,
        extensionName: String
    ): OutputStream {
        return createNewFile(
            dependencies,
            pathOf(packageName, fileName, extensionName),
            extensionToDirectory(extensionName)
        )
    }

    override fun createNewFileByPath(dependencies: Dependencies, path: String, extensionName: String): OutputStream {
        val extension = if (extensionName != "") ".$extensionName" else ""
        return createNewFile(dependencies, path + extension, extensionToDirectory(extensionName))
    }

    override fun associate(sources: List<KSFile>, packageName: String, fileName: String, extensionName: String) {
        associate(sources, pathOf(packageName, fileName, extensionName), extensionToDirectory(extensionName))
    }

    override fun associateByPath(sources: List<KSFile>, path: String, extensionName: String) {
        val extension = if (extensionName != "") ".$extensionName" else ""
        associate(sources, path + extension, extensionToDirectory(extensionName))
    }

    override fun associateWithClasses(
        classes: List<KSClassDeclaration>,
        packageName: String,
        fileName: String,
        extensionName: String
    ) {
        val path = pathOf(packageName, fileName, extensionName)
        val files = classes.map {
            it.containingFile ?: NoSourceFile(projectBase, it.qualifiedName?.asString().toString())
        }
        associate(files, path, extensionToDirectory(extensionName))
    }

    private fun extensionToDirectory(extensionName: String): File {
        return when (extensionName) {
            "class" -> classDir
            "java" -> javaDir
            "kt" -> kotlinDir
            else -> resourcesDir
        }
    }

    private fun createNewFile(dependencies: Dependencies, path: String, baseDir: File): OutputStream {
        val file = File(baseDir, path)
        if (!isWithinBaseDir(baseDir, file)) {
            throw IllegalStateException("requested path is outside the bounds of the required directory")
        }
        val absolutePath = file.absolutePath
        if (absolutePath in fileMap) {
            throw FileAlreadyExistsException(file)
        }
        val parentFile = file.parentFile
        if (!parentFile.exists() && !parentFile.mkdirs()) {
            throw IllegalStateException("failed to make parent directories.")
        }
        file.writeText("")
        fileMap[absolutePath] = file
        val sources = if (dependencies.isAllSources) {
            allSources + anyChangesWildcard
        } else {
            if (dependencies.aggregating) {
                dependencies.originatingFiles + anyChangesWildcard
            } else {
                dependencies.originatingFiles
            }
        }
        associate(sources, file)
        fileOutputStreamMap[absolutePath] = fileMap[absolutePath]!!.outputStream()
        return fileOutputStreamMap[absolutePath]!!
    }

    private fun isWithinBaseDir(baseDir: File, file: File): Boolean {
        val base = baseDir.toPath().normalize()
        return try {
            val relativePath = file.toPath().normalize()
            relativePath.startsWith(base)
        } catch (e: IOException) {
            false
        }
    }

    private fun associate(sources: List<KSFile>, path: String, baseDir: File) {
        val file = File(baseDir, path)
        if (!isWithinBaseDir(baseDir, file)) {
            throw IllegalStateException("requested path is outside the bounds of the required directory")
        }
        associate(sources, file)
    }

    private fun associate(sources: List<KSFile>, outputPath: File) {
        if (!isIncremental)
            return

        val output = outputPath.relativeTo(projectBase)
        sources.forEach { source ->
            sourceToOutputs.getOrPut(File(source.filePath).relativeTo(projectBase)) { mutableSetOf() }.add(output)
        }
    }

    val outputs: Set<File>
        get() = fileMap.values.mapTo(mutableSetOf()) { it.relativeTo(projectBase) }

    override val generatedFile: Collection<File>
        get() = fileOutputStreamMap.keys.map { fileMap[it]!! }
}