-
Notifications
You must be signed in to change notification settings - Fork 118
/
JsMRGenerator.kt
254 lines (219 loc) · 9.12 KB
/
JsMRGenerator.kt
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
* Copyright 2022 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.gradle.generator.js
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.STRING
import com.squareup.kotlinpoet.TypeSpec
import dev.icerock.gradle.generator.MRGenerator
import dev.icerock.gradle.utils.calculateResourcesHash
import dev.icerock.gradle.utils.klibs
import org.gradle.api.Action
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.gradle.targets.js.ir.KotlinJsIrCompilation
import org.jetbrains.kotlin.gradle.targets.js.ir.KotlinJsIrTarget
import org.jetbrains.kotlin.gradle.tasks.Kotlin2JsCompile
import org.jetbrains.kotlin.library.impl.KotlinLibraryLayoutImpl
import java.io.File
class JsMRGenerator(
generatedDir: File,
sourceSet: SourceSet,
mrSettings: MRSettings,
generators: List<Generator>,
private val compilation: KotlinJsIrCompilation
) : MRGenerator(
generatedDir = generatedDir,
sourceSet = sourceSet,
mrSettings = mrSettings,
generators = generators
) {
private val flattenClassName: String get() = mrSettings.packageName.replace(".", "")
override val resourcesGenerationDir: File
get() = outputDir.resolve("$flattenClassName/res")
override fun getMRClassModifiers(): Array<KModifier> = arrayOf(KModifier.ACTUAL)
override fun processMRClass(mrClass: TypeSpec.Builder) {
mrClass.addProperty(
PropertySpec.builder("contentHash", STRING, KModifier.PRIVATE)
.initializer("%S", resourcesGenerationDir.calculateResourcesHash())
.build()
)
@OptIn(ExperimentalStdlibApi::class)
val stringsLoaderInitializer = buildList {
val stringsObjectLoader = mrClass
.typeSpecs
.find { it.name == "strings" }
?.propertySpecs
?.find { it.name == "stringsLoader" }
val pluralsObjectLoader = mrClass
.typeSpecs
.find { it.name == "plurals" }
?.propertySpecs
?.find { it.name == "stringsLoader" }
if (stringsObjectLoader != null) {
add("strings.stringsLoader")
}
if (pluralsObjectLoader != null) {
add("plurals.stringsLoader")
}
}.takeIf(List<*>::isNotEmpty)
?.joinToString(separator = " + ")
if (stringsLoaderInitializer != null) {
mrClass.addProperty(
PropertySpec.builder(
"stringsLoader",
ClassName("dev.icerock.moko.resources.provider", "RemoteJsStringLoader"),
).initializer(stringsLoaderInitializer)
.build()
)
}
}
override fun apply(generationTask: Task, project: Project) {
project.tasks.withType<Kotlin2JsCompile>().configureEach {
it.dependsOn(generationTask)
}
setupKLibResources(generationTask)
setupResources()
}
private fun setupKLibResources(generationTask: Task) {
val compileTask: Kotlin2JsCompile = compilation.compileKotlinTask
compileTask.dependsOn(generationTask)
@Suppress("UNCHECKED_CAST")
compileTask.doLast(CopyResourcesToKLibAction(resourcesGenerationDir) as Action<in Task>)
}
private fun setupResources() {
val kotlinTarget = compilation.target as KotlinJsIrTarget
kotlinTarget.compilations
.map { it.compileKotlinTask }
.forEach { compileTask ->
@Suppress("UNCHECKED_CAST")
compileTask.doLast(CopyResourcesToExecutableAction(resourcesGenerationDir) as Action<in Task>)
}
}
class CopyResourcesToKLibAction(private val resourcesDir: File) : Action<Kotlin2JsCompile> {
override fun execute(task: Kotlin2JsCompile) {
val unpackedKLibDir: File = task.outputFileProperty.get()
val defaultDir = File(unpackedKLibDir, "default")
val resRepackDir = File(defaultDir, "resources")
if (resRepackDir.exists().not()) return
val resDir = File(resRepackDir, "moko-resources-js")
resourcesDir.copyRecursively(
resDir,
overwrite = true
)
}
}
class CopyResourcesToExecutableAction(
private val resourcesGeneratedDir: File
) : Action<Kotlin2JsCompile> {
override fun execute(task: Kotlin2JsCompile) {
val project: Project = task.project
task.klibs.forEach { dependency ->
copyResourcesFromLibraries(
inputFile = dependency,
project = project,
outputDir = resourcesGeneratedDir
)
}
generateWebpackConfig(project, resourcesGeneratedDir)
generateKarmaConfig(project)
}
private fun generateWebpackConfig(project: Project, resourcesOutput: File) {
val webpackDir: File = File(project.projectDir, "webpack.config.d")
webpackDir.mkdirs()
val webpackConfig: File = File(webpackDir, "moko-resources-generated.js")
webpackConfig.writeText(
// language=js
"""
const path = require('path');
const mokoResourcePath = path.resolve("${resourcesOutput.absolutePath}");
config.module.rules.push(
{
test: /\.(.*)/,
include: [
path.resolve(mokoResourcePath)
],
type: 'asset/resource'
}
);
config.module.rules.push(
{
test: /\.(otf|ttf)?${'$'}/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[ext]',
outputPath: 'fonts/'
}
}
]
}
)
config.resolve.modules.push(
path.resolve(mokoResourcePath)
);
""".trimIndent()
)
}
private fun generateKarmaConfig(project: Project) {
val webpackDir: File = File(project.projectDir, "karma.config.d")
webpackDir.mkdirs()
val webpackTestConfig: File = File(webpackDir, "moko-resources-generated.js")
val pattern = "`\${output.path}/**/*`"
webpackTestConfig.writeText(
// language=js
"""
// workaround from https://github.com/ryanclark/karma-webpack/issues/498#issuecomment-790040818
const output = {
path: require("os").tmpdir() + '/' + '_karma_webpack_' + Math.floor(Math.random() * 1000000),
}
config.set(
{
webpack: {... createWebpackConfig(), output},
files: config.files.concat([{
pattern: $pattern,
watched: false,
included: false,
}]
)
}
)
""".trimIndent()
)
}
private fun copyResourcesFromLibraries(
inputFile: File,
project: Project,
outputDir: File
) {
if (inputFile.extension != "klib") return
if (inputFile.exists().not()) return
project.logger.info("copy resources from $inputFile into $outputDir")
val klibKonan = org.jetbrains.kotlin.konan.file.File(inputFile.path)
val klib = KotlinLibraryLayoutImpl(klib = klibKonan, component = "default")
val layout = klib.extractingToTemp
try {
File(layout.resourcesDir.path, "moko-resources-js").copyRecursively(
target = outputDir,
overwrite = true
)
} catch (exc: kotlin.io.NoSuchFileException) {
project.logger.info("resources in $inputFile not found")
} catch (exc: java.nio.file.NoSuchFileException) {
project.logger.info("resources in $inputFile not found (empty lib)")
}
}
}
companion object {
const val STRINGS_JSON_NAME = "stringsJson"
const val PLURALS_JSON_NAME = "pluralsJson"
const val SUPPORTED_LOCALES_PROPERTY_NAME = "supportedLocales"
const val STRINGS_FALLBACK_FILE_URL_PROPERTY_NAME = "stringsFallbackFileUrl"
const val PLURALS_FALLBACK_FILE_URL_PROPERTY_NAME = "stringsFallbackFileUrl"
const val LOCALIZATION_DIR = "localization"
}
}