Created
April 5, 2024 12:50
-
-
Save fourlastor/247f2cea46ca6aee37d4375e9049f796 to your computer and use it in GitHub Desktop.
Create constants for translation files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
buildscript { | |
repositories { | |
mavenCentral() | |
gradlePluginPortal() | |
} | |
} | |
plugins { | |
id 'org.jetbrains.kotlin.jvm' version '1.9.10' | |
} | |
repositories { | |
mavenCentral() | |
} | |
dependencies { | |
implementation('com.squareup:javapoet:1.13.0') | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class GenerateStrings : DefaultTask() { | |
@get:InputDirectory | |
abstract val propertiesDir: DirectoryProperty | |
@get:OutputDirectory | |
abstract val destination: DirectoryProperty | |
init { | |
destination.convention(project.layout.buildDirectory.dir("generated/sources/strings")) | |
} | |
@TaskAction | |
fun run() { | |
val propertiesDir = propertiesDir.asFile.get() | |
val propertiesFiles = propertiesDir.walkTopDown() | |
.filter { it.isFile && it.extension == "properties" && !it.name.contains("_", ignoreCase = true) } | |
val stringsSpec = TypeSpec.classBuilder("R") | |
.addAnnotation(AnnotationSpec.builder(SuppressWarnings::class.java).addMember("value", "\$S", "unused").build()) | |
.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build()) | |
.addModifiers(Modifier.PUBLIC, Modifier.FINAL) | |
.apply { | |
for (propertiesFile in propertiesFiles) { | |
addType( | |
TypeSpec.classBuilder( propertiesFile.getName().replace(".properties", "")) | |
.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PRIVATE).build()) | |
.addModifiers(Modifier.PUBLIC, Modifier.FINAL, Modifier.STATIC) | |
.apply { | |
val properties = Properties().apply { load(propertiesFile.reader()) } | |
for (propertyName in properties.propertyNames()) { | |
addField(FieldSpec.builder( | |
String::class.java, propertyName.toString(), Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL | |
).initializer("\$S", propertyName.toString()) | |
.build()) | |
} | |
} | |
.build() | |
) | |
} | |
} | |
.build() | |
val outputFile = destination.asFile.get().resolve("com/pkmngen/game/R.java") | |
if (!outputFile.exists()) { | |
outputFile.getParentFile().mkdirs() | |
} | |
outputFile.writer().use { | |
JavaFile.builder("com.pkmngen.game", stringsSpec).build() | |
.writeTo(it) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment