-
Notifications
You must be signed in to change notification settings - Fork 121
/
AppleStringsGenerator.kt
65 lines (54 loc) · 2.28 KB
/
AppleStringsGenerator.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
/*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.gradle.generator.apple
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.KModifier
import dev.icerock.gradle.generator.KeyType
import dev.icerock.gradle.generator.ObjectBodyExtendable
import dev.icerock.gradle.generator.StringsGenerator
import dev.icerock.gradle.generator.apple.AppleMRGenerator.Companion.BUNDLE_PROPERTY_NAME
import org.apache.commons.text.StringEscapeUtils
import org.gradle.api.file.FileTree
import java.io.File
class AppleStringsGenerator(
stringsFileTree: FileTree,
strictLineBreaks: Boolean,
private val baseLocalizationRegion: String
) : StringsGenerator(stringsFileTree, strictLineBreaks),
ObjectBodyExtendable by AppleGeneratorHelper() {
override fun getClassModifiers(): Array<KModifier> = arrayOf(KModifier.ACTUAL)
override fun getPropertyModifiers(): Array<KModifier> = arrayOf(KModifier.ACTUAL)
override fun getPropertyInitializer(key: String) =
CodeBlock.of("StringResource(resourceId = %S, bundle = $BUNDLE_PROPERTY_NAME)", key)
override fun generateResources(
resourcesGenerationDir: File,
language: String?,
strings: Map<KeyType, String>
) {
val resDirName = when (language) {
null -> "Base.lproj"
else -> "$language.lproj"
}
val resDir = File(resourcesGenerationDir, resDirName)
val localizableFile = File(resDir, "Localizable.strings")
resDir.mkdirs()
val content = strings.mapValues { (_, value) ->
convertXmlStringToAppleLocalization(value)
}.map { (key, value) ->
"\"$key\" = \"$value\";"
}.joinToString("\n")
localizableFile.writeText(content)
if (language == null) {
val regionDir = File(resourcesGenerationDir, "$baseLocalizationRegion.lproj")
regionDir.mkdirs()
val regionFile = File(regionDir, "Localizable.strings")
regionFile.writeText(content)
}
}
private fun convertXmlStringToAppleLocalization(input: String): String {
val xmlDecoded = StringEscapeUtils.unescapeXml(input)
return xmlDecoded.replace("\n", "\\n")
.replace("\"", "\\\"")
}
}