diff --git a/.gitignore b/.gitignore index 01a89a8..af53e1b 100644 --- a/.gitignore +++ b/.gitignore @@ -21,7 +21,9 @@ classes/ .settings *.launch .architectury-transformer/debug.log -**/resources/.cache/ +**/src/generated/ +!test/src/main/resources/ +!test/src/main/resources/** *.patch *.DS_Store diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ba9f119..53db024 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -36,7 +36,7 @@ - `RegistrateLib` 是本分支的库模组入口点,同时持有共享元数据/常量 `RegistrateLib` is the library mod entrypoint for the fork and also holds shared metadata/constants -- `src/test/java/com/modularmc/registrate/test/meta` 包含用于生成的桥接方法的维护辅助工具 - `src/test/java/com/modularmc/registrate/test/meta` contains maintenance helpers for generated bridge methods +- `test/src/main/java/com/modularmc/registratetest` 包含用于生成的桥接方法的维护辅助工具 + `test/src/main/java/com/modularmc/registratetest` contains maintenance helpers for generated bridge methods - 当上游 Registrate 变更时,先更新实现类,然后对照 `docs/architecture.md` 重新验证包所有权 When upstream Registrate changes, update implementation classes first and then re-verify package ownership against `docs/architecture.md` diff --git a/build.gradle b/build.gradle index 68952f2..54b7bb6 100644 --- a/build.gradle +++ b/build.gradle @@ -5,12 +5,10 @@ plugins { id 'eclipse' id 'idea' id 'maven-publish' - id 'jacoco' alias libs.plugins.modDevGradle //alias libs.plugins.shadow alias libs.plugins.spotless alias libs.plugins.kotlin.jvm - alias libs.plugins.ksp } group = maven_group @@ -41,14 +39,6 @@ sourceSets { runtimeClasspath += main.output + main.runtimeClasspath } - test { - compileClasspath += main.output + main.compileClasspath - runtimeClasspath += main.output + main.runtimeClasspath - resources { - srcDir 'src/test/generated/resources' - } - } - extra { compileClasspath += main.output runtimeClasspath += main.output + main.runtimeClasspath @@ -56,9 +46,7 @@ sourceSets { clientExtra { compileClasspath += client.output + extra.compileClasspath - // The normal client run also mounts the test mod, so include the test source set - // here to keep generated test resources synchronized into build/resources/test. - runtimeClasspath += client.output + client.runtimeClasspath + extra.runtimeClasspath + test.output + test.runtimeClasspath + runtimeClasspath += client.output + client.runtimeClasspath + extra.runtimeClasspath } } @@ -67,8 +55,6 @@ configurations { clientRuntimeOnly.canBeResolved = false extraRuntimeOnly.canBeResolved = false clientExtraRuntimeOnly.canBeResolved = false - testImplementation.canBeResolved = false - testRuntimeOnly.canBeResolved = false runtimeClasspath.extendsFrom localRuntime extraRuntimeClasspath.extendsFrom extraLocalRuntime @@ -93,33 +79,3 @@ tasks.withType(JavaCompile).configureEach { options.compilerArgs << '-Xmaxerrs' << '2000' options.compilerArgs << "-Xlint:-removal" } - -tasks.named('test') { - // The test source set is exercised by NeoForge's GameTest server. - failOnNoDiscoveredTests = false -} - -jacoco { - applyTo runGameTestServer -} - -tasks.named('runGameTestServer') { - jacoco.excludes = ['com.mojang.*', 'net.minecraft.*', 'net.neoforged.*'] -} - -jacocoTestReport { - dependsOn runGameTestServer - executionData runGameTestServer - sourceSets sourceSets.test - reports { - csv.required = false - xml.required = true - html.outputLocation = layout.buildDirectory.dir('coverage') - xml.outputLocation = layout.buildDirectory.file('coverage/coverage.xml') - } - afterEvaluate { - classDirectories.setFrom(classDirectories.asFileTree.matching { - exclude '**/client/**', '**/mixins/**' - }) - } -} diff --git a/dependencies.gradle b/dependencies.gradle index 15d4f3c..fb5d39c 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -5,13 +5,6 @@ dependencies { jarJar(api(libs.kotlin.stdlib.get())) { exclude group: 'org.jetbrains', module: 'annotations' } - testImplementation(libs.testframework.get()) - testAnnotationProcessor(project(':localization-processor')) - kspTest(project(':localization-processor')) - - // Standard runtime mods // - localRuntime(libs.testframework) - renderNurseCfg(libs.renderNurse) ////////////////////////////////////////////////////// diff --git a/docs/architecture.md b/docs/architecture.md index 911f4c3..0cabec2 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -75,8 +75,8 @@ Treat the root package plus `builders` and `util.entry` as the main downstream-f Event-bus plumbing and other implementation-only helpers belong under `internal` - 实例级 NeoForge 生命周期编排放在 `internal.lifecycle` Instance-scoped NeoForge lifecycle orchestration belongs in `internal.lifecycle` -- 仅测试用的框架放在 `src/test/java` - Test-only scaffolding belongs under `src/test/java` +- 仅测试用的框架放在 `test/src/main/java` + Test-only scaffolding belongs under `test/src/main/java` ## 现代化原则 / Modernization Principles diff --git a/docs/localization-exchange.schema.json b/docs/localization-exchange.schema.json new file mode 100644 index 0000000..a0487b9 --- /dev/null +++ b/docs/localization-exchange.schema.json @@ -0,0 +1,94 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Registrate Localization Exchange", + "type": "object", + "required": ["formatVersion", "modId", "sourceLocale", "entries"], + "properties": { + "formatVersion": { "const": 1 }, + "modId": { "type": "string" }, + "sourceLocale": { "$ref": "#/$defs/locale" }, + "entries": { + "type": "array", + "items": { "$ref": "#/$defs/entry" } + } + }, + "additionalProperties": false, + "$defs": { + "locale": { + "type": "string", + "pattern": "^[a-z]{2}_[a-z]{2}$" + }, + "revision": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + "entry": { + "type": "object", + "required": ["namespace", "key", "source", "context", "translations"], + "properties": { + "namespace": { "type": "string" }, + "key": { "type": "string" }, + "source": { "$ref": "#/$defs/sourceText" }, + "context": { "$ref": "#/$defs/context" }, + "translations": { + "type": "array", + "items": { "$ref": "#/$defs/translation" } + } + }, + "additionalProperties": false + }, + "sourceText": { + "type": "object", + "required": ["locale", "text", "revision"], + "properties": { + "locale": { "$ref": "#/$defs/locale" }, + "text": { "type": "string" }, + "revision": { "$ref": "#/$defs/revision" } + }, + "additionalProperties": false + }, + "context": { + "type": "object", + "required": ["domains", "type", "glossaryIds", "unitIds", "placeholderSignature"], + "properties": { + "domains": { "type": "array", "items": { "type": "string" } }, + "type": { "type": ["string", "null"] }, + "glossaryIds": { "type": "array", "items": { "type": "string" } }, + "unitIds": { "type": "array", "items": { "type": "string" } }, + "placeholderSignature": { + "type": "object", + "propertyNames": { "pattern": "^(0|[1-9][0-9]*)$" }, + "additionalProperties": { "type": "integer", "minimum": 1 } + } + }, + "additionalProperties": false + }, + "translation": { + "type": "object", + "required": ["locale", "text", "source", "sourceRevision", "status", "locked"], + "properties": { + "locale": { "$ref": "#/$defs/locale" }, + "text": { "type": "string" }, + "source": { "$ref": "#/$defs/translationSource" }, + "sourceRevision": { "$ref": "#/$defs/revision" }, + "status": { + "type": ["string", "null"], + "enum": ["stale", "draft", "in_review", "approved", null] + }, + "locked": { "type": "boolean" } + }, + "additionalProperties": false + }, + "translationSource": { + "type": "object", + "required": ["kind", "location"], + "properties": { + "kind": { + "enum": ["fallback", "variant", "automatic", "glossary", "imported", "declared"] + }, + "location": { "type": "string" } + }, + "additionalProperties": false + } + } +} diff --git a/docs/localization.md b/docs/localization.md index c7afee1..a35ea9d 100644 --- a/docs/localization.md +++ b/docs/localization.md @@ -7,10 +7,16 @@ ```java import com.modularmc.registrate.Registrate; import com.modularmc.registrate.localization.MinecraftLocale; +import java.nio.file.Path; Registrate registrate = Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US); +registrate.export().localization() + .path(Path.of("build", "localization", "mymod.json")) + .build(); ``` +`path` is the destination JSON file. Relative paths resolve against the DataGen process working directory. The export request is fulfilled after language callbacks have run once; the same declarations produce both Minecraft language files and the exchange document. + ## 声明文本 物品、方块、实体和流体的 Builder 从注册对象取 Minecraft 原生翻译 Key。通用 Builder 可用 `.localization(keyFunction, text -> ...)` 指定取 Key 的方式。 @@ -30,7 +36,7 @@ var title = registrate.addLocalization(new TranslationKey(MOD_ID, "gui.mymod.vol `addLocalization` 返回可用于 GUI 的翻译组件。进度标题等跨侧文本可在模组构造期间声明,在服务端 DataGen 的进度回调中引用组件。`addLang`、`addRawLang` 和 `ProviderType.LANG` 回调都使用同一个源 Locale。 -在 `registrate.terminology()` 中登记 `Domain`、`GlossaryTerm` 和 `MeasurementUnit`。Builder 的 `.defaults(defaults)` 可复用领域、文本类型和术语。条目的显式参数覆盖对应的默认值。 +在 `registrate.terminology()` 中登记 `Domain`、`GlossaryTerm` 和 `MeasurementUnit`。用 `.localizationDefaults(defaults)` 设置模组级默认值,Builder 的 `.defaults(defaults)` 可设置条目级默认值。条目的显式参数覆盖对应默认值。 ### 按语境选取术语 @@ -48,6 +54,12 @@ var title = registrate.addLocalization(new TranslationKey(MOD_ID, "gui.mymod.vol 转换会保留 Minecraft 参数、样式标记、URL、换行和已声明的单位符号。默认的 `en_us → en_ud` 同样遵循这些规则,并用显式索引保持倒置后的参数含义。 +### 导出交换数据 + +导出文档的 `formatVersion` 当前为 `1`。每个条目保留输出命名空间、原始 Key、源文本、SHA-256 源修订、领域、TextType、词条与单位引用、占位符签名和译文候选。译文记录包含 Locale、文本、来源类型与位置、源修订、审核状态和锁定标记。自动 Locale 变体也会进入记录,`source.location` 标明原始声明与转换路径。 + +JSON Schema 位于 [`localization-exchange.schema.json`](localization-exchange.schema.json)。条目按命名空间和 Key 排序,译文按 Locale、来源类型和来源位置排序。显式译文的 `status` 为 `null`;导入译文保留当前审核状态和其审核时使用的源修订。 + ### 导入人工译文 在模组初始化时用 `importTranslation` 登记已读入的译文。提供译者审核时对应的源文本修订,以及可以定位到文件或平台条目的来源。 @@ -71,33 +83,25 @@ registrate.importTranslation(new ImportedTranslation( DataGen 用模组当前选中的源文本核对修订。源文本变化会将译文标为 `STALE`。锁定译文仍可参与选择,未锁定的过期译文仅用于诊断,此时配置的术语、转换和回退规则可以继续解析目标 Locale。开发者显式声明优先,其次是锁定的导入译文和当前修订的普通导入译文。同一层级中,已批准、审核中和草稿依次参与选择。 -## 接入注解处理器 +## 注解声明 -用 `./gradlew :localization-processor:jar` 构建与库版本对应的处理器。Java 源码使用 `annotationProcessor`,Kotlin 源码使用 KSP 插件和 `ksp`。混合项目可同时使用两项配置,主库作为模组依赖。 - -```groovy -dependencies { - def processor = files("libs/registratelib-26.1.2-${registratelib_version}-localization-processor.jar") - annotationProcessor(processor) - ksp(processor) -} -``` +添加 RegistrateLib 模组依赖即可在 Java 和 Kotlin 源码中使用本地化注解。DataGen 从 NeoForge 的扫描结果读取所属模组文件中的声明。升级时移除 RegistrateLib 的 `annotationProcessor` 和 `ksp` 依赖。旧构建目录里有索引文件时,清理一次再构建。 -`@Trans` 和 `@TransVariants` 可以声明在类型或字段上。`modId` 选择声明归属的模组和源 Locale。省略 `namespace` 时,资源命名空间取 `modId`。 +`@Trans` 和 `@TransVariants` 可以声明在类型或字段上。文件只包含一个 Mod 时可以省略 `modId`,DataGen 使用该 Mod 的源 Locale。文件包含多个 Mod 时,每条声明都必须填写 `modId`。省略 `namespace` 时,资源命名空间取所属 Mod 的 ID。 ```java -@TransVariants(modId = "mymod", keyPrefix = "gui.mymod.power", value = { +@TransVariants(keyPrefix = "gui.mymod.power", value = { @Variant(id = "low", source = "Low power"), @Variant(id = "high", source = "High power") }) final class Labels { - @Trans(modId = "mymod", key = "gui.mymod.container", source = "Test Container", + @Trans(key = "gui.mymod.container", source = "Test Container", translations = @Translation(locale = MinecraftLocale.ZH_CN, text = "测试容器")) static final String CONTAINER = "gui.mymod.container"; } ``` -Kotlin 中在带有后备字段的属性上使用 `@field:Trans` 或 `@field:TransVariants`。两个处理器按 Mod ID 写入各自的版本化声明索引,DataGen 从所属模组读取并合并。变体的 Key 由前缀和 ID 拼接,例如 `gui.mymod.power.low`。同一命名空间、Key 和 Locale 下,同级异值声明会报告双方来源。`%s` 的隐式索引按出现顺序分配,译文可用 `%1$s` 等显式索引重排。 +Kotlin 中在带有后备字段的属性上使用 `@field:Trans` 或 `@field:TransVariants`。变体的 Key 由前缀和 ID 拼接,例如 `gui.mymod.power.low`。同一命名空间、Key 和 Locale 下,同级异值声明会报告双方来源,并用类名、字段名和变体 ID 定位注解。`%s` 的隐式索引按出现顺序分配,译文可用 `%1$s` 等显式索引重排。 ## 注册兼容性 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 41c7b01..e544245 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -6,7 +6,6 @@ shadow = "9.6.1" spotless = "8.11.0" modDevGradle = "2.0.148" kotlin = "2.4.21" -ksp = "2.3.14" jetbrains-annotations = "26.1.0" jspecify = "1.0.0" renderNurse = "0.0.26" @@ -17,7 +16,6 @@ minecraft = { module = "com.mojang:minecraft", version.ref = "mine neoForge = { module = "net.neoforged:neoforge", version.ref = "neoForge" } testframework = { module = "net.neoforged:testframework", version.ref = "neoForge" } kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } -ksp-api = { module = "com.google.devtools.ksp:symbol-processing-api", version.ref = "ksp" } renderNurse = { module = "net.neoforged:render-nurse", version.ref = "renderNurse" } mixin = { module = "org.spongepowered:mixin", version.ref = "mixin" } jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } @@ -28,4 +26,3 @@ modDevGradle = { id = "net.neoforged.moddev", version.ref = "modDevGr shadow = { id = "com.gradleup.shadow", version.ref = "shadow" } spotless = { id = "com.diffplug.spotless", version.ref = "spotless" } kotlin-jvm = { id = "org.jetbrains.kotlin.jvm", version.ref = "kotlin" } -ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } \ No newline at end of file diff --git a/gradle/scripts/jars.gradle b/gradle/scripts/jars.gradle index e60d0db..b1a28bc 100644 --- a/gradle/scripts/jars.gradle +++ b/gradle/scripts/jars.gradle @@ -3,10 +3,6 @@ jar { exclude "**/SimplifiedToTraditional.properties" } -tasks.named('assemble') { - dependsOn(':localization-processor:jar') -} - tasks.register('slimJar', Jar) { dependsOn("classes") archiveClassifier = "slim" diff --git a/gradle/scripts/moddevgradle.gradle b/gradle/scripts/moddevgradle.gradle index 1f28c0f..aa28e77 100644 --- a/gradle/scripts/moddevgradle.gradle +++ b/gradle/scripts/moddevgradle.gradle @@ -1,7 +1,5 @@ import org.slf4j.event.Level -def devTestModId = 'testmod' - neoForge { version = libs.versions.neoForge.get() @@ -20,7 +18,6 @@ neoForge { // // interfaceInjectionData = project.files('injected_interfaces/interfaces.json') - addModdingDependenciesTo(sourceSets.test) addModdingDependenciesTo(sourceSets.extra) mods { @@ -31,9 +28,6 @@ neoForge { sourceSet(sourceSets.extra) sourceSet(sourceSets.clientExtra) } - "${devTestModId}" { - sourceSet(sourceSets.test) - } } runs { @@ -44,7 +38,6 @@ neoForge { gameDirectory.set(file('run/client')) - systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) } server { @@ -54,74 +47,12 @@ neoForge { gameDirectory.set(file('run/server')) programArguments.addAll('--nogui', '--world', 'world-extra') - systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) - } - - // This run config launches GameTestServer and runs all registered gametests, then exits. - // By default, the server will crash when no gametests are provided. - // The gametest system is also enabled by default for other run configs under the /test command. - gameTestServer { - type = "gameTestServer" - sourceSet = sourceSets.test - ideName = "Game Tests" - - gameDirectory.set(file('run/gametest/server')) - systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) - environment('TEST', 'true') - } - - gameTestClient { - client() - sourceSet = sourceSets.test - ideName = "Game Tests (Client)" - - gameDirectory.set(file('run/gametest/client')) - systemProperty('neoforge.enabledGameTestNamespaces', devTestModId) - environment('TEST', 'true') - } - - data { - type = 'clientData' - sourceSet = sourceSets.main - ideName = "Data Generation" - - gameDirectory.set(file('run/data')) - // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. - programArguments.addAll('--mod', project.mod_id) - programArguments.addAll('--all') - programArguments.addAll('--output', file('src/generated/resources/').getAbsolutePath()) - programArguments.addAll('--existing', file('src/main/resources/').getAbsolutePath()) - } - - Testdata { - type = providers.gradleProperty('testDataSide').getOrElse('all') == 'server' ? 'serverData' : 'clientData' - sourceSet = sourceSets.test - ideName = "Test Data Generation" - - gameDirectory.set(file('run/data')) - // Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources. - programArguments.addAll('--mod', "${devTestModId},localetest", '--flat') - programArguments.addAll('--all') - programArguments.add('--output') - programArguments.add(providers.gradleProperty('testDataOutput').orElse('src/test/generated/resources').map { file(it).absolutePath }) - programArguments.addAll('--existing', file('src/test/resources/').getAbsolutePath()) } // applies to all the run configs above configureEach { - // Recommended logging data for a userdev environment - // The markers can be added/remove as needed separated by commas. - // "SCAN": For mods scan. - // "REGISTRIES": For firing of registry events. - // "REGISTRYDUMP": For getting the contents of all registries. systemProperty 'forge.logging.markers', 'REGISTRIES' - - // Enable assertions for our classes in dev environment jvmArgument('-ea:com.modularmc.registrate...') - - // Recommended logging level for the console - // You can set various levels here. - // Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels logLevel = Level.INFO } } diff --git a/gradle/scripts/repositories.gradle b/gradle/scripts/repositories.gradle index e113d2b..4fec516 100644 --- a/gradle/scripts/repositories.gradle +++ b/gradle/scripts/repositories.gradle @@ -8,7 +8,6 @@ repositories { includeGroup("it.unimi.dsi") includeGroup("org.lwjgl") includeGroup("com.google.guava") - includeGroup("com.google.devtools.ksp") includeGroup("org.jacoco") includeGroupAndSubgroups("io.netty") includeGroupAndSubgroups("org.jetbrains") diff --git a/gradle/scripts/spotless.gradle b/gradle/scripts/spotless.gradle index 7f8f125..6a5dbbb 100644 --- a/gradle/scripts/spotless.gradle +++ b/gradle/scripts/spotless.gradle @@ -9,7 +9,7 @@ spotless { endWithNewline() } java { - target 'src/*/java/**/*.java', 'localization-processor/src/main/java/**/*.java' + target 'src/*/java/**/*.java' def orderFile = file("$rootDir/gradle/spotless/spotless.importorder") def formatFile = file("$rootDir/gradle/spotless/spotless.eclipseformat.xml") @@ -23,7 +23,7 @@ spotless { eclipse('4.31').configFile(formatFile) } kotlin { - target 'src/*/java/**/*.kt', 'localization-processor/src/*/java/**/*.kt' + target 'src/*/java/**/*.kt' def orderFile = file("$rootDir/gradle/spotless/spotless.ktlint") ktlint().setEditorConfigPath(orderFile) diff --git a/localization-processor/build.gradle b/localization-processor/build.gradle deleted file mode 100644 index 26605dd..0000000 --- a/localization-processor/build.gradle +++ /dev/null @@ -1,48 +0,0 @@ -plugins { - alias libs.plugins.kotlin.jvm -} - -group = rootProject.group -version = rootProject.version - -java { - toolchain.languageVersion.set(rootProject.java.toolchain.languageVersion) -} - -kotlin { - jvmToolchain(rootProject.java.toolchain.languageVersion.get().asInt()) -} - -configurations { - processorKotlinRuntime { - canBeConsumed = false - } -} - -dependencies { - compileOnly(libs.ksp.api) - compileOnly(project(':')) { - transitive = false - } - processorKotlinRuntime(libs.kotlin.stdlib) { - transitive = false - } -} - -tasks.named('jar', Jar) { - archiveBaseName.set(rootProject.base.archivesName) - archiveClassifier = 'localization-processor' - destinationDirectory.set(rootProject.layout.buildDirectory.dir('libs')) - - // The processor needs these types on javac's isolated processor path. - from(rootProject.sourceSets.main.output.classesDirs) { - include 'com/modularmc/registrate/localization/annotation/**' - include 'com/modularmc/registrate/localization/MinecraftLocale.class' - include 'com/modularmc/registrate/localization/index/LocalizationIndex*.class' - } - - // Keep the standalone compiler path working for Java consumers. - from({ zipTree(configurations.processorKotlinRuntime.singleFile) }) { - include 'kotlin/**', 'META-INF/*.kotlin_module', 'META-INF/LICENSE*', 'META-INF/NOTICE*' - } -} diff --git a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt b/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt deleted file mode 100644 index c95760b..0000000 --- a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/TranslationProcessor.kt +++ /dev/null @@ -1,78 +0,0 @@ -package com.modularmc.registrate.localization.processor - -import com.modularmc.registrate.localization.MinecraftLocale -import com.modularmc.registrate.localization.annotation.Trans -import com.modularmc.registrate.localization.annotation.TransVariants -import com.modularmc.registrate.localization.annotation.Translation -import com.modularmc.registrate.localization.index.LocalizationIndex -import com.modularmc.registrate.localization.index.LocalizationIndex.Entry - -import java.io.DataOutputStream -import java.io.IOException -import java.util.EnumMap -import javax.annotation.processing.AbstractProcessor -import javax.annotation.processing.RoundEnvironment -import javax.lang.model.SourceVersion -import javax.lang.model.element.Element -import javax.lang.model.element.TypeElement -import javax.tools.StandardLocation - -/** Collects the annotated declarations from all rounds of a downstream Java compilation. */ -class TranslationProcessor : AbstractProcessor() { - private val declarations = LinkedHashMap>() - - private data class Declaration(val element: Element, val entry: Entry) - - override fun getSupportedAnnotationTypes(): Set = setOf(Trans::class.java.name, TransVariants::class.java.name) - - override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latestSupported() - - override fun process(annotations: Set, round: RoundEnvironment): Boolean { - for (element in round.getElementsAnnotatedWith(Trans::class.java)) { - val trans = element.getAnnotation(Trans::class.java) - add(trans.modId, trans.namespace, trans.key, trans.source, trans.translations, element, "@Trans ${location(element)}") - } - for (element in round.getElementsAnnotatedWith(TransVariants::class.java)) { - val group = element.getAnnotation(TransVariants::class.java) - for (variant in group.value) { - val key = LocalizationIndex.variantKey(group.keyPrefix, variant.id) - add(group.modId, group.namespace, key, variant.source, variant.translations, element, "@TransVariants ${location(element)} [${variant.id}]") - } - } - if (round.processingOver() && !round.errorRaised()) { - declarations.forEach(::write) - } - return true - } - - private fun add(modId: String, namespace: String, key: String, source: String, translations: Array, element: Element, location: String) { - val texts = if (translations.isEmpty()) { - emptyMap() - } else { - EnumMap(MinecraftLocale::class.java).apply { - for (translation in translations) put(translation.locale, translation.text) - } - } - val entry = Entry(namespace.ifEmpty { modId }, key, source, location, texts) - declarations.getOrPut(modId, ::ArrayList).add(Declaration(element, entry)) - } - - private fun write(modId: String, declarations: List) { - val path = LocalizationIndex.path(modId) - val origins = declarations.mapTo(LinkedHashSet(), Declaration::element).toTypedArray() - try { - val resource = processingEnv.filer.createResource(StandardLocation.CLASS_OUTPUT, "", path, *origins) - DataOutputStream(resource.openOutputStream().buffered()).use { output -> - LocalizationIndex.write(output, declarations.map(Declaration::entry)) - } - } catch (error: IOException) { - processingEnv.messager.printError("Cannot write localization index $path: ${error.message}") - } - } - - private fun location(element: Element): String { - if (element is TypeElement) return element.qualifiedName.toString() - val owner = element.enclosingElement as TypeElement - return "${owner.qualifiedName}#${element.simpleName}" - } -} diff --git a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt b/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt deleted file mode 100644 index 65b3194..0000000 --- a/localization-processor/src/main/java/com/modularmc/registrate/localization/processor/ksp/LocalizationSymbolProcessorProvider.kt +++ /dev/null @@ -1,107 +0,0 @@ -package com.modularmc.registrate.localization.processor.ksp - -import com.modularmc.registrate.localization.MinecraftLocale -import com.modularmc.registrate.localization.annotation.Trans -import com.modularmc.registrate.localization.annotation.TransVariants -import com.modularmc.registrate.localization.index.LocalizationIndex -import com.modularmc.registrate.localization.index.LocalizationIndex.Entry -import com.modularmc.registrate.localization.index.LocalizationIndex.Frontend - -import com.google.devtools.ksp.processing.CodeGenerator -import com.google.devtools.ksp.processing.Dependencies -import com.google.devtools.ksp.processing.Resolver -import com.google.devtools.ksp.processing.SymbolProcessor -import com.google.devtools.ksp.processing.SymbolProcessorEnvironment -import com.google.devtools.ksp.processing.SymbolProcessorProvider -import com.google.devtools.ksp.symbol.FileLocation -import com.google.devtools.ksp.symbol.KSAnnotated -import com.google.devtools.ksp.symbol.KSAnnotation -import com.google.devtools.ksp.symbol.KSClassDeclaration -import com.google.devtools.ksp.symbol.KSDeclaration -import com.google.devtools.ksp.symbol.KSFile -import com.google.devtools.ksp.symbol.KSPropertyDeclaration -import com.google.devtools.ksp.symbol.Origin - -import java.io.DataOutputStream -import java.util.EnumMap - -class LocalizationSymbolProcessorProvider : SymbolProcessorProvider { - override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor = LocalizationSymbolProcessor(environment.codeGenerator) -} - -/** Collects Kotlin declarations and writes one aggregating KSP resource per mod. */ -private class LocalizationSymbolProcessor(private val codeGenerator: CodeGenerator) : SymbolProcessor { - private class ModDeclarations { - val entries = ArrayList() - val files = LinkedHashSet() - } - - private val mods = LinkedHashMap() - - override fun process(resolver: Resolver): List { - collect(resolver, Trans::class.java.name) { annotation, location, group, namespace -> - group.entries.add(entry(namespace, annotation["key"] as String, annotation, "@Trans $location")) - } - collect(resolver, TransVariants::class.java.name) { annotation, location, group, namespace -> - val prefix = annotation["keyPrefix"] as String - for (variant in annotation["value"] as List<*>) { - variant as KSAnnotation - val id = variant["id"] as String - group.entries.add(entry(namespace, LocalizationIndex.variantKey(prefix, id), variant, "@TransVariants $location [$id]")) - } - } - return emptyList() - } - - override fun finish() { - for ((modId, group) in mods) { - val dependencies = Dependencies(aggregating = true, *group.files.toTypedArray()) - val path = LocalizationIndex.path(modId, Frontend.KSP).removeSuffix(".bin") - val resource = codeGenerator.createNewFileByPath(dependencies, path, "bin") - DataOutputStream(resource.buffered()).use { LocalizationIndex.write(it, group.entries) } - } - } - - private inline fun collect(resolver: Resolver, annotationName: String, consume: (KSAnnotation, String, ModDeclarations, String) -> Unit) { - for (symbol in resolver.getSymbolsWithAnnotation(annotationName)) { - if (symbol.origin != Origin.KOTLIN) continue - val declaration = symbol as KSDeclaration - val annotation = declaration.annotations.first { it.annotationType.resolve().declaration.qualifiedName?.asString() == annotationName } - val modId = annotation["modId"] as String - val namespace = (annotation["namespace"] as String).ifEmpty { modId } - val file = declaration.containingFile!! - val group = mods.getOrPut(modId, ::ModDeclarations) - group.files.add(file) - consume(annotation, location(declaration, file), group, namespace) - } - } - - private fun entry(namespace: String, key: String, annotation: KSAnnotation, location: String): Entry { - val translations = annotation["translations"] as List<*> - val texts = if (translations.isEmpty()) { - emptyMap() - } else { - EnumMap(MinecraftLocale::class.java).apply { - for (value in translations) { - value as KSAnnotation - val locale = (value["locale"] as KSClassDeclaration).simpleName.asString() - put(MinecraftLocale.valueOf(locale), value["text"] as String) - } - } - } - return Entry(namespace, key, annotation["source"] as String, location, texts) - } - - private fun location(declaration: KSDeclaration, file: KSFile): String { - val owner = declaration.parentDeclaration - val name = if (declaration is KSPropertyDeclaration && owner != null) { - "${owner.qualifiedName?.asString()}#${declaration.simpleName.asString()}" - } else { - declaration.qualifiedName?.asString() ?: declaration.simpleName.asString() - } - val line = (declaration.location as FileLocation).lineNumber - return "$name (${file.fileName}:$line)" - } - - private operator fun KSAnnotation.get(name: String): Any? = arguments.first { it.name?.asString() == name }.value -} diff --git a/localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors b/localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors deleted file mode 100644 index 13c2ec4..0000000 --- a/localization-processor/src/main/resources/META-INF/gradle/incremental.annotation.processors +++ /dev/null @@ -1 +0,0 @@ -com.modularmc.registrate.localization.processor.TranslationProcessor,aggregating diff --git a/localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider b/localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider deleted file mode 100644 index 273c3e1..0000000 --- a/localization-processor/src/main/resources/META-INF/services/com.google.devtools.ksp.processing.SymbolProcessorProvider +++ /dev/null @@ -1 +0,0 @@ -com.modularmc.registrate.localization.processor.ksp.LocalizationSymbolProcessorProvider diff --git a/localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor deleted file mode 100644 index 14f4a6f..0000000 --- a/localization-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor +++ /dev/null @@ -1 +0,0 @@ -com.modularmc.registrate.localization.processor.TranslationProcessor diff --git a/settings.gradle b/settings.gradle index 2e5a23a..4e03807 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,9 +1,6 @@ pluginManagement { repositories { mavenLocal() - mavenCentral { - content { includeGroup("com.google.devtools.ksp") } - } gradlePluginPortal() maven { url = 'https://maven.neoforged.net/releases' } maven { url = "https://maven.quiltmc.org/repository/release" } @@ -26,4 +23,4 @@ dependencyResolutionManagement { } rootProject.name = "${mod_id}" -include 'localization-processor' +include 'test' diff --git a/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt b/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt index 5a75bf7..76071e3 100644 --- a/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt +++ b/src/main/java/com/modularmc/registrate/AbstractRegistrate.kt @@ -19,6 +19,7 @@ import com.modularmc.registrate.builders.base.AbstractBuilder import com.modularmc.registrate.builders.base.Builder import com.modularmc.registrate.builders.base.BuilderCallback import com.modularmc.registrate.builders.base.NoConfigBuilder +import com.modularmc.registrate.export.RegistrateExportBuilder import com.modularmc.registrate.internal.RegistrationTracker import com.modularmc.registrate.internal.event.OneTimeEventReceiver.Companion.addModListener import com.modularmc.registrate.internal.lifecycle.RegistrateLifecycle @@ -26,6 +27,7 @@ import com.modularmc.registrate.internal.util.DebugMarkers import com.modularmc.registrate.internal.util.RegistrateLogger.core import com.modularmc.registrate.internal.util.RegistrateLogger.datagen import com.modularmc.registrate.internal.util.RegistrateLogger.modMessage +import com.modularmc.registrate.localization.DeclarationDefaults import com.modularmc.registrate.localization.EntryLocalization import com.modularmc.registrate.localization.ImportedTranslation import com.modularmc.registrate.localization.LocalizationDeclaration @@ -95,6 +97,7 @@ import it.unimi.dsi.fastutil.objects.ObjectArrayList import org.apache.commons.lang3.tuple.Pair import org.apache.logging.log4j.Level +import java.nio.file.Path import java.util.EnumMap import java.util.Optional import java.util.concurrent.ConcurrentLinkedQueue @@ -548,6 +551,15 @@ abstract class AbstractRegistrate> protected construct return self() } + /** Adds a callback before other callbacks registered for the same generator type. */ + open fun addDataGeneratorFirst(type: GeneratorType, cons: NonNullConsumer): S { + if (dataGeneration.get()) { + check(provider == null) { "Cannot add data generator after construction of root generator" } + datagens.get(type).addFirst(cons) + } + return self() + } + open val dataGenInitializer: DataProviderInitializer by lazy(LazyThreadSafetyMode.NONE, ::DataProviderInitializer) @JvmRecord @@ -557,6 +569,8 @@ abstract class AbstractRegistrate> protected construct private val generatedLang = ConcurrentLinkedQueue() private val importedTranslations = ObjectArrayList() private var sourceLocale: MinecraftLocale? = null + private var defaultLocalization = DeclarationDefaults.EMPTY + private var localizationExportPath: Path? = null private val terminology = Terminology() private val localeDerivations = EnumMap(MinecraftLocale::class.java) @@ -566,6 +580,23 @@ abstract class AbstractRegistrate> protected construct return self() } + /** Starts a chain for export files created during this Registrate's DataGen run. */ + open fun export(): RegistrateExportBuilder = RegistrateExportBuilder(this) + + internal fun requestLocalizationExport(path: Path) { + localizationExportPath = path + } + + internal fun localizationExportPath(): Path? = localizationExportPath + + /** Sets the defaults applied to localization declarations created after this call. */ + open fun localizationDefaults(defaults: DeclarationDefaults): S { + defaultLocalization = defaults + return self() + } + + internal fun localizationDefaultValues(): DeclarationDefaults = defaultLocalization + /** Returns the source locale after validating this mod's configuration. */ open fun requireSourceLocale(): MinecraftLocale { val locale = sourceLocale @@ -596,7 +627,7 @@ abstract class AbstractRegistrate> protected construct if (localeDerivations.isNotEmpty()) registry.configureDerivations(terminology(), modid, localeDerivations.values) } - open fun collectRawTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { + internal fun collectRawTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { for (translation in extraLang) { collectRawTranslation(registry, locale, translation) } @@ -659,7 +690,7 @@ abstract class AbstractRegistrate> protected construct private fun addRawLang(key: String, value: String, kind: TranslationSource.Kind): MutableComponent { if (dataGeneration.get()) { - addLocalization(TranslationKey(modid, key), sourceText(value), kind) + addLocalization(TranslationKey(modid, key), sourceText(value, defaultLocalization), kind) } return Component.translatable(key) } @@ -669,7 +700,7 @@ abstract class AbstractRegistrate> protected construct if (dataGeneration.get()) { val builder = LocalizationDeclaration.Builder() configure.accept(builder) - addLocalization(key, builder.build(), TranslationSource.Kind.DECLARED) + addLocalization(key, builder.build(defaultLocalization), TranslationSource.Kind.DECLARED) } return Component.translatable(key.value) } @@ -687,7 +718,7 @@ abstract class AbstractRegistrate> protected construct } } - open fun collectEntryTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { + internal fun collectEntryTranslations(registry: TranslationRegistry, locale: MinecraftLocale) { registrationTracker.forEachLocalization { entry, localization -> if (localization.kind == TranslationSource.Kind.AUTOMATIC && locale != MinecraftLocale.EN_US) { return@forEachLocalization diff --git a/src/main/java/com/modularmc/registrate/RegistrateLib.java b/src/main/java/com/modularmc/registrate/RegistrateLib.java index f992d5f..3846d5b 100644 --- a/src/main/java/com/modularmc/registrate/RegistrateLib.java +++ b/src/main/java/com/modularmc/registrate/RegistrateLib.java @@ -13,7 +13,7 @@ * This library is intended to load as its own NeoForge mod so downstream * mods can depend on it as a prerequisite during development. Integration * scenarios, sample registrations, and visual validation belong in the test - * harness under {@code src/test}. + * harness under {@code test/src/main}. */ @Mod(RegistrateLib.MOD_ID) public final class RegistrateLib { diff --git a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt index b5fced6..7cc5457 100644 --- a/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt +++ b/src/main/java/com/modularmc/registrate/builders/base/AbstractBuilder.kt @@ -107,14 +107,18 @@ abstract class AbstractBuilder): S = defaultLang(langKeyProvider, name) - open fun lang(langKeyProvider: NonNullFunction, name: String): S = localization(langKeyProvider, { LocalizationDeclaration.sourceText(name) }, Kind.DECLARED) + open fun lang(langKeyProvider: NonNullFunction, name: String): S = localization( + langKeyProvider, + { LocalizationDeclaration.sourceText(name, owner.localizationDefaultValues()) }, + Kind.DECLARED, + ) protected open fun defaultLang(key: NonNullFunction, path: String): S = - localization(key, { LocalizationDeclaration.sourceText(RegistrateLangProvider.toEnglishName(path)) }, Kind.AUTOMATIC) + localization(key, { LocalizationDeclaration.sourceText(RegistrateLangProvider.toEnglishName(path), owner.localizationDefaultValues()) }, Kind.AUTOMATIC) /** Declares text whose translation key is read from the registered object during DataGen. */ open fun localization(key: NonNullFunction, configure: Consumer): S { - val declaration = LocalizationDeclaration.Builder().also(configure::accept).build() + val declaration = LocalizationDeclaration.Builder().also(configure::accept).build(owner.localizationDefaultValues()) return localization(key, { declaration }, Kind.DECLARED) } diff --git a/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt b/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt new file mode 100644 index 0000000..cf573b9 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/export/RegistrateExportBuilder.kt @@ -0,0 +1,10 @@ +package com.modularmc.registrate.export + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.localization.export.LocalizationExportBuilder + +/** Starts export builders for the data produced by one Registrate instance. */ +class RegistrateExportBuilder internal constructor(private val registrate: AbstractRegistrate<*>) { + /** Configures localization exchange output for the owning mod. */ + fun localization(): LocalizationExportBuilder = LocalizationExportBuilder(registrate) +} diff --git a/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt b/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt index 32e8908..094df26 100644 --- a/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt +++ b/src/main/java/com/modularmc/registrate/localization/DeclarationDefaults.kt @@ -43,7 +43,7 @@ data class DeclarationDefaults @JvmOverloads constructor( require(existing == null || existing == term) { "Included defaults disagree on glossary term '${term.id}'" } } defaults.type?.let { candidate -> - require(type == null || type == candidate) { "Included defaults disagree on text type: $type and $candidate" } + require(type == null || type == candidate) { "Included defaults disagree on text type: ${type?.id} and ${candidate.id}" } type = candidate } } diff --git a/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt b/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt index 5bc827b..9757692 100644 --- a/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt +++ b/src/main/java/com/modularmc/registrate/localization/LocalizationDeclaration.kt @@ -51,19 +51,28 @@ data class LocalizationDeclaration @JvmOverloads constructor( fun units(vararg ids: String) = apply { unitIds = ids.asList() } - fun build() = LocalizationDeclaration( - source, - translations?.toMap() ?: emptyMap(), - domains ?: defaults.domains, - type ?: defaults.type, - glossary ?: defaults.glossary, - glossaryIds ?: defaults.glossaryIds, - unitIds ?: defaults.unitIds, - ) + fun build(): LocalizationDeclaration = build(DeclarationDefaults.EMPTY) + + fun build(moduleDefaults: DeclarationDefaults): LocalizationDeclaration { + val entryGlossary = if (defaults.glossary.isEmpty() && defaults.glossaryIds.isEmpty()) moduleDefaults else defaults + return LocalizationDeclaration( + source, + translations?.toMap() ?: emptyMap(), + domains ?: defaults.domains.ifEmpty { moduleDefaults.domains }, + type ?: defaults.type ?: moduleDefaults.type, + glossary ?: entryGlossary.glossary, + glossaryIds ?: entryGlossary.glossaryIds, + unitIds ?: defaults.unitIds.ifEmpty { moduleDefaults.unitIds }, + ) + } } companion object { @JvmStatic fun sourceText(source: String) = LocalizationDeclaration(source, emptyMap(), emptyList(), null, emptyList()) + + @JvmStatic + fun sourceText(source: String, defaults: DeclarationDefaults) = + LocalizationDeclaration(source, emptyMap(), defaults.domains, defaults.type, defaults.glossary, defaults.glossaryIds, defaults.unitIds) } } diff --git a/src/main/java/com/modularmc/registrate/localization/TextType.kt b/src/main/java/com/modularmc/registrate/localization/TextType.kt index 9568003..4d61e84 100644 --- a/src/main/java/com/modularmc/registrate/localization/TextType.kt +++ b/src/main/java/com/modularmc/registrate/localization/TextType.kt @@ -1,19 +1,35 @@ package com.modularmc.registrate.localization -/** The role of a piece of text in the mod. */ -enum class TextType { - ITEM, - BLOCK, - MACHINE, - MATERIAL, - PROCESS, - REACTION, - PHENOMENON, - ASTRONOMICAL_OBJECT, - BIOME, - RESEARCH, - STATISTIC, - DESCRIPTION, - TOOLTIP, - GUI_LABEL, +/** A stable, extensible role for text in a mod. */ +@JvmRecord +data class TextType(val id: String) { + companion object { + @JvmField val ITEM = TextType("item") + + @JvmField val BLOCK = TextType("block") + + @JvmField val MACHINE = TextType("machine") + + @JvmField val MATERIAL = TextType("material") + + @JvmField val PROCESS = TextType("process") + + @JvmField val REACTION = TextType("reaction") + + @JvmField val PHENOMENON = TextType("phenomenon") + + @JvmField val ASTRONOMICAL_OBJECT = TextType("astronomical_object") + + @JvmField val BIOME = TextType("biome") + + @JvmField val RESEARCH = TextType("research") + + @JvmField val STATISTIC = TextType("statistic") + + @JvmField val DESCRIPTION = TextType("description") + + @JvmField val TOOLTIP = TextType("tooltip") + + @JvmField val GUI_LABEL = TextType("gui_label") + } } diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt b/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt new file mode 100644 index 0000000..e19dd93 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/annotation/AnnotatedTranslations.kt @@ -0,0 +1,88 @@ +package com.modularmc.registrate.localization.annotation + +import com.modularmc.registrate.AbstractRegistrate +import com.modularmc.registrate.localization.LocalizationDeclaration +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource +import com.modularmc.registrate.localization.TranslationSource.Kind.DECLARED +import com.modularmc.registrate.localization.resolution.TranslationRegistry + +import net.neoforged.fml.ModList +import net.neoforged.fml.loading.modscan.ModAnnotation.EnumHolder +import net.neoforged.neoforgespi.language.ModFileScanData.AnnotationData + +import org.objectweb.asm.Type + +import java.lang.annotation.ElementType +import java.util.EnumMap + +/** Reads declarations from the owning mod file's NeoForge scan data during DataGen. */ +internal object AnnotatedTranslations { + private val trans = Type.getType(Trans::class.java) + private val transVariants = Type.getType(TransVariants::class.java) + + fun collect(owner: AbstractRegistrate<*>, locale: MinecraftLocale, registry: TranslationRegistry) { + val modId = owner.modid + val defaults = owner.localizationDefaultValues() + val terminology = owner.terminology() + val modFile = ModList.get().getModFileById(modId) + val singleModFile = modFile.mods.size == 1 + + fun add(namespace: String, key: String, values: Map<*, *>, location: String) { + val declaration = LocalizationDeclaration( + values["source"] as String, + translations(values), + defaults.domains, + defaults.type, + defaults.glossary, + defaults.glossaryIds, + defaults.unitIds, + ) + registry.add(TranslationKey(namespace, key), locale, declaration, TranslationSource(DECLARED, location), terminology) + } + + for (annotation in modFile.file.scanResult.annotations) { + val type = annotation.annotationType() + if (type != trans && type != transVariants) continue + val values = annotation.annotationData() + val declaredModId = values["modId"] as String? + if (declaredModId.isNullOrEmpty()) { + check(singleModFile) { "${annotation.location()} must declare modId because its file contains multiple mods" } + } else if (declaredModId != modId) { + continue + } + + val namespace = (values["namespace"] as String?).orEmpty().ifEmpty { modId } + val location = annotation.location() + if (type == trans) { + add(namespace, values["key"] as String, values, "@Trans $location") + } else { + val keyPrefix = values["keyPrefix"] as String + val prefix = if (keyPrefix.endsWith('.')) keyPrefix else "$keyPrefix." + for (variant in values["value"] as List<*>) { + variant as Map<*, *> + val id = variant["id"] as String + add(namespace, "$prefix$id", variant, "@TransVariants $location [$id]") + } + } + } + } + + private fun AnnotationData.location(): String { + val className = clazz().className + return if (targetType() == ElementType.FIELD) "$className#${memberName()}" else className + } + + private fun translations(values: Map<*, *>): Map { + val translations = values["translations"] as List<*>? + if (translations.isNullOrEmpty()) return emptyMap() + val texts = EnumMap(MinecraftLocale::class.java) + for (translation in translations) { + translation as Map<*, *> + val locale = MinecraftLocale.valueOf((translation["locale"] as EnumHolder).value()) + texts[locale] = translation["text"] as String + } + return texts + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt b/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt index ed42984..f2eabfe 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/Trans.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization.annotation -/** Adds one translation key to the named mod's language declarations. */ +/** Adds one translation key. [modId] may be omitted when the file declares a single mod. */ @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS, AnnotationTarget.FIELD) -annotation class Trans(val modId: String, val key: String, val source: String, val namespace: String = "", val translations: Array = []) +annotation class Trans(val modId: String = "", val key: String, val source: String, val namespace: String = "", val translations: Array = []) diff --git a/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt b/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt index 1be3f31..cf8d6a9 100644 --- a/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt +++ b/src/main/java/com/modularmc/registrate/localization/annotation/TransVariants.kt @@ -1,6 +1,6 @@ package com.modularmc.registrate.localization.annotation -/** Adds a translation for each variant under the given key prefix. */ +/** Adds a translation for each variant. [modId] may be omitted when the file declares a single mod. */ @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.CLASS, AnnotationTarget.FIELD) -annotation class TransVariants(val modId: String, val keyPrefix: String, val value: Array, val namespace: String = "") +annotation class TransVariants(val modId: String = "", val keyPrefix: String, val value: Array, val namespace: String = "") diff --git a/src/main/java/com/modularmc/registrate/localization/export/LocalizationDocument.kt b/src/main/java/com/modularmc/registrate/localization/export/LocalizationDocument.kt new file mode 100644 index 0000000..c102ff3 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/export/LocalizationDocument.kt @@ -0,0 +1,24 @@ +package com.modularmc.registrate.localization.export + +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TranslationKey +import com.modularmc.registrate.localization.TranslationSource + +import it.unimi.dsi.fastutil.ints.Int2IntMap +import it.unimi.dsi.fastutil.objects.ObjectArrayList + +internal class LocalizationDocument(val modId: String, val sourceLocale: MinecraftLocale, val entries: ObjectArrayList) { + internal class Entry( + val key: TranslationKey, + val sourceText: String, + val sourceRevision: String, + val domains: ObjectArrayList, + val type: String?, + val glossaryIds: ObjectArrayList, + val unitIds: ObjectArrayList, + val placeholderSignature: Int2IntMap, + val translations: ObjectArrayList, + ) + + internal class Translation(val locale: MinecraftLocale, val text: String, val source: TranslationSource, val sourceRevision: String, val status: String?, val locked: Boolean) +} diff --git a/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt new file mode 100644 index 0000000..c472e22 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportBuilder.kt @@ -0,0 +1,21 @@ +package com.modularmc.registrate.localization.export + +import com.modularmc.registrate.AbstractRegistrate + +import java.nio.file.Path + +/** Requests a per-mod localization exchange document during DataGen. */ +class LocalizationExportBuilder internal constructor(private val registrate: AbstractRegistrate<*>) { + private var outputPath: Path? = null + + /** Sets the exact JSON file path used for this mod's export. */ + fun path(path: Path): LocalizationExportBuilder { + outputPath = path.toAbsolutePath().normalize() + return this + } + + /** Registers localization export after the owning mod's language declarations have been collected. */ + fun build() { + registrate.requestLocalizationExport(requireNotNull(outputPath) { "Set the localization export path before build" }) + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportOutput.kt b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportOutput.kt new file mode 100644 index 0000000..a5e8bef --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/export/LocalizationExportOutput.kt @@ -0,0 +1,82 @@ +package com.modularmc.registrate.localization.export + +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.TranslationSource + +import net.minecraft.data.CachedOutput +import net.minecraft.data.DataProvider + +import com.google.gson.JsonArray +import com.google.gson.JsonNull +import com.google.gson.JsonObject +import it.unimi.dsi.fastutil.ints.Int2IntMaps + +import java.nio.file.Path +import java.util.Locale +import java.util.concurrent.CompletableFuture + +internal object LocalizationExportOutput { + fun write(cache: CachedOutput, path: Path, document: LocalizationDocument): CompletableFuture<*> = DataProvider.saveStable(cache, toJson(document), path) + + private fun toJson(document: LocalizationDocument): JsonObject { + val json = JsonObject() + json.addProperty("formatVersion", 1) + json.addProperty("modId", document.modId) + json.addProperty("sourceLocale", document.sourceLocale.code()) + val entries = JsonArray() + for (entry in document.entries) entries.add(entry(entry, document.sourceLocale)) + json.add("entries", entries) + return json + } + + private fun entry(value: LocalizationDocument.Entry, sourceLocale: MinecraftLocale): JsonObject { + val json = JsonObject() + json.addProperty("namespace", value.key.namespace) + json.addProperty("key", value.key.value) + val source = JsonObject() + source.addProperty("locale", sourceLocale.code()) + source.addProperty("text", value.sourceText) + source.addProperty("revision", value.sourceRevision) + json.add("source", source) + val context = JsonObject() + context.add("domains", strings(value.domains)) + if (value.type == null) context.add("type", JsonNull.INSTANCE) else context.addProperty("type", value.type) + context.add("glossaryIds", strings(value.glossaryIds)) + context.add("unitIds", strings(value.unitIds)) + val placeholders = JsonObject() + val indexes = IntArray(value.placeholderSignature.size) + val iterator = Int2IntMaps.fastIterator(value.placeholderSignature) + var index = 0 + while (iterator.hasNext()) indexes[index++] = iterator.next().intKey + indexes.sort() + for (argument in indexes) placeholders.addProperty(argument.toString(), value.placeholderSignature.get(argument)) + context.add("placeholderSignature", placeholders) + json.add("context", context) + val translations = JsonArray() + for (translation in value.translations) translations.add(translation(translation)) + json.add("translations", translations) + return json + } + + private fun translation(value: LocalizationDocument.Translation): JsonObject { + val json = JsonObject() + json.addProperty("locale", value.locale.code()) + json.addProperty("text", value.text) + val source = JsonObject() + source.addProperty("kind", sourceKind(value.source.kind)) + source.addProperty("location", value.source.location) + json.add("source", source) + json.addProperty("sourceRevision", value.sourceRevision) + if (value.status == null) json.add("status", JsonNull.INSTANCE) else json.addProperty("status", value.status) + json.addProperty("locked", value.locked) + return json + } + + private fun strings(values: Iterable): JsonArray { + val array = JsonArray() + for (value in values) array.add(value) + return array + } + + private fun sourceKind(kind: TranslationSource.Kind): String = kind.name.lowercase(Locale.ROOT) +} diff --git a/src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt b/src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt deleted file mode 100644 index 88d3f8e..0000000 --- a/src/main/java/com/modularmc/registrate/localization/index/IndexedTranslations.kt +++ /dev/null @@ -1,43 +0,0 @@ -package com.modularmc.registrate.localization.index - -import com.modularmc.registrate.localization.LocalizationDeclaration -import com.modularmc.registrate.localization.MinecraftLocale -import com.modularmc.registrate.localization.TranslationKey -import com.modularmc.registrate.localization.TranslationSource -import com.modularmc.registrate.localization.resolution.TranslationRegistry -import com.modularmc.registrate.localization.terminology.Terminology - -import net.neoforged.fml.ModList - -import java.io.DataInputStream -import java.io.IOException -import java.io.UncheckedIOException - -/** Loads the declarations compiled into a mod's own resources during DataGen. */ -object IndexedTranslations { - @JvmStatic - @JvmOverloads - fun collect(modId: String, locale: MinecraftLocale, registry: TranslationRegistry, terminology: Terminology = Terminology.EMPTY) { - val contents = ModList.get().getModFileById(modId).file.contents - for (frontend in LocalizationIndex.Frontend.entries) { - val index = LocalizationIndex.path(modId, frontend) - - try { - val stream = contents.openFile(index) ?: continue - DataInputStream(stream.buffered()).use { input -> - LocalizationIndex.read(input) { entry -> - registry.add( - TranslationKey(entry.namespace, entry.key), - locale, - LocalizationDeclaration(entry.source, entry.translations, emptyList(), null, emptyList()), - TranslationSource(TranslationSource.Kind.DECLARED, entry.location), - terminology, - ) - } - } - } catch (error: IOException) { - throw UncheckedIOException("[$modId] Reading localization index $index", error) - } - } - } -} diff --git a/src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt b/src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt deleted file mode 100644 index ed1ff17..0000000 --- a/src/main/java/com/modularmc/registrate/localization/index/LocalizationIndex.kt +++ /dev/null @@ -1,90 +0,0 @@ -package com.modularmc.registrate.localization.index - -import com.modularmc.registrate.localization.MinecraftLocale - -import java.io.DataInputStream -import java.io.DataOutputStream -import java.io.IOException -import java.util.EnumMap -import java.util.function.Consumer - -/** The declaration protocol used by compiler frontends and the DataGen reader. */ -object LocalizationIndex { - private const val MAGIC = -0x524c494e - private const val VERSION = 1 - - private val entryOrder = compareBy(Entry::namespace, Entry::key, Entry::location) - - enum class Frontend(val suffix: String) { - JAVAC(""), - KSP(".ksp"), - } - - @JvmRecord - data class Entry(val namespace: String, val key: String, val source: String, val location: String, val translations: Map) - - @JvmStatic - @JvmOverloads - fun path(modId: String, frontend: Frontend = Frontend.JAVAC): String = "META-INF/registratelib/localization/$modId${frontend.suffix}.bin" - - @JvmStatic - fun variantKey(prefix: String, id: String): String = if (prefix.endsWith('.')) "$prefix$id" else "$prefix.$id" - - @JvmStatic - @Throws(IOException::class) - fun write(output: DataOutputStream, entries: Collection) { - output.writeInt(MAGIC) - output.writeInt(VERSION) - output.writeInt(entries.size) - for ((namespace, key, source, location, translations) in entries.sortedWith(entryOrder)) { - output.writeUTF(namespace) - output.writeUTF(key) - output.writeUTF(source) - output.writeUTF(location) - output.writeInt(translations.size) - for ((locale, text) in translations) { - output.writeUTF(locale.name) - output.writeUTF(text) - } - } - } - - @JvmStatic - @Throws(IOException::class) - fun read(input: DataInputStream, consumer: Consumer) { - val leading = input.readInt() - val count = if (leading == MAGIC) { - val version = input.readInt() - if (version != VERSION) { - throw IOException("Unsupported localization index version $version") - } - input.readInt() - } else { - leading // Version 0 began with the entry count. - } - - if (count < 0) { - throw IOException("Invalid localization index entry count $count") - } - repeat(count) { - val namespace = input.readUTF() - val key = input.readUTF() - val source = input.readUTF() - val location = input.readUTF() - val targetCount = input.readInt() - if (targetCount < 0) { - throw IOException("Invalid translation count $targetCount for $namespace/$key") - } - val translations = if (targetCount == 0) { - emptyMap() - } else { - EnumMap(MinecraftLocale::class.java).apply { - repeat(targetCount) { - put(MinecraftLocale.valueOf(input.readUTF()), input.readUTF()) - } - } - } - consumer.accept(Entry(namespace, key, source, location, translations)) - } - } -} diff --git a/src/main/java/com/modularmc/registrate/localization/locale/BritishEnglish.kt b/src/main/java/com/modularmc/registrate/localization/locale/BritishEnglish.kt new file mode 100644 index 0000000..ad19c91 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/locale/BritishEnglish.kt @@ -0,0 +1,75 @@ +package com.modularmc.registrate.localization.locale + +import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap + +import java.util.regex.Pattern + +internal object BritishEnglish { + private val words = Object2ObjectOpenHashMap(42).apply { + put("color", "colour") + put("colors", "colours") + put("colored", "coloured") + put("coloring", "colouring") + put("colorize", "colourise") + put("colorized", "colourised") + put("colorizes", "colourises") + put("colorizing", "colourising") + put("favor", "favour") + put("favors", "favours") + put("favorite", "favourite") + put("favorites", "favourites") + put("honor", "honour") + put("honors", "honours") + put("honored", "honoured") + put("honoring", "honouring") + put("labor", "labour") + put("neighbor", "neighbour") + put("neighbors", "neighbours") + put("rumor", "rumour") + put("center", "centre") + put("centers", "centres") + put("centered", "centred") + put("centering", "centring") + put("meter", "metre") + put("meters", "metres") + put("liter", "litre") + put("liters", "litres") + put("theater", "theatre") + put("theaters", "theatres") + put("gray", "grey") + put("grays", "greys") + put("defense", "defence") + put("offense", "offence") + put("organize", "organise") + put("organizes", "organises") + put("organized", "organised") + put("organizing", "organising") + put("analyze", "analyse") + put("analyzes", "analyses") + put("analyzed", "analysed") + put("analyzing", "analysing") + } + private val wordsPattern = Pattern.compile("[A-Za-z]+") + + fun convert(text: String): String { + val matcher = wordsPattern.matcher(text) + var converted: StringBuilder? = null + var copiedUntil = 0 + while (matcher.find()) { + val word = matcher.group() + val replacement = words[word.lowercase()] ?: continue + val output = converted ?: StringBuilder(text.length).also { converted = it } + output.append(text, copiedUntil, matcher.start()) + output.append(caseLike(word, replacement)) + copiedUntil = matcher.end() + } + val output = converted ?: return text + return output.append(text, copiedUntil, text.length).toString() + } + + private fun caseLike(word: String, replacement: String): String = when { + word.all(Char::isUpperCase) -> replacement.uppercase() + word.first().isUpperCase() -> replacement.replaceFirstChar(Char::uppercase) + else -> replacement + } +} diff --git a/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt index ee1a5db..bea8ca9 100644 --- a/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt +++ b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivation.kt @@ -2,8 +2,11 @@ package com.modularmc.registrate.localization.locale import com.modularmc.registrate.localization.LocalizationDeclaration import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.MinecraftLocale.EN_GB import com.modularmc.registrate.localization.MinecraftLocale.EN_UD import com.modularmc.registrate.localization.MinecraftLocale.EN_US +import com.modularmc.registrate.localization.MinecraftLocale.ZH_CN +import com.modularmc.registrate.localization.MinecraftLocale.ZH_TW import com.modularmc.registrate.localization.TranslationKey import com.modularmc.registrate.localization.TranslationSource.Kind import com.modularmc.registrate.localization.resolution.MinecraftTextFormat @@ -29,6 +32,8 @@ class LocaleDerivation private constructor( companion object { internal val UPSIDE_DOWN = LocaleDerivation(EN_US, EN_UD, Kind.VARIANT) { text, symbols, _, _ -> MinecraftTextFormat.upsideDown(text, symbols) } + internal val BRITISH_ENGLISH = LocaleDerivation(EN_US, EN_GB) { text, _ -> BritishEnglish.convert(text) } + internal val TRADITIONAL_CHINESE = LocaleDerivation(ZH_CN, ZH_TW) { text, _ -> TraditionalChinese.convert(text) } /** Copies the resolved input as a display fallback for a missing target. */ @JvmStatic diff --git a/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivationGraph.kt b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivationGraph.kt index b90b66b..904cd0f 100644 --- a/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivationGraph.kt +++ b/src/main/java/com/modularmc/registrate/localization/locale/LocaleDerivationGraph.kt @@ -1,7 +1,9 @@ package com.modularmc.registrate.localization.locale import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.MinecraftLocale.EN_GB import com.modularmc.registrate.localization.MinecraftLocale.EN_UD +import com.modularmc.registrate.localization.MinecraftLocale.ZH_TW import it.unimi.dsi.fastutil.objects.ObjectArrayList @@ -14,6 +16,8 @@ internal class LocaleDerivationGraph(modId: String, derivations: Collection(MinecraftLocale::class.java) byTarget[EN_UD] = LocaleDerivation.UPSIDE_DOWN + byTarget[EN_GB] = LocaleDerivation.BRITISH_ENGLISH + byTarget[ZH_TW] = LocaleDerivation.TRADITIONAL_CHINESE for (derivation in derivations) byTarget[derivation.output] = derivation val done = EnumSet.noneOf(MinecraftLocale::class.java) diff --git a/src/main/java/com/modularmc/registrate/localization/locale/TraditionalChinese.kt b/src/main/java/com/modularmc/registrate/localization/locale/TraditionalChinese.kt new file mode 100644 index 0000000..82b49a2 --- /dev/null +++ b/src/main/java/com/modularmc/registrate/localization/locale/TraditionalChinese.kt @@ -0,0 +1,9 @@ +package com.modularmc.registrate.localization.locale + +import com.ibm.icu.text.Transliterator + +internal object TraditionalChinese { + private val transliterator = ThreadLocal.withInitial { Transliterator.getInstance("Simplified-Traditional") } + + fun convert(text: String): String = transliterator.get().transliterate(text) +} diff --git a/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt b/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt index 3e83be3..b81e3ce 100644 --- a/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt +++ b/src/main/java/com/modularmc/registrate/localization/resolution/TranslationRegistry.kt @@ -9,6 +9,7 @@ import com.modularmc.registrate.localization.TranslationKey import com.modularmc.registrate.localization.TranslationSource import com.modularmc.registrate.localization.TranslationSource.Kind import com.modularmc.registrate.localization.TranslationStatus.STALE +import com.modularmc.registrate.localization.export.LocalizationDocument import com.modularmc.registrate.localization.locale.LocaleDerivation import com.modularmc.registrate.localization.locale.LocaleDerivationGraph import com.modularmc.registrate.localization.terminology.Terminology @@ -27,7 +28,7 @@ import java.util.TreeMap import java.util.function.Consumer /** Resolves the declarations for one DataGen output before the language provider writes any files. */ -class TranslationRegistry { +internal class TranslationRegistry(private val parent: TranslationRegistry? = null) { private val selections = Object2ObjectLinkedOpenHashMap() private val imports = ObjectArrayList() private val declarations = Reference2ObjectOpenHashMap>() @@ -52,8 +53,21 @@ class TranslationRegistry { } } + private class Resolved( + val imported: Object2ObjectMap, + val glossary: Object2ObjectLinkedOpenHashMap, + val glossaryTerms: MutableMap, + val variants: Object2ObjectLinkedOpenHashMap, + val files: Map>, + ) + + private class ExportEntry(val candidate: Candidate) { + val sourceRevision = SourceRevision.of(candidate.declaration.localization.source).value + val translations = ObjectArrayList() + } + private class Selection(private val key: EntryKey, var winner: Candidate) { - private var ties: MutableList? = null + private var ties: ObjectArrayList? = null private var signature: Int2IntMap? = null fun add(candidate: Candidate) { @@ -63,7 +77,7 @@ class TranslationRegistry { ties = null signature = null } else if (precedence == 0) { - val candidates = ties ?: ArrayList(1).also { ties = it } + val candidates = ties ?: ObjectArrayList(1).also { ties = it } candidates.add(candidate) } } @@ -111,6 +125,7 @@ class TranslationRegistry { for ((target, text) in declaration.translations) { selections.add(EntryKey(key, target), Candidate(text, source, context, original)) } + parent?.add(key, locale, declaration, source, terminology) } internal fun addImported(sourceLocale: MinecraftLocale, translation: ImportedTranslation, terminology: Terminology) { @@ -121,10 +136,12 @@ class TranslationRegistry { val target = key.copy(locale = translation.locale) require(target != key) { "Imported translation $target at ${translation.location} uses the source locale" } imports.add(PendingImport(sourceLocale, translation, terminology)) + parent?.addImported(sourceLocale, translation, terminology) } internal fun configureDerivations(terminology: Terminology, modId: String, rules: Collection) { derivations[terminology] = LocaleDerivationGraph(modId, rules) + parent?.configureDerivations(terminology, modId, rules) } private fun Object2ObjectLinkedOpenHashMap.add(key: EntryKey, candidate: Candidate): Selection { @@ -138,24 +155,125 @@ class TranslationRegistry { /** Resolves language entries and, when requested, reports each matched import with its current status. */ @JvmOverloads - fun resolve(reportImport: Consumer? = null): Map> { - val imported = resolveImports(reportImport) + fun resolve(reportImport: Consumer? = null): Map> = resolveAll(reportImport).files + + internal fun export(modId: String, sourceLocale: MinecraftLocale): LocalizationDocument { + val resolved = resolveAll(reportWarnings = false) + val entries = Object2ObjectLinkedOpenHashMap() + for (owned in declarations.values) { + owned.object2ObjectEntrySet().fastForEach { (key, candidate) -> + if (key.locale == sourceLocale) entries.computeIfAbsent(key.key) { ExportEntry(candidate) } + } + } + + forEachSelection(resolved.imported) { key, selection -> + if (key.locale != sourceLocale) { + selection.forEachWinner { candidate -> + if (candidate.source.kind != Kind.IMPORTED) { + val exported = entries.getValue(key.key) + exported.translations.add(candidate.translation(key.locale, exported.sourceRevision)) + } + } + } + } + resolved.glossary.object2ObjectEntrySet().fastForEach { (key, selection) -> + if (key.locale != sourceLocale) { + selection.forEachWinner { candidate -> + val exported = entries.getValue(key.key) + exported.translations.add(candidate.translation(key.locale, exported.sourceRevision)) + } + } + } + resolved.variants.object2ObjectEntrySet().fastForEach { (key, selection) -> + if (key.locale != sourceLocale) { + selection.forEachWinner { candidate -> + val exported = entries.getValue(key.key) + exported.translations.add(candidate.translation(key.locale, exported.sourceRevision)) + } + } + } + for (pending in imports) { + val key = EntryKey(pending.translation.key, pending.sourceLocale) + val source = declarations[pending.terminology]!!.getValue(key) + val revision = importRevisions.getValue(source) + val translation = pending.translation.forRevision(revision) + entries.getValue(translation.key).translations.add( + LocalizationDocument.Translation( + translation.locale, + translation.text, + TranslationSource(Kind.IMPORTED, translation.location), + translation.sourceRevision.value, + translation.status.name.lowercase(), + translation.locked, + ), + ) + } + + val result = ObjectArrayList(entries.size) + entries.object2ObjectEntrySet().fastForEach { (key, exported) -> + val declaration = exported.candidate.declaration + val localization = declaration.localization + val glossaryIds = ObjectOpenHashSet(localization.glossary.size + localization.glossaryIds.size + 1) + for (term in localization.glossary) glossaryIds.add(term.id) + glossaryIds.addAll(localization.glossaryIds) + val unitIds = ObjectOpenHashSet(localization.unitIds) + resolved.glossaryTerms[declaration]?.let { term -> + glossaryIds.add(term.id) + unitIds.addAll(term.unitIds) + } + val domains = ObjectArrayList(localization.domains.size) + for (domain in localization.domains) domains.add(domain.id) + domains.sort() + val sortedGlossaryIds = ObjectArrayList(glossaryIds) + sortedGlossaryIds.sort() + val sortedUnitIds = ObjectArrayList(unitIds) + sortedUnitIds.sort() + exported.translations.sortWith(compareBy({ it.locale.code() }, { it.source.kind.name }, { it.source.location }, { it.text })) + result.add( + LocalizationDocument.Entry( + key, + localization.source, + exported.sourceRevision, + domains, + localization.type?.id, + sortedGlossaryIds, + sortedUnitIds, + MinecraftTextFormat.signature(localization.source), + exported.translations, + ), + ) + } + result.sortWith(compareBy({ it.key.namespace }, { it.key.value })) + return LocalizationDocument(modId, sourceLocale, result) + } + + private fun Candidate.translation(locale: MinecraftLocale, sourceRevision: String): LocalizationDocument.Translation = LocalizationDocument.Translation( + locale, + text, + source, + sourceRevision, + null, + false, + ) + + private fun resolveAll(reportImport: Consumer? = null, reportWarnings: Boolean = true): Resolved { + val imported = resolveImports(reportImport, reportWarnings) val files = Object2ObjectLinkedOpenHashMap>() forEachSelection(imported) { key, selection -> collectLanguageText(key, selection, files) } val glossaryTerms = Reference2ObjectOpenHashMap() - val glossary = collectGlossary(imported, glossaryTerms) + val glossary = collectGlossary(imported, glossaryTerms, reportWarnings) glossary.object2ObjectEntrySet().fastForEach { collectLanguageText(it.key, it.value, files) } val variants = collectDerivations(imported, glossary, glossaryTerms) variants.object2ObjectEntrySet().fastForEach { collectLanguageText(it.key, it.value, files) } - return files + return Resolved(imported, glossary, glossaryTerms, variants, files) } - private fun resolveImports(reportImport: Consumer?): Object2ObjectMap { + private fun resolveImports(reportImport: Consumer?, reportWarnings: Boolean): Object2ObjectMap { if (imports.isEmpty) return Object2ObjectMaps.emptyMap() val selected = Object2ObjectLinkedOpenHashMap() - val logger = datagen() + val logger = if (reportWarnings) datagen() else null for (pending in imports) { val key = EntryKey(pending.translation.key, pending.sourceLocale) val declarationCandidate = declarations[pending.terminology]!![key]!! @@ -167,7 +285,7 @@ class TranslationRegistry { val target = key.copy(locale = translation.locale) if (translation.status == STALE) { - logger.warn("Stale translation for {} at {} (reviewed revision {}, current revision {})", target, translation.location, translation.sourceRevision.value, revision.value) + logger?.warn("Stale translation for {} at {} (reviewed revision {}, current revision {})", target, translation.location, translation.sourceRevision.value, revision.value) if (!translation.locked) continue } val existing = selections[target] @@ -191,7 +309,11 @@ class TranslationRegistry { } } - private fun collectGlossary(imported: Object2ObjectMap, terms: MutableMap): Object2ObjectLinkedOpenHashMap { + private fun collectGlossary( + imported: Object2ObjectMap, + terms: MutableMap, + reportWarnings: Boolean, + ): Object2ObjectLinkedOpenHashMap { val glossary = Object2ObjectLinkedOpenHashMap() forEachSelection(imported) { key, selection -> selection.forEachWinner { candidate -> @@ -199,15 +321,17 @@ class TranslationRegistry { val declaration = candidate.declaration val term = declaration.terminology.resolveTerm(key.key, declaration.localization, candidate.source) ?: return@forEachWinner terms[declaration] = term - val source = TranslationSource(Kind.GLOSSARY, "${candidate.source.location} (glossary ${term.id})") - for ((locale, text) in term.preferredTranslations) { - if (locale == key.locale) continue - val target = key.copy(locale = locale) - val explicit = imported[target] ?: selections[target] - if (explicit == null) { - glossary.add(target, Candidate(text, source, declaration, selection)) - } else { - checkGlossaryText(target, term, text, explicit.winner) + for (synonym in declaration.terminology.synonyms(term)) { + val source = TranslationSource(Kind.GLOSSARY, "${candidate.source.location} (glossary ${synonym.id})") + for ((locale, text) in synonym.preferredTranslations) { + if (locale == key.locale) continue + val target = key.copy(locale = locale) + val explicit = imported[target] ?: selections[target] + if (explicit == null) { + glossary.add(target, Candidate(text, source, declaration, selection)) + } else { + checkGlossaryText(target, synonym, text, explicit.winner, reportWarnings) + } } } } @@ -260,11 +384,11 @@ class TranslationRegistry { return unitSymbols } - private fun checkGlossaryText(key: EntryKey, term: GlossaryTerm, preferred: String, candidate: Candidate) { + private fun checkGlossaryText(key: EntryKey, term: GlossaryTerm, preferred: String, candidate: Candidate, reportWarnings: Boolean) { val text = candidate.text val forbidden = term.forbiddenTranslations[key.locale]?.any { it.equals(text, ignoreCase = true) } == true val accepted = preferred.equals(text, ignoreCase = true) || term.acceptedTranslations[key.locale]?.any { it.equals(text, ignoreCase = true) } == true - if (forbidden || !accepted) { + if (reportWarnings && (forbidden || !accepted)) { datagen().warn("Glossary term {} for {} at {} prefers '{}', found '{}'", term.id, key, candidate.source.location, preferred, text) } } diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt index 65bbb5c..0d81355 100644 --- a/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Domain.kt @@ -1,19 +1,29 @@ package com.modularmc.registrate.localization.terminology -/** Built-in fields used to associate terms and localization declarations. */ -enum class Domain(private val id: String) { - CHEMISTRY("chemistry"), - PHYSICS("physics"), - ENERGY("energy"), - ASTRONOMY("astronomy"), - GEOGRAPHY("geography"), - GEOLOGY("geology"), - ENGINEERING("engineering"), - MATERIALS("materials"), - COMPUTING("computing"), - MAGIC("magic"), - ADVENTURE("adventure"), - ; - - fun id(): String = id +/** A stable, extensible field used to associate terms and localization declarations. */ +@JvmRecord +data class Domain(val id: String) { + companion object { + @JvmField val CHEMISTRY = Domain("chemistry") + + @JvmField val PHYSICS = Domain("physics") + + @JvmField val ENERGY = Domain("energy") + + @JvmField val ASTRONOMY = Domain("astronomy") + + @JvmField val GEOGRAPHY = Domain("geography") + + @JvmField val GEOLOGY = Domain("geology") + + @JvmField val ENGINEERING = Domain("engineering") + + @JvmField val MATERIALS = Domain("materials") + + @JvmField val COMPUTING = Domain("computing") + + @JvmField val MAGIC = Domain("magic") + + @JvmField val ADVENTURE = Domain("adventure") + } } diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt index 901578c..6743c5e 100644 --- a/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Glossary.kt @@ -1,6 +1,7 @@ package com.modularmc.registrate.localization.terminology import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm +import com.modularmc.registrate.localization.terminology.Terminology.TermRelation /** * Supplies terminology to a mod's [Terminology] from any storage format. @@ -16,4 +17,10 @@ interface Glossary { * The query uses locale-independent lowercase. An unmatched label returns an empty iterable. */ fun findBySource(normalizedSource: String): Iterable + + /** + * Returns terms directly related to the supplied term. `SYNONYM` results include both incoming and outgoing links. + * Implementations own the relation data and keep lookups stable throughout DataGen. + */ + fun findRelated(id: String, relation: TermRelation): Iterable } diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/IndexedGlossary.kt b/src/main/java/com/modularmc/registrate/localization/terminology/IndexedGlossary.kt index d173022..c9ab229 100644 --- a/src/main/java/com/modularmc/registrate/localization/terminology/IndexedGlossary.kt +++ b/src/main/java/com/modularmc/registrate/localization/terminology/IndexedGlossary.kt @@ -1,35 +1,80 @@ package com.modularmc.registrate.localization.terminology import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm +import com.modularmc.registrate.localization.terminology.Terminology.TermRelation +import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.ObjectArrayList +import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenHashSet import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet internal class IndexedGlossary : Glossary { + private data class RelationKey(val id: String, val relation: TermRelation) + private data class RelationEdge(val key: RelationKey, val targetId: String) + private val terms = Object2ObjectOpenHashMap() private val termsBySource = Object2ObjectOpenHashMap>() + private val relatedIds = Object2ObjectOpenHashMap>() + private val relationCounts = Object2ObjectOpenHashMap>() + private val relationEdges = Object2ObjectOpenHashMap>() fun isEmpty(): Boolean = terms.isEmpty() fun register(term: GlossaryTerm) { - val previous = terms.put(term.id, term) + val previous = terms[term.id] if (previous != null) { forEachForm(previous) { source -> val oldTerms = termsBySource.getValue(source) oldTerms.remove(previous) if (oldTerms.isEmpty) termsBySource.remove(source) } + relationEdges.remove(term.id)?.forEach(::removeRelation) } + terms[term.id] = term forEachForm(term) { source -> termsBySource.computeIfAbsent(source) { ObjectArrayList(1) }.add(term) } + val edges = ObjectArrayList() + for ((relation, ids) in term.relations) { + for (relatedId in ids) { + addRelation(RelationKey(term.id, relation), relatedId, edges) + if (relation == TermRelation.SYNONYM) { + addRelation(RelationKey(relatedId, relation), term.id, edges) + } + } + } + relationEdges[term.id] = edges } override fun find(id: String): GlossaryTerm? = terms[id] override fun findBySource(normalizedSource: String): Iterable = termsBySource[normalizedSource] ?: emptyList() + override fun findRelated(id: String, relation: TermRelation): Iterable { + val ids = relatedIds[RelationKey(id, relation)] ?: return emptyList() + val related = ObjectArrayList(ids.size) + for (relatedId in ids) terms[relatedId]?.let(related::add) + return related + } + + private fun addRelation(key: RelationKey, targetId: String, edges: ObjectArrayList) { + relationCounts.computeIfAbsent(key) { Object2IntOpenHashMap() }.addTo(targetId, 1) + relatedIds.computeIfAbsent(key) { ObjectLinkedOpenHashSet() }.add(targetId) + edges.add(RelationEdge(key, targetId)) + } + + private fun removeRelation(edge: RelationEdge) { + val counts = relationCounts.getValue(edge.key) + if (counts.addTo(edge.targetId, -1) == 1) { + counts.removeInt(edge.targetId) + if (counts.isEmpty()) relationCounts.remove(edge.key) + val ids = relatedIds.getValue(edge.key) + ids.remove(edge.targetId) + if (ids.isEmpty()) relatedIds.remove(edge.key) + } + } + private inline fun forEachForm(term: GlossaryTerm, action: (String) -> Unit) { val source = term.source.lowercase() if (term.aliases.isEmpty()) { diff --git a/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt b/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt index 6ddaaa8..6b20f65 100644 --- a/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt +++ b/src/main/java/com/modularmc/registrate/localization/terminology/Terminology.kt @@ -8,8 +8,8 @@ import com.modularmc.registrate.localization.TranslationSource import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import it.unimi.dsi.fastutil.objects.ObjectArrayList +import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet -import java.util.EnumSet import java.util.Optional /** Terminology defined by one mod. Register it during mod setup and query it alongside declarations. */ @@ -44,7 +44,7 @@ class Terminology { fun format(value: Number, locale: MinecraftLocale): String = formats[locale]?.format(value, symbol) ?: "$value $symbol" } - private val domains = EnumSet.noneOf(Domain::class.java) + private val domains = ObjectOpenHashSet() private val indexedGlossary = IndexedGlossary() private val glossaries = ObjectArrayList(1).apply { add(indexedGlossary) } private val units = Object2ObjectOpenHashMap() @@ -67,6 +67,28 @@ class Terminology { fun hasDomain(domain: Domain): Boolean = domains.contains(domain) + internal fun synonyms(term: GlossaryTerm): ObjectArrayList { + val discovered = ObjectOpenHashSet() + val pending = ObjectArrayList(4) + val result = ObjectArrayList(4) + discovered.add(term.id) + pending.add(term) + result.add(term) + var index = 0 + while (index < pending.size) { + val current = pending[index++] + for (glossary in glossaries) { + for (related in glossary.findRelated(current.id, TermRelation.SYNONYM)) { + if (discovered.add(related.id)) { + pending.add(related) + result.add(related) + } + } + } + } + return result + } + fun glossary(id: String): Optional = Optional.ofNullable(findTerm(id)) fun unit(id: String): Optional = Optional.ofNullable(units[id]) diff --git a/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.kt b/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.kt index a4a9d8b..7474a05 100644 --- a/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.kt +++ b/src/main/java/com/modularmc/registrate/providers/RegistrateLangProvider.kt @@ -5,7 +5,7 @@ import com.modularmc.registrate.localization.LocalizationDeclaration import com.modularmc.registrate.localization.TranslationKey import com.modularmc.registrate.localization.TranslationSource import com.modularmc.registrate.localization.TranslationSource.Kind -import com.modularmc.registrate.localization.index.IndexedTranslations +import com.modularmc.registrate.localization.annotation.AnnotatedTranslations import com.modularmc.registrate.localization.resolution.TranslationRegistry import com.modularmc.registrate.providers.core.LanguageOutput import com.modularmc.registrate.providers.core.ProviderType @@ -27,6 +27,7 @@ import net.minecraft.world.level.block.Block import net.neoforged.fml.LogicalSide import net.neoforged.neoforge.common.data.LanguageProvider +import it.unimi.dsi.fastutil.objects.ObjectArrayList import org.apache.commons.lang3.StringUtils import java.util.concurrent.CompletableFuture @@ -37,7 +38,7 @@ open class RegistrateLangProvider(private val owner: AbstractRegistrate<*>, priv RegistrateProvider { private class Operation(val key: String, val value: String) - private val operations = ArrayList() + private val operations = ObjectArrayList() override fun getSide(): LogicalSide = LogicalSide.CLIENT @@ -94,7 +95,7 @@ open class RegistrateLangProvider(private val owner: AbstractRegistrate<*>, priv operations.add(Operation(key, value)) } - open fun collect(registry: TranslationRegistry) { + internal fun collect(registry: TranslationRegistry) { val modId = owner.modid val locale = owner.requireSourceLocale() val terminology = owner.terminology() @@ -104,11 +105,17 @@ open class RegistrateLangProvider(private val owner: AbstractRegistrate<*>, priv for (operation in operations) { val key = operation.key val source = TranslationSource(Kind.DECLARED, "[$modId] ProviderType.LANG ($key)") - registry.add(TranslationKey(modId, key), locale, LocalizationDeclaration.sourceText(operation.value), source, terminology) + registry.add( + TranslationKey(modId, key), + locale, + LocalizationDeclaration.sourceText(operation.value, owner.localizationDefaultValues()), + source, + terminology, + ) } operations.clear() owner.collectRawTranslations(registry, locale) - IndexedTranslations.collect(modId, locale, registry, terminology) + AnnotatedTranslations.collect(owner, locale, registry) owner.collectImportedTranslations(registry, locale) } diff --git a/src/main/java/com/modularmc/registrate/providers/core/DataGenBatch.kt b/src/main/java/com/modularmc/registrate/providers/core/DataGenBatch.kt index d3779dc..4e9a81c 100644 --- a/src/main/java/com/modularmc/registrate/providers/core/DataGenBatch.kt +++ b/src/main/java/com/modularmc/registrate/providers/core/DataGenBatch.kt @@ -1,5 +1,7 @@ package com.modularmc.registrate.providers.core +import com.modularmc.registrate.localization.MinecraftLocale +import com.modularmc.registrate.localization.export.LocalizationExportOutput import com.modularmc.registrate.localization.resolution.TranslationRegistry import net.minecraft.data.CachedOutput @@ -7,14 +9,16 @@ import net.minecraft.data.DataProvider import net.minecraft.data.PackOutput import net.neoforged.neoforge.data.event.GatherDataEvent +import it.unimi.dsi.fastutil.objects.Object2ObjectLinkedOpenHashMap import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap +import it.unimi.dsi.fastutil.objects.ObjectArrayList import java.nio.file.Path import java.util.concurrent.CompletableFuture /** Groups the providers attached to the same output before NeoForge starts the DataGen run. */ internal class DataGenBatch private constructor(private val output: PackOutput, private val root: Path) : DataProvider { - private val participants = ArrayList() + private val participants = ObjectArrayList() override fun run(cache: CachedOutput): CompletableFuture<*> { synchronized(pending) { pending.remove(root) } @@ -40,8 +44,34 @@ internal class DataGenBatch private constructor(private val output: PackOutput, val runs = Array(participants.size) { participants[it].runResources(cache) } return CompletableFuture.allOf(*runs).thenCompose { val translations = TranslationRegistry() - for (provider in participants) provider.collectTranslations(translations) - LanguageOutput.write(cache, output, translations) + val exportRegistries = Object2ObjectLinkedOpenHashMap() + val exportLocales = Object2ObjectOpenHashMap() + val exportPaths = Object2ObjectOpenHashMap() + val exportOwners = Object2ObjectOpenHashMap() + for (provider in participants) { + if (!provider.hasLanguageProvider()) continue + val path = provider.localizationExportPath() ?: continue + val modId = provider.modId + val locale = provider.localizationSourceLocale() + val previousLocale = exportLocales.putIfAbsent(modId, locale) + check(previousLocale == null || previousLocale == locale) { "[$modId] Registrate instances use different source locales" } + val previousPath = exportPaths.putIfAbsent(modId, path) + check(previousPath == null || previousPath == path) { "[$modId] Registrate instances use different localization export paths" } + val previousOwner = exportOwners.putIfAbsent(path, modId) + check(previousOwner == null || previousOwner == modId) { "Localization exports for $previousOwner and $modId use the same path $path" } + exportRegistries.computeIfAbsent(modId) { TranslationRegistry(translations) } + } + for (provider in participants) provider.collectTranslations(translations, exportRegistries[provider.modId]) + + val writes = ObjectArrayList>(exportRegistries.size + 1) + writes.add(LanguageOutput.write(cache, output, translations)) + val iterator = exportRegistries.object2ObjectEntrySet().fastIterator() + while (iterator.hasNext()) { + val entry = iterator.next() + val document = entry.value.export(entry.key, exportLocales.getValue(entry.key)) + writes.add(LocalizationExportOutput.write(cache, exportPaths.getValue(entry.key), document)) + } + CompletableFuture.allOf(*writes.toTypedArray()) } } } diff --git a/src/main/java/com/modularmc/registrate/providers/core/LanguageOutput.kt b/src/main/java/com/modularmc/registrate/providers/core/LanguageOutput.kt index d56d8da..a128a52 100644 --- a/src/main/java/com/modularmc/registrate/providers/core/LanguageOutput.kt +++ b/src/main/java/com/modularmc/registrate/providers/core/LanguageOutput.kt @@ -12,9 +12,9 @@ import com.google.gson.JsonObject import java.util.concurrent.CompletableFuture -object LanguageOutput { +internal object LanguageOutput { @JvmStatic - fun write(cache: CachedOutput, output: PackOutput, registry: TranslationRegistry): CompletableFuture<*> { + internal fun write(cache: CachedOutput, output: PackOutput, registry: TranslationRegistry): CompletableFuture<*> { val paths = output.createPathProvider(Target.RESOURCE_PACK, "lang") val files = registry.resolve() val entries = files.entries.iterator() diff --git a/src/main/java/com/modularmc/registrate/providers/core/ProviderType.kt b/src/main/java/com/modularmc/registrate/providers/core/ProviderType.kt index f8ced30..d5fbe41 100644 --- a/src/main/java/com/modularmc/registrate/providers/core/ProviderType.kt +++ b/src/main/java/com/modularmc/registrate/providers/core/ProviderType.kt @@ -146,6 +146,13 @@ fun interface ProviderType : GeneratorType { return type } + /** Rebinds [name] to [type], replacing its current provider and any previous name for [type]. */ + @JvmStatic + fun replaceProvider(name: String, type: ProviderType): ProviderType { + RegistrateDataProvider.TYPES.forcePut(name, type) + return type + } + @JvmStatic fun registerClientProvider(name: String, supplier: NonNullSupplier>): ProviderType { val type = if (DatagenModLoader.isRunningDataGen()) { diff --git a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.kt b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.kt index 9209f7d..889c260 100644 --- a/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.kt +++ b/src/main/java/com/modularmc/registrate/providers/core/RegistrateDataProvider.kt @@ -24,7 +24,7 @@ import java.util.Optional import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentHashMap -open class RegistrateDataProvider(parent: AbstractRegistrate<*>, private val mod: String, event: GatherDataEvent) : DataProvider { +open class RegistrateDataProvider(private val parent: AbstractRegistrate<*>, private val mod: String, event: GatherDataEvent) : DataProvider { private val output = event.generator.packOutput private val registriesLookup: CompletableFuture = event.lookupProvider private val subProviders = Object2ObjectLinkedOpenHashMap, RegistrateProvider>() @@ -79,8 +79,17 @@ open class RegistrateDataProvider(parent: AbstractRegistrate<*>, private val mod CompletableFuture.allOf(*runs.values.toTypedArray()) } - internal fun collectTranslations(registry: TranslationRegistry) { - (subProviders[ProviderType.LANG] as? RegistrateLangProvider)?.collect(registry) + internal val modId: String + get() = mod + + internal fun hasLanguageProvider(): Boolean = ProviderType.LANG in subProviders + + internal fun localizationExportPath() = parent.localizationExportPath() + + internal fun localizationSourceLocale() = parent.requireSourceLocale() + + internal fun collectTranslations(registry: TranslationRegistry, exportRegistry: TranslationRegistry?) { + (subProviders[ProviderType.LANG] as? RegistrateLangProvider)?.collect(exportRegistry ?: registry) } override fun getName(): String = "Registrate Provider for $mod" diff --git a/src/test/generated/resources/assets/testmod/blockstates/magic_item_model.json b/src/test/generated/resources/assets/testmod/blockstates/magic_item_model.json deleted file mode 100644 index 0ad4a59..0000000 --- a/src/test/generated/resources/assets/testmod/blockstates/magic_item_model.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "": { - "model": "testmod:block/subfolder/magic_item_model" - } - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/blockstates/testblock.json b/src/test/generated/resources/assets/testmod/blockstates/testblock.json deleted file mode 100644 index 5f6ec4d..0000000 --- a/src/test/generated/resources/assets/testmod/blockstates/testblock.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "": { - "model": "minecraft:block/glass" - } - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/blockstates/testbucketfluid.json b/src/test/generated/resources/assets/testmod/blockstates/testbucketfluid.json deleted file mode 100644 index d97bc1a..0000000 --- a/src/test/generated/resources/assets/testmod/blockstates/testbucketfluid.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "": { - "model": "testmod:block/testbucketfluid" - } - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/blockstates/testfluid.json b/src/test/generated/resources/assets/testmod/blockstates/testfluid.json deleted file mode 100644 index 791eb00..0000000 --- a/src/test/generated/resources/assets/testmod/blockstates/testfluid.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "variants": { - "": { - "model": "testmod:block/testfluid" - } - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/magic_item_model.json b/src/test/generated/resources/assets/testmod/items/magic_item_model.json deleted file mode 100644 index 8f0f7e8..0000000 --- a/src/test/generated/resources/assets/testmod/items/magic_item_model.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "testmod:block/subfolder/magic_item_model" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testblock.json b/src/test/generated/resources/assets/testmod/items/testblock.json deleted file mode 100644 index 0f2f576..0000000 --- a/src/test/generated/resources/assets/testmod/items/testblock.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "minecraft:item/egg", - "tints": [ - { - "type": "minecraft:constant", - "value": -65536 - } - ] - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json b/src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json deleted file mode 100644 index b48ce41..0000000 --- a/src/test/generated/resources/assets/testmod/items/testbucketfluid_bucket.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "model": { - "type": "neoforge:fluid_container", - "flip_gas": true, - "fluid": "testmod:testbucketfluid", - "textures": { - "base": "minecraft:item/bucket", - "fluid": "neoforge:item/mask/bucket_fluid", - "particle": "minecraft:item/bucket" - } - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json b/src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json deleted file mode 100644 index ec7ccbb..0000000 --- a/src/test/generated/resources/assets/testmod/items/testentity_spawn_egg.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "testmod:item/testentity_spawn_egg" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/items/testitem.json b/src/test/generated/resources/assets/testmod/items/testitem.json deleted file mode 100644 index f5c9f2a..0000000 --- a/src/test/generated/resources/assets/testmod/items/testitem.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "model": { - "type": "minecraft:model", - "model": "minecraft:block/stone" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/lang/en_ud.json b/src/test/generated/resources/assets/testmod/lang/en_ud.json deleted file mode 100644 index a236878..0000000 --- a/src/test/generated/resources/assets/testmod/lang/en_ud.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "advancements.testmod.root.description": "˙bbǝ uɐ ʇǝ⅁", - "advancements.testmod.root.title": "ʇuǝɯǝɔuɐʌpⱯ ʇsǝ⟘", - "block.testmod.magic_item_model": "ןǝpoW ɯǝʇI ɔıbɐW", - "block.testmod.testblock": "ʞɔoןqʇsǝ⟘", - "block.testmod.testbucketfluid": "pınןɟʇǝʞɔnqʇsǝ⟘", - "block.testmod.testfluid": "pınןɟʇsǝ⟘", - "entity.testmod.testentity": "ʎʇıʇuǝʇsǝ⟘", - "entity.testmod.testitem": "ɯǝʇıʇsǝ⟘", - "fluid.testmod.testbucketfluid": "pınןɟʇǝʞɔnqʇsǝ⟘", - "fluid.testmod.testfluid": "pınןɟʇsǝ⟘", - "item.testmod.testbucketfluid_bucket": "ʇǝʞɔnᗺ pınןɟʇǝʞɔnqʇsǝ⟘", - "item.testmod.testentity_spawn_egg": "bbƎ uʍɐdS ʎʇıʇuǝʇsǝ⟘", - "item.testmod.testitem": "ɯǝʇıʇsǝ⟘", - "item.testmod.testitem.testextra": "¡ɔıbɐW", - "itemGroup.testmod.test_creative_mode_tab": "qɐ⟘ ǝpoW ǝʌıʇɐǝɹƆ ʇsǝ⟘", - "testmod.custom.lang": "ʇsǝ⟘", - "testmod.custom.lang.brackets": "◁ϛ ʇǝʞɔɐɹᗺ▷ <ㄣ ʇǝʞɔɐɹᗺ> {Ɛ ʇǝʞɔɐɹᗺ} [ᄅ ʇǝʞɔɐɹᗺ] (Ɩ ʇǝʞɔɐɹᗺ)", - "testmod.custom.lang.slashes": "/ ɥsɐןsʞɔɐq ɐ sı ǝɹǝɥ puɐ poob ʞooן spuɐɯɯɯoɔ\\", - "testmod.custom.lang.with_placeholders1": "%2$s ᄅ ɹǝpןoɥǝɔɐןԀ %1$s Ɩ ɹǝpןoɥǝɔɐןԀ", - "testmod.custom.lang.with_placeholders2": "%3$s Ɛ ɹǝpןoɥǝɔɐןԀ %2$s ᄅ ɹǝpןoɥǝɔɐןԀ %1$s Ɩ ɹǝpןoɥǝɔɐןԀ", - "tooltip.testmod.testblock": "˙bbƎ" -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/lang/en_us.json b/src/test/generated/resources/assets/testmod/lang/en_us.json deleted file mode 100644 index 58f56c5..0000000 --- a/src/test/generated/resources/assets/testmod/lang/en_us.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "advancements.testmod.root.description": "Get an egg.", - "advancements.testmod.root.title": "Test Advancement", - "block.testmod.magic_item_model": "Magic Item Model", - "block.testmod.testblock": "Testblock", - "block.testmod.testbucketfluid": "Testbucketfluid", - "block.testmod.testfluid": "Testfluid", - "entity.testmod.testentity": "Testentity", - "entity.testmod.testitem": "Testitem", - "fluid.testmod.testbucketfluid": "Testbucketfluid", - "fluid.testmod.testfluid": "Testfluid", - "item.testmod.testbucketfluid_bucket": "Testbucketfluid Bucket", - "item.testmod.testentity_spawn_egg": "Testentity Spawn Egg", - "item.testmod.testitem": "Testitem", - "item.testmod.testitem.testextra": "Magic!", - "itemGroup.testmod.test_creative_mode_tab": "Test Creative Mode Tab", - "testmod.custom.lang": "Test", - "testmod.custom.lang.brackets": "(Bracket 1) [Bracket 2] {Bracket 3} ◁Bracket 5▷", - "testmod.custom.lang.slashes": "/commmands look good and here is a backslash \\", - "testmod.custom.lang.with_placeholders1": "Placeholder 1 %s Placeholder 2 %s", - "testmod.custom.lang.with_placeholders2": "Placeholder 1 %s Placeholder 2 %2$s Placeholder 3 %s", - "tooltip.testmod.testblock": "Egg." -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/block/subfolder/magic_item_model.json b/src/test/generated/resources/assets/testmod/models/block/subfolder/magic_item_model.json deleted file mode 100644 index e4cf5ec..0000000 --- a/src/test/generated/resources/assets/testmod/models/block/subfolder/magic_item_model.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "parent": "minecraft:block/cube_all", - "textures": { - "all": "minecraft:block/gold_block" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/block/testbucketfluid.json b/src/test/generated/resources/assets/testmod/models/block/testbucketfluid.json deleted file mode 100644 index 6703228..0000000 --- a/src/test/generated/resources/assets/testmod/models/block/testbucketfluid.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "textures": { - "particle": "minecraft:block/water_still" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/block/testfluid.json b/src/test/generated/resources/assets/testmod/models/block/testfluid.json deleted file mode 100644 index 467346c..0000000 --- a/src/test/generated/resources/assets/testmod/models/block/testfluid.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "textures": { - "particle": "minecraft:block/water_flow" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/assets/testmod/models/item/testentity_spawn_egg.json b/src/test/generated/resources/assets/testmod/models/item/testentity_spawn_egg.json deleted file mode 100644 index 3730294..0000000 --- a/src/test/generated/resources/assets/testmod/models/item/testentity_spawn_egg.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "parent": "minecraft:item/generated", - "textures": { - "layer0": "testmod:item/testentity_spawn_egg" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/block/dragon_immune.json b/src/test/generated/resources/data/minecraft/tags/block/dragon_immune.json deleted file mode 100644 index 185287b..0000000 --- a/src/test/generated/resources/data/minecraft/tags/block/dragon_immune.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "values": [ - "testmod:testblock" - ] -} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/block/supports_bamboo.json b/src/test/generated/resources/data/minecraft/tags/block/supports_bamboo.json deleted file mode 100644 index 185287b..0000000 --- a/src/test/generated/resources/data/minecraft/tags/block/supports_bamboo.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "values": [ - "testmod:testblock" - ] -} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/block/wither_immune.json b/src/test/generated/resources/data/minecraft/tags/block/wither_immune.json deleted file mode 100644 index 185287b..0000000 --- a/src/test/generated/resources/data/minecraft/tags/block/wither_immune.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "values": [ - "testmod:testblock" - ] -} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/entity_type/raiders.json b/src/test/generated/resources/data/minecraft/tags/entity_type/raiders.json deleted file mode 100644 index c064704..0000000 --- a/src/test/generated/resources/data/minecraft/tags/entity_type/raiders.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "values": [ - "testmod:testentity" - ] -} \ No newline at end of file diff --git a/src/test/generated/resources/data/minecraft/tags/item/beds.json b/src/test/generated/resources/data/minecraft/tags/item/beds.json deleted file mode 100644 index 8f30064..0000000 --- a/src/test/generated/resources/data/minecraft/tags/item/beds.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "values": [ - "testmod:testitem" - ] -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_campfire.json b/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_campfire.json deleted file mode 100644 index 7c8f4ee..0000000 --- a/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_campfire.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "parent": "minecraft:recipes/root", - "criteria": { - "has_testblock": { - "conditions": { - "items": [ - { - "items": "testmod:testblock" - } - ] - }, - "trigger": "minecraft:inventory_changed" - }, - "has_the_recipe": { - "conditions": { - "recipe": "testmod:diamond_block_from_testblock_campfire" - }, - "trigger": "minecraft:recipe_unlocked" - } - }, - "requirements": [ - [ - "has_the_recipe", - "has_testblock" - ] - ], - "rewards": { - "recipes": [ - "testmod:diamond_block_from_testblock_campfire" - ] - } -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smelting.json b/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smelting.json deleted file mode 100644 index bbbad68..0000000 --- a/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smelting.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "parent": "minecraft:recipes/root", - "criteria": { - "has_testblock": { - "conditions": { - "items": [ - { - "items": "testmod:testblock" - } - ] - }, - "trigger": "minecraft:inventory_changed" - }, - "has_the_recipe": { - "conditions": { - "recipe": "testmod:diamond_block_from_testblock_smelting" - }, - "trigger": "minecraft:recipe_unlocked" - } - }, - "requirements": [ - [ - "has_the_recipe", - "has_testblock" - ] - ], - "rewards": { - "recipes": [ - "testmod:diamond_block_from_testblock_smelting" - ] - } -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smoking.json b/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smoking.json deleted file mode 100644 index 0cd3a34..0000000 --- a/src/test/generated/resources/data/testmod/advancement/recipes/misc/diamond_block_from_testblock_smoking.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "parent": "minecraft:recipes/root", - "criteria": { - "has_testblock": { - "conditions": { - "items": [ - { - "items": "testmod:testblock" - } - ] - }, - "trigger": "minecraft:inventory_changed" - }, - "has_the_recipe": { - "conditions": { - "recipe": "testmod:diamond_block_from_testblock_smoking" - }, - "trigger": "minecraft:recipe_unlocked" - } - }, - "requirements": [ - [ - "has_the_recipe", - "has_testblock" - ] - ], - "rewards": { - "recipes": [ - "testmod:diamond_block_from_testblock_smoking" - ] - } -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/recipes/misc/testblock.json b/src/test/generated/resources/data/testmod/advancement/recipes/misc/testblock.json deleted file mode 100644 index 950b7cc..0000000 --- a/src/test/generated/resources/data/testmod/advancement/recipes/misc/testblock.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "parent": "minecraft:recipes/root", - "criteria": { - "has_egg": { - "conditions": { - "items": [ - { - "items": "minecraft:egg" - } - ] - }, - "trigger": "minecraft:inventory_changed" - }, - "has_the_recipe": { - "conditions": { - "recipe": "testmod:testblock" - }, - "trigger": "minecraft:recipe_unlocked" - } - }, - "requirements": [ - [ - "has_the_recipe", - "has_egg" - ] - ], - "rewards": { - "recipes": [ - "testmod:testblock" - ] - } -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/advancement/root.json b/src/test/generated/resources/data/testmod/advancement/root.json deleted file mode 100644 index 28d1f62..0000000 --- a/src/test/generated/resources/data/testmod/advancement/root.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "criteria": { - "has_egg": { - "conditions": { - "items": [ - { - "items": "minecraft:egg" - } - ] - }, - "trigger": "minecraft:inventory_changed" - } - }, - "display": { - "background": "minecraft:textures/gui/advancements/backgrounds/stone.png", - "description": { - "translate": "advancements.testmod.root.description" - }, - "icon": { - "id": "minecraft:egg" - }, - "title": { - "translate": "advancements.testmod.root.title" - } - }, - "requirements": [ - [ - "has_egg" - ] - ], - "sends_telemetry_event": true -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/dimension/test_dimension.json b/src/test/generated/resources/data/testmod/dimension/test_dimension.json deleted file mode 100644 index 06f6aa9..0000000 --- a/src/test/generated/resources/data/testmod/dimension/test_dimension.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "type": "testmod:test_dimension_type", - "generator": { - "type": "minecraft:noise", - "biome_source": { - "type": "minecraft:fixed", - "biome": "minecraft:plains" - }, - "settings": "minecraft:overworld" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json b/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json deleted file mode 100644 index ff1f490..0000000 --- a/src/test/generated/resources/data/testmod/dimension_type/test_dimension_type.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "ambient_light": 0.0, - "attributes": { - "minecraft:audio/ambient_sounds": { - "mood": { - "block_search_extent": 8, - "offset": 2.0, - "sound": "minecraft:ambient.cave", - "tick_delay": 6000 - } - }, - "minecraft:audio/background_music": { - "creative": { - "max_delay": 24000, - "min_delay": 12000, - "sound": "minecraft:music.creative" - }, - "default": { - "max_delay": 24000, - "min_delay": 12000, - "sound": "minecraft:music.game" - } - }, - "minecraft:gameplay/bed_rule": { - "can_set_spawn": "always", - "can_sleep": "when_dark", - "error_message": { - "translate": "block.minecraft.bed.no_sleep" - } - }, - "minecraft:gameplay/nether_portal_spawns_piglin": true, - "minecraft:gameplay/respawn_anchor_works": false, - "minecraft:visual/ambient_light_color": "#0a0a0a", - "minecraft:visual/cloud_color": "#ccffffff", - "minecraft:visual/cloud_height": 192.33, - "minecraft:visual/fog_color": "#c0d8ff", - "minecraft:visual/sky_color": "#78a7ff" - }, - "coordinate_scale": 1.0, - "default_clock": "minecraft:overworld", - "has_ceiling": false, - "has_ender_dragon_fight": false, - "has_skylight": true, - "height": 384, - "infiniburn": "#minecraft:infiniburn_overworld", - "logical_height": 384, - "min_y": -64, - "monster_spawn_block_light_limit": 0, - "monster_spawn_light_level": { - "type": "minecraft:uniform", - "max_inclusive": 7, - "min_inclusive": 0 - }, - "timelines": "#minecraft:in_overworld" -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/loot_table/blocks/magic_item_model.json b/src/test/generated/resources/data/testmod/loot_table/blocks/magic_item_model.json deleted file mode 100644 index e94ddd4..0000000 --- a/src/test/generated/resources/data/testmod/loot_table/blocks/magic_item_model.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "type": "minecraft:block", - "pools": [ - { - "bonus_rolls": 0.0, - "conditions": [ - { - "condition": "minecraft:survives_explosion" - } - ], - "entries": [ - { - "type": "minecraft:item", - "name": "testmod:magic_item_model" - } - ], - "rolls": 1.0 - } - ], - "random_sequence": "testmod:blocks/magic_item_model" -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/loot_table/blocks/testblock.json b/src/test/generated/resources/data/testmod/loot_table/blocks/testblock.json deleted file mode 100644 index ef4f7fc..0000000 --- a/src/test/generated/resources/data/testmod/loot_table/blocks/testblock.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "type": "minecraft:block", - "pools": [ - { - "bonus_rolls": 0.0, - "conditions": [ - { - "condition": "minecraft:survives_explosion" - } - ], - "entries": [ - { - "type": "minecraft:item", - "name": "minecraft:diamond" - } - ], - "rolls": 1.0 - } - ], - "random_sequence": "testmod:blocks/testblock" -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/loot_table/entities/testentity.json b/src/test/generated/resources/data/testmod/loot_table/entities/testentity.json deleted file mode 100644 index 3e34c66..0000000 --- a/src/test/generated/resources/data/testmod/loot_table/entities/testentity.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "type": "minecraft:entity", - "pools": [ - { - "bonus_rolls": 0.0, - "entries": [ - { - "type": "minecraft:item", - "functions": [ - { - "add": false, - "count": { - "type": "minecraft:uniform", - "max": 3.0, - "min": 1.0 - }, - "function": "minecraft:set_count" - }, - { - "count": { - "type": "minecraft:uniform", - "max": 2.0, - "min": 0.0 - }, - "enchantment": "minecraft:looting", - "function": "minecraft:enchanted_count_increase" - } - ], - "name": "minecraft:diamond" - } - ], - "rolls": 1.0 - } - ], - "random_sequence": "testmod:entities/testentity" -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/loot_table/entities/testitem.json b/src/test/generated/resources/data/testmod/loot_table/entities/testitem.json deleted file mode 100644 index 058a463..0000000 --- a/src/test/generated/resources/data/testmod/loot_table/entities/testitem.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "type": "minecraft:entity", - "random_sequence": "testmod:entities/testitem" -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json deleted file mode 100644 index 66c260d..0000000 --- a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_campfire.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "type": "minecraft:campfire_cooking", - "category": "misc", - "cookingtime": 600, - "experience": 1.0, - "ingredient": "testmod:testblock", - "result": { - "id": "minecraft:diamond_block" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json deleted file mode 100644 index 4b5e4df..0000000 --- a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smelting.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "type": "minecraft:smelting", - "category": "misc", - "cookingtime": 200, - "experience": 1.0, - "ingredient": "testmod:testblock", - "result": { - "id": "minecraft:diamond_block" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json b/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json deleted file mode 100644 index 69eed99..0000000 --- a/src/test/generated/resources/data/testmod/recipe/diamond_block_from_testblock_smoking.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "type": "minecraft:smoking", - "category": "misc", - "cookingtime": 100, - "experience": 1.0, - "ingredient": "testmod:testblock", - "result": { - "id": "minecraft:diamond_block" - } -} \ No newline at end of file diff --git a/src/test/generated/resources/data/testmod/recipe/testblock.json b/src/test/generated/resources/data/testmod/recipe/testblock.json deleted file mode 100644 index 6e325d8..0000000 --- a/src/test/generated/resources/data/testmod/recipe/testblock.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "type": "minecraft:crafting_shaped", - "category": "misc", - "key": { - "D": "minecraft:diamond", - "E": "minecraft:egg" - }, - "pattern": [ - "DDD", - "DED", - "DDD" - ], - "result": { - "id": "testmod:testblock" - } -} \ No newline at end of file diff --git a/src/test/java/com/modularmc/registrate/test/gametests/LocalizationTests.kt b/src/test/java/com/modularmc/registrate/test/gametests/LocalizationTests.kt deleted file mode 100644 index 20e7d2d..0000000 --- a/src/test/java/com/modularmc/registrate/test/gametests/LocalizationTests.kt +++ /dev/null @@ -1,343 +0,0 @@ -package com.modularmc.registrate.test.gametests - -import com.modularmc.registrate.AbstractRegistrate -import com.modularmc.registrate.localization.DeclarationDefaults -import com.modularmc.registrate.localization.ImportedTranslation -import com.modularmc.registrate.localization.LocalizationDeclaration -import com.modularmc.registrate.localization.LocalizationDeclaration.Companion.sourceText -import com.modularmc.registrate.localization.MinecraftLocale -import com.modularmc.registrate.localization.MinecraftLocale.EN_AU -import com.modularmc.registrate.localization.MinecraftLocale.EN_GB -import com.modularmc.registrate.localization.MinecraftLocale.EN_UD -import com.modularmc.registrate.localization.MinecraftLocale.EN_US -import com.modularmc.registrate.localization.MinecraftLocale.ZH_CN -import com.modularmc.registrate.localization.SourceRevision -import com.modularmc.registrate.localization.TextType -import com.modularmc.registrate.localization.TranslationKey -import com.modularmc.registrate.localization.TranslationSource -import com.modularmc.registrate.localization.TranslationSource.Kind -import com.modularmc.registrate.localization.TranslationStatus -import com.modularmc.registrate.localization.TranslationStatus.APPROVED -import com.modularmc.registrate.localization.TranslationStatus.DRAFT -import com.modularmc.registrate.localization.TranslationStatus.IN_REVIEW -import com.modularmc.registrate.localization.TranslationStatus.STALE -import com.modularmc.registrate.localization.index.IndexedTranslations -import com.modularmc.registrate.localization.locale.LocaleDerivation -import com.modularmc.registrate.localization.resolution.TranslationRegistry -import com.modularmc.registrate.localization.resolution.TranslationRegistry.LanguageFile -import com.modularmc.registrate.localization.terminology.Domain -import com.modularmc.registrate.localization.terminology.Glossary -import com.modularmc.registrate.localization.terminology.Terminology -import com.modularmc.registrate.localization.terminology.Terminology.GlossaryTerm -import com.modularmc.registrate.localization.terminology.Terminology.MeasurementUnit -import com.modularmc.registrate.localization.terminology.Terminology.TermRelation -import com.modularmc.registrate.localization.terminology.UnitFormat -import com.modularmc.registrate.providers.RegistrateLangProvider -import com.modularmc.registrate.providers.core.LanguageOutput -import com.modularmc.registrate.test.mod.TestMod -import com.modularmc.registrate.test.mod.localization.ChineseLocaleTestMod -import com.modularmc.registrate.test.mod.localization.EnglishLabels - -import net.minecraft.data.PackOutput -import net.neoforged.testframework.DynamicTest -import net.neoforged.testframework.annotation.ForEachTest -import net.neoforged.testframework.annotation.TestHolder -import net.neoforged.testframework.gametest.EmptyTemplate -import net.neoforged.testframework.gametest.GameTest - -import java.nio.file.Path - -@ForEachTest(groups = ["registrate-localization"]) -object LocalizationTests { - private val inventory = TranslationKey(TestMod.MOD_ID, "gui.testmod.inventory") - private val builder = TranslationSource(Kind.DECLARED, "Builder testmod:inventory") - private val manual = TranslationSource(Kind.DECLARED, "Manual inventory label") - - @JvmStatic - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = ["Use explicit translations and preserve reordered Minecraft placeholders"]) - fun resolveDeclaredTextAndMinecraftPlaceholders(test: DynamicTest) { - test.onGameTest { helper -> - val registry = TranslationRegistry() - registry.add(inventory, EN_US, sourceText("Automatic Name"), TranslationSource(Kind.AUTOMATIC, "Default inventory label")) - registry.add(inventory, EN_US, sourceText("Other Automatic Name"), TranslationSource(Kind.AUTOMATIC, "Other default inventory label")) - val label = LocalizationDeclaration.Builder() - .source($$"%s at %2$s (%s%%)") - .translation(ZH_CN, $$"%2$s 上的 %1$s(%2$s%%)") - .build() - registry.add(inventory, EN_US, label, builder) - registry.add(inventory, EN_US, sourceText(label.source), manual) - - val languages = registry.resolve() - helper.assertValueEqual(label.source, languages.text(EN_US, inventory.value), "Declared source") - helper.assertValueEqual(label.translations.getValue(ZH_CN), languages.text(ZH_CN, inventory.value), "Reordered indexed arguments") - helper.assertTrue($$"%%%2$s" in languages.text(EN_UD, inventory.value), "Variant reverses the percent and argument tokens as units") - - val explicitVariant = $$"%1$s / %2$s / %2$s %%" - registry.add( - inventory, - EN_US, - LocalizationDeclaration.Builder().source(label.source).translation(EN_UD, explicitVariant).build(), - manual, - ) - helper.assertValueEqual(explicitVariant, registry.resolve().text(EN_UD, inventory.value), "Explicit variant takes priority") - - val mod = TestMod.instance() - val metadata = mod.testitem.metadata().localization()!!.declaration.get() - val terms = mod.registrate().terminology() - helper.assertValueEqual(listOf(Domain.PHYSICS), metadata.domains, "Object-level domain overrides the default") - helper.assertTrue(metadata.type == TextType.ITEM, "Default text type") - helper.assertValueEqual(terms.glossary("electric_potential").orElseThrow(), metadata.glossary.first(), "Default glossary term") - helper.assertValueEqual("V", terms.unit("volt").orElseThrow().symbol, "Unit symbol") - helper.succeed() - } - } - - @JvmStatic - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = ["Resolve glossary labels using their owning mod, context and explicit terminology"]) - fun resolveGlossaryByContext(test: DynamicTest) { - test.onGameTest { helper -> - val terms = Terminology() - terms.register(GlossaryTerm("electric_potential", "potential", listOf(Domain.PHYSICS), mapOf(ZH_CN to "电势"), setOf(TextType.GUI_LABEL))) - val personal = GlossaryTerm("personal_potential", "potential", emptyList(), mapOf(ZH_CN to "潜力"), setOf(TextType.DESCRIPTION)) - terms.register(object : Glossary { - override fun find(id: String): GlossaryTerm? = personal.takeIf { it.id == id } - - override fun findBySource(normalizedSource: String): Iterable = if (normalizedSource == personal.source) listOf(personal) else emptyList() - }) - val otherTerms = Terminology() - otherTerms.register(GlossaryTerm("potential", "potential", emptyList(), mapOf(ZH_CN to "势能"))) - - val registry = TranslationRegistry() - val electrical = TranslationKey(TestMod.MOD_ID, "gui.testmod.electrical_potential") - val talent = electrical.copy(value = "gui.testmod.personal_potential") - val override = electrical.copy(value = "gui.testmod.potential_override") - val otherMod = electrical.copy(value = "gui.localetest.potential") - registry.add(electrical, EN_US, LocalizationDeclaration.Builder().source("Potential").domain(Domain.PHYSICS).build(), builder, terms) - registry.add(talent, EN_US, LocalizationDeclaration.Builder().source("Potential").type(TextType.DESCRIPTION).build(), manual, terms) - val explicit = LocalizationDeclaration.Builder().source("Potential").domain(Domain.PHYSICS).glossaryIds("personal_potential").build() - registry.add(override, EN_US, explicit, manual, terms) - registry.add(otherMod, EN_US, sourceText("Potential"), manual, otherTerms) - val languages = registry.resolve() - helper.assertValueEqual("电势", languages.text(ZH_CN, electrical.value), "Domain selects electric potential") - helper.assertValueEqual("潜力", languages.text(ZH_CN, talent.value), "Text type selects personal potential") - helper.assertValueEqual("潜力", languages.text(ZH_CN, override.value), "Explicit glossary ID takes priority") - helper.assertValueEqual("势能", languages.text(ZH_CN, otherMod.value), "A shared namespace uses its declaring mod's glossary") - - registry.add(electrical, EN_US, LocalizationDeclaration.Builder().source("Potential").translation(ZH_CN, "电位").build(), manual) - helper.assertValueEqual("电位", registry.resolve().text(ZH_CN, electrical.value), "Explicit translation takes priority over glossary") - - registry.add(inventory, EN_US, sourceText("Potential"), manual, terms) - val diagnostic = failure(registry::resolve) - helper.assertTrue(listOf("electric_potential", "personal_potential", manual.location, inventory.value).all { it in diagnostic }, "Ambiguous term diagnostic") - helper.succeed() - } - } - - @JvmStatic - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = ["Combine declaration defaults and format a unit for its target locale"]) - fun combineDefaultsAndFormatUnits(test: DynamicTest) { - test.onGameTest { helper -> - val terms = Terminology() - val ohm = MeasurementUnit("ohm", "Ω", mapOf(EN_US to "ohm"), mapOf(ZH_CN to UnitFormat("0.00E0", '.', ""))) - terms.register(ohm) - helper.assertValueEqual("1250 Ω", ohm.format(1250, EN_US), "Default unit formatting") - helper.assertValueEqual("1.25E3Ω", ohm.format(1250, ZH_CN), "Localized scientific formatting") - val power = MeasurementUnit("kilowatt", "kW", emptyMap(), mapOf(ZH_CN to UnitFormat("0.0", ',', " "))) - helper.assertValueEqual("2,5 kW", power.format(2.5, ZH_CN), "Configured decimal separator") - - val resistance = GlossaryTerm( - "resistance", - "electrical resistance", - listOf(Domain.PHYSICS), - mapOf(ZH_CN to "电阻"), - aliases = setOf("resistance"), - relations = mapOf(TermRelation.BROADER to setOf("electrical_quantity")), - unitIds = setOf("ohm"), - ) - terms.register(resistance) - val defaults = DeclarationDefaults(listOf(Domain.ENGINEERING), TextType.DESCRIPTION, emptyList(), unitIds = listOf("kilowatt")) - val parent = DeclarationDefaults(listOf(Domain.PHYSICS), TextType.GUI_LABEL, emptyList()) - val terminology = DeclarationDefaults(emptyList(), null, emptyList(), glossaryIds = listOf(resistance.id)) - val combined = DeclarationDefaults.Builder().defaults(defaults).inherits(parent).include(terminology).build() - val declaration = LocalizationDeclaration.Builder().source("Resistance").defaults(combined).units("ohm").build() - helper.assertValueEqual(listOf(Domain.PHYSICS), declaration.domains, "Parent domains override defaults") - helper.assertValueEqual(TextType.GUI_LABEL, declaration.type!!, "Parent text type") - helper.assertValueEqual(listOf("kilowatt"), combined.unitIds, "Unit default") - helper.assertValueEqual(listOf("ohm"), declaration.unitIds, "Declaration overrides unit defaults") - helper.assertValueEqual(setOf("electrical_quantity"), terms.glossary("resistance").orElseThrow().relations.getValue(TermRelation.BROADER), "Glossary relationships") - val registry = TranslationRegistry() - registry.add(inventory, EN_US, declaration, manual, terms) - helper.assertValueEqual("电阻", registry.resolve().text(ZH_CN, inventory.value), "Included glossary ID resolves its alias") - val conflict = failure { DeclarationDefaults.Builder().include(parent, defaults).build() } - helper.assertTrue("GUI_LABEL" in conflict && "DESCRIPTION" in conflict, "Same-level text types conflict") - helper.succeed() - } - } - - @JvmStatic - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = ["Derive configured locales while preserving Minecraft text and measurement symbols"]) - fun deriveLocalesAndProtectFormatting(test: DynamicTest) { - test.onGameTest { helper -> - val owner = UnconfiguredRegistrate() - val terms = owner.terminology() - terms.register(MeasurementUnit("kilowatt", "kW", emptyMap())) - terms.register(MeasurementUnit("ohm", "Ω", emptyMap())) - owner.deriveLocale(LocaleDerivation(EN_US, EN_GB) { text, _ -> text.lowercase().replace("color", "colour") }) - owner.deriveLocale(LocaleDerivation.fallback(EN_GB, EN_AU)) - - val registry = TranslationRegistry() - owner.configureLocaleDerivations(registry) - val text = $$"§cColor %1$s at 5 kW / Ω\nhttps://example.org/Power %%" - val british = $$"§ccolour %1$s at 5 kW / Ω\nhttps://example.org/Power %%" - val declaration = LocalizationDeclaration.Builder().source(text).units("kilowatt", "ohm").build() - registry.add(inventory, EN_US, declaration, manual, terms) - val languages = registry.resolve() - helper.assertValueEqual(british, languages.text(EN_GB, inventory.value), "Only plain text is converted") - helper.assertValueEqual(british, languages.text(EN_AU, inventory.value), "An explicitly configured chain can use a derived text") - val inverted = languages.text(EN_UD, inventory.value) - val preserved = listOf($$"%1$s", "%%", "kW", "Ω", "https://example.org/Power", "\n") - helper.assertTrue(inverted.startsWith("§c") && preserved.all { it in inverted }, "Upside-down English protects formatting and units") - - val explicit = $$"Color %1$s %%" - registry.add(inventory, EN_US, declaration.copy(translations = mapOf(EN_GB to explicit)), builder, terms) - val explicitLanguages = registry.resolve() - helper.assertValueEqual(explicit, explicitLanguages.text(EN_GB, inventory.value), "An explicit translation wins") - helper.assertValueEqual(explicit, explicitLanguages.text(EN_AU, inventory.value), "The chain uses the winning text") - - owner.deriveLocale(LocaleDerivation.fallback(EN_GB, EN_US)) - val cycle = failure { owner.configureLocaleDerivations(registry) } - helper.assertTrue(listOf(owner.modid, "en_us", "en_gb", "cycle").all { it in cycle }, "Cycle diagnostic") - helper.succeed() - } - } - - @JvmStatic - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = ["Resolve imported translations by source revision, review state and lock state"]) - fun resolveImportedTranslations(test: DynamicTest) { - test.onGameTest { helper -> - val registry = TranslationRegistry() - val owner = UnconfiguredRegistrate(TestMod.MOD_ID).sourceLocale(EN_US) - val terms = owner.terminology() - val reviewedKey = inventory.copy(value = "gui.testmod.reviewed") - val staleKey = inventory.copy(value = "gui.testmod.stale") - val lockedKey = inventory.copy(value = "gui.testmod.locked") - val sharedKey = inventory.copy(value = "gui.testmod.shared") - val annotatedKey = inventory.copy(value = EnglishLabels.MENU_TITLE) - - val current = "Current source" - val previous = "Previous source" - registry.add(reviewedKey, EN_US, sourceText(current), manual, terms) - registry.add(staleKey, EN_US, sourceText(previous), TranslationSource(Kind.AUTOMATIC, "Default label"), terms) - registry.add(lockedKey, EN_US, sourceText(current), manual, terms) - registry.add(sharedKey, EN_US, sourceText(previous), TranslationSource(Kind.AUTOMATIC, "Default shared label"), terms) - registry.add(sharedKey, EN_US, sourceText("Another mod source"), manual, Terminology()) - - fun importText(key: TranslationKey, text: String, source: String, status: TranslationStatus = APPROVED, locked: Boolean = false) = - ImportedTranslation(key, ZH_CN, text, SourceRevision.of(source), status, locked, "translations/${key.value}").also { - owner.importTranslation(it) - } - - importText(reviewedKey, "审核中", current, IN_REVIEW) - importText(reviewedKey, "已审核", current) - importText(reviewedKey, "草稿", current, DRAFT) - val stale = importText(staleKey, "旧译文", previous) - val locked = importText(lockedKey, "锁定旧译文", previous, locked = true) - val shared = importText(sharedKey, "共享译文", previous) - importText(lockedKey, "新译文", current) - importText(annotatedKey, "导入译文", "Test Container", locked = true) - - RegistrateLangProvider(owner, PackOutput(Path.of("unused-language-output"))).collect(registry) - helper.assertValueEqual(stale.text, registry.resolve().text(ZH_CN, staleKey.value), "A matching source revision enables the import") - registry.add(staleKey, EN_US, sourceText("Updated source"), manual, terms) - - val imports = ArrayList() - val languages = registry.resolve(imports::add) - val chinese = languages.getValue(LanguageFile(TestMod.MOD_ID, ZH_CN)) - helper.assertValueEqual("已审核", chinese.getValue(reviewedKey.value), "Approved translation outranks lower review states") - helper.assertTrue(stale.copy(status = STALE) in imports, "Source change marks the import stale and keeps its provenance") - helper.assertTrue(staleKey.value !in chinese, "Unlocked stale text is excluded from language output") - helper.assertTrue(locked.copy(status = STALE) in imports, "A locked import still reports its stale revision") - helper.assertValueEqual(locked.text, chinese.getValue(lockedKey.value), "The locked import preserves its wording") - helper.assertValueEqual(shared.text, chinese.getValue(sharedKey.value), "The import uses its own source when another mod has a higher-priority declaration for the same key") - helper.assertValueEqual("测试容器", chinese.getValue(annotatedKey.value), "The annotation's explicit translation takes priority") - helper.succeed() - } - } - - @JvmStatic - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = ["Report both conflicting declarations, mismatched placeholders and missing source locale"]) - fun locateInvalidLocalizationDeclarations(test: DynamicTest) { - test.onGameTest { helper -> - val conflict = TranslationRegistry() - conflict.add(inventory, EN_US, sourceText("First"), builder) - conflict.add(inventory, EN_US, sourceText("Second"), manual) - val conflictingDeclarations = failure(conflict::resolve) - helper.assertTrue(builder.location in conflictingDeclarations && manual.location in conflictingDeclarations, "Both conflicting sources") - - val wrongFormat = TranslationRegistry() - wrongFormat.add( - inventory, - EN_US, - LocalizationDeclaration.Builder().source("Inventory: %s").translation(ZH_CN, $$"物品栏:%2$s").build(), - manual, - ) - val mismatch = failure(wrongFormat::resolve) - helper.assertTrue("placeholder mismatch" in mismatch && manual.location in mismatch, "Translation that changed its source argument") - helper.assertTrue("[missing_locale]" in failure(UnconfiguredRegistrate()::requireSourceLocale), "Mod with missing source locale") - helper.succeed() - } - } - - @JvmStatic - @GameTest - @EmptyTemplate(floor = true) - @TestHolder(description = ["Read Java and Kotlin indexes and fail before writing when a manual declaration conflicts with an annotation"]) - fun collectCompiledAnnotationsBeforeWriting(test: DynamicTest) { - test.onGameTest { helper -> - val registry = TranslationRegistry() - IndexedTranslations.collect(TestMod.MOD_ID, EN_US, registry) - IndexedTranslations.collect(ChineseLocaleTestMod.MOD_ID, ZH_CN, registry) - val languages = registry.resolve() - helper.assertValueEqual("Test", languages.text(EN_US, TestMod.CUSTOM_LANG), "Java annotation") - helper.assertValueEqual("Test Container", languages.text(EN_US, EnglishLabels.MENU_TITLE), "Kotlin field annotation") - helper.assertValueEqual("Low power", languages.text(EN_US, "gui.testmod.power.low"), "First variant") - helper.assertValueEqual("高功率", languages.text(ZH_CN, "gui.testmod.power.high"), "Second variant's target text") - helper.assertValueEqual($$"频率:%1$s Hz", languages.text(ZH_CN, "gui.localetest.frequency"), "Chinese source in shared namespace") - - registry.add(TranslationKey(TestMod.MOD_ID, EnglishLabels.MENU_TITLE), EN_US, sourceText("Conflicting name"), manual) - val diagnostic = failure { - LanguageOutput.write({ _, _, _ -> - throw AssertionError("Conflicting declarations caused a language write") - }, PackOutput(Path.of("unused-language-output")), registry) - } - helper.assertTrue("@Trans ${EnglishLabels::class.java.name}#MENU_TITLE" in diagnostic, "Annotated field in conflict diagnostic") - helper.assertTrue(manual.location in diagnostic, "Manual declaration in conflict diagnostic") - helper.succeed() - } - } - - private fun Map>.text(locale: MinecraftLocale, key: String): String = getValue(LanguageFile(TestMod.MOD_ID, locale)).getValue(key) - - private fun failure(operation: () -> Unit): String { - try { - operation() - } catch (error: IllegalArgumentException) { - return error.message!! - } - throw AssertionError("Localization operation should have failed") - } - - private class UnconfiguredRegistrate(modId: String = "missing_locale") : AbstractRegistrate(modId) -} diff --git a/test/build.gradle b/test/build.gradle new file mode 100644 index 0000000..7fb3049 --- /dev/null +++ b/test/build.gradle @@ -0,0 +1,117 @@ +import org.jetbrains.kotlin.gradle.dsl.JvmDefaultMode +import org.slf4j.event.Level + +plugins { + id 'java-library' + alias libs.plugins.modDevGradle + alias libs.plugins.kotlin.jvm +} + +group = rootProject.group +version = rootProject.version + +java { + toolchain.languageVersion = JavaLanguageVersion.of(25) +} + +kotlin { + jvmToolchain(25) + compilerOptions { + jvmDefault = JvmDefaultMode.NO_COMPATIBILITY + } +} + +sourceSets.main.resources.srcDir 'src/generated/resources' + +neoForge { + version = libs.versions.neoForge.get() + + addModdingDependenciesTo(sourceSets.main) + + mods { + testmod { + sourceSet(sourceSets.main) + } + localetest { + sourceSet(sourceSets.main) + } + } + + runs { + gameTestServer { + type = 'gameTestServer' + sourceSet = sourceSets.main + ideName = 'Game Tests' + + gameDirectory.set(rootProject.file('run/gametest/server')) + systemProperty('neoforge.enabledGameTestNamespaces', 'testmod') + environment('TEST', 'true') + } + + gameTestClient { + client() + sourceSet = sourceSets.main + ideName = 'Game Tests (Client)' + + gameDirectory.set(rootProject.file('run/gametest/client')) + systemProperty('neoforge.enabledGameTestNamespaces', 'testmod') + environment('TEST', 'true') + } + + Testdata { + type = providers.gradleProperty('testDataSide').getOrElse('all') == 'server' ? 'serverData' : 'clientData' + sourceSet = sourceSets.main + ideName = 'Test Data Generation' + + gameDirectory.set(rootProject.file('run/data')) + programArguments.addAll('--mod', 'testmod,localetest', '--flat') + programArguments.addAll('--all') + programArguments.add('--output') + programArguments.add(providers.gradleProperty('testDataOutput').orElse('test/src/generated/resources').map { rootProject.file(it).absolutePath }) + programArguments.addAll('--existing', file('src/main/resources/').absolutePath) + } + + configureEach { + systemProperty 'forge.logging.markers', 'REGISTRIES' + jvmArgument('-ea:com.modularmc.registrate...') + logLevel = Level.INFO + } + } +} +repositories { + mavenLocal() + mavenCentral() + // Resolve libraries hosted on Maven Central without querying mod repositories. + exclusiveContent { // Force + forRepository { mavenCentral() } + filter { + includeGroup("it.unimi.dsi") + includeGroup("org.lwjgl") + includeGroup("com.google.guava") + includeGroup("org.jacoco") + includeGroupAndSubgroups("io.netty") + includeGroupAndSubgroups("org.jetbrains") + includeGroupAndSubgroups("org.ow2") + } + } +} + +dependencies { + implementation(project(':')) + implementation(libs.testframework) + compileOnly(libs.jetbrains.annotations) + compileOnly(libs.jspecify) +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.compilerArgs << '-Xmaxerrs' << '2000' + options.compilerArgs << '-Xlint:-removal' +} + +idea { + module { + downloadSources = true + downloadJavadoc = true + } +} diff --git a/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.kt b/test/src/main/java/com/modularmc/registratetest/gametests/CustomItemTests.kt similarity index 88% rename from src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.kt rename to test/src/main/java/com/modularmc/registratetest/gametests/CustomItemTests.kt index abd2e6e..37700fc 100644 --- a/src/test/java/com/modularmc/registrate/test/gametests/CustomItemTests.kt +++ b/test/src/main/java/com/modularmc/registratetest/gametests/CustomItemTests.kt @@ -1,6 +1,6 @@ -package com.modularmc.registrate.test.gametests +package com.modularmc.registratetest.gametests -import com.modularmc.registrate.test.mod.TestMod +import com.modularmc.registratetest.mod.TestMod import net.neoforged.testframework.DynamicTest import net.neoforged.testframework.annotation.ForEachTest diff --git a/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.kt b/test/src/main/java/com/modularmc/registratetest/gametests/RegistrationRuntimeTests.kt similarity index 97% rename from src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.kt rename to test/src/main/java/com/modularmc/registratetest/gametests/RegistrationRuntimeTests.kt index f6b6488..38b55ee 100644 --- a/src/test/java/com/modularmc/registrate/test/gametests/RegistrationRuntimeTests.kt +++ b/test/src/main/java/com/modularmc/registratetest/gametests/RegistrationRuntimeTests.kt @@ -1,7 +1,7 @@ -package com.modularmc.registrate.test.gametests +package com.modularmc.registratetest.gametests import com.modularmc.registrate.providers.core.ProviderType -import com.modularmc.registrate.test.mod.TestMod +import com.modularmc.registratetest.mod.TestMod import net.minecraft.core.registries.Registries import net.minecraft.world.item.Item diff --git a/src/test/java/com/modularmc/registrate/test/gametests/package-info.java b/test/src/main/java/com/modularmc/registratetest/gametests/package-info.java similarity index 71% rename from src/test/java/com/modularmc/registrate/test/gametests/package-info.java rename to test/src/main/java/com/modularmc/registratetest/gametests/package-info.java index 7ab2d70..4ddc8c2 100644 --- a/src/test/java/com/modularmc/registrate/test/gametests/package-info.java +++ b/test/src/main/java/com/modularmc/registratetest/gametests/package-info.java @@ -2,4 +2,4 @@ * Executable game tests that validate runtime behavior for the sample mod. */ @org.jspecify.annotations.NullMarked -package com.modularmc.registrate.test.gametests; +package com.modularmc.registratetest.gametests; diff --git a/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.kt b/test/src/main/java/com/modularmc/registratetest/meta/MethodGenerator.kt similarity index 96% rename from src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.kt rename to test/src/main/java/com/modularmc/registratetest/meta/MethodGenerator.kt index f251103..9f27d35 100644 --- a/src/test/java/com/modularmc/registrate/test/meta/MethodGenerator.kt +++ b/test/src/main/java/com/modularmc/registratetest/meta/MethodGenerator.kt @@ -1,7 +1,7 @@ -package com.modularmc.registrate.test.meta +package com.modularmc.registratetest.meta -import com.modularmc.registrate.test.meta.ProtectedMethodScraper.isNullable -import com.modularmc.registrate.test.meta.ProtectedMethodScraper.kotlinType +import com.modularmc.registratetest.meta.ProtectedMethodScraper.isNullable +import com.modularmc.registratetest.meta.ProtectedMethodScraper.kotlinType import com.sun.source.tree.AnnotatedTypeTree import com.sun.source.tree.ArrayTypeTree diff --git a/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.kt b/test/src/main/java/com/modularmc/registratetest/meta/ProtectedMethodScraper.kt similarity index 98% rename from src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.kt rename to test/src/main/java/com/modularmc/registratetest/meta/ProtectedMethodScraper.kt index 65096e8..5c74bf8 100644 --- a/src/test/java/com/modularmc/registrate/test/meta/ProtectedMethodScraper.kt +++ b/test/src/main/java/com/modularmc/registratetest/meta/ProtectedMethodScraper.kt @@ -1,4 +1,4 @@ -package com.modularmc.registrate.test.meta +package com.modularmc.registratetest.meta import com.sun.source.tree.AnnotatedTypeTree import com.sun.source.tree.ArrayTypeTree diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.kt b/test/src/main/java/com/modularmc/registratetest/meta/UpdateBlockLootTables.kt similarity index 89% rename from src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.kt rename to test/src/main/java/com/modularmc/registratetest/meta/UpdateBlockLootTables.kt index 8cc136f..357a945 100644 --- a/src/test/java/com/modularmc/registrate/test/meta/UpdateBlockLootTables.kt +++ b/test/src/main/java/com/modularmc/registratetest/meta/UpdateBlockLootTables.kt @@ -1,4 +1,4 @@ -package com.modularmc.registrate.test.meta +package com.modularmc.registratetest.meta import java.nio.file.Path diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.kt b/test/src/main/java/com/modularmc/registratetest/meta/UpdateEntityLootTables.kt similarity index 89% rename from src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.kt rename to test/src/main/java/com/modularmc/registratetest/meta/UpdateEntityLootTables.kt index ff785ee..590dd54 100644 --- a/src/test/java/com/modularmc/registrate/test/meta/UpdateEntityLootTables.kt +++ b/test/src/main/java/com/modularmc/registratetest/meta/UpdateEntityLootTables.kt @@ -1,4 +1,4 @@ -package com.modularmc.registrate.test.meta +package com.modularmc.registratetest.meta import java.nio.file.Path diff --git a/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.kt b/test/src/main/java/com/modularmc/registratetest/meta/UpdateRecipeProvider.kt similarity index 88% rename from src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.kt rename to test/src/main/java/com/modularmc/registratetest/meta/UpdateRecipeProvider.kt index 23b8614..feb378a 100644 --- a/src/test/java/com/modularmc/registrate/test/meta/UpdateRecipeProvider.kt +++ b/test/src/main/java/com/modularmc/registratetest/meta/UpdateRecipeProvider.kt @@ -1,4 +1,4 @@ -package com.modularmc.registrate.test.meta +package com.modularmc.registratetest.meta import java.nio.file.Path diff --git a/src/test/java/com/modularmc/registrate/test/meta/package-info.java b/test/src/main/java/com/modularmc/registratetest/meta/package-info.java similarity index 81% rename from src/test/java/com/modularmc/registrate/test/meta/package-info.java rename to test/src/main/java/com/modularmc/registratetest/meta/package-info.java index 0827a07..645b3a1 100644 --- a/src/test/java/com/modularmc/registrate/test/meta/package-info.java +++ b/test/src/main/java/com/modularmc/registratetest/meta/package-info.java @@ -5,4 +5,4 @@ * These tests support source upkeep rather than runtime game behavior. */ @org.jspecify.annotations.NullMarked -package com.modularmc.registrate.test.meta; +package com.modularmc.registratetest.meta; diff --git a/src/test/java/com/modularmc/registrate/test/mod/KotlinRegistrations.kt b/test/src/main/java/com/modularmc/registratetest/mod/KotlinRegistrations.kt similarity index 97% rename from src/test/java/com/modularmc/registrate/test/mod/KotlinRegistrations.kt rename to test/src/main/java/com/modularmc/registratetest/mod/KotlinRegistrations.kt index 91cc9fe..fdf39b2 100644 --- a/src/test/java/com/modularmc/registrate/test/mod/KotlinRegistrations.kt +++ b/test/src/main/java/com/modularmc/registratetest/mod/KotlinRegistrations.kt @@ -1,4 +1,4 @@ -package com.modularmc.registrate.test.mod +package com.modularmc.registratetest.mod import com.modularmc.registrate.Registrate import com.modularmc.registrate.util.nullness.NonNullBiConsumer diff --git a/src/test/java/com/modularmc/registrate/test/mod/TestMod.java b/test/src/main/java/com/modularmc/registratetest/mod/TestMod.java similarity index 96% rename from src/test/java/com/modularmc/registrate/test/mod/TestMod.java rename to test/src/main/java/com/modularmc/registratetest/mod/TestMod.java index 0ba3041..5f357f1 100644 --- a/src/test/java/com/modularmc/registrate/test/mod/TestMod.java +++ b/test/src/main/java/com/modularmc/registratetest/mod/TestMod.java @@ -1,4 +1,4 @@ -package com.modularmc.registrate.test.mod; +package com.modularmc.registratetest.mod; import com.modularmc.registrate.Registrate; import com.modularmc.registrate.builders.BlockBuilder; @@ -13,7 +13,7 @@ import com.modularmc.registrate.providers.DataGenContext; import com.modularmc.registrate.providers.core.ProviderType; import com.modularmc.registrate.providers.generators.RegistrateItemModelGenerator; -import com.modularmc.registrate.test.mod.localization.EnglishLabels; +import com.modularmc.registratetest.mod.localization.EnglishLabels; import com.modularmc.registrate.util.DataIngredient; import com.modularmc.registrate.util.entry.*; @@ -119,6 +119,7 @@ import org.jspecify.annotations.Nullable; import org.lwjgl.glfw.GLFW; +import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.Optional; @@ -133,8 +134,11 @@ public class TestMod { @Trans(modId = MOD_ID, key = TestMod.CUSTOM_LANG, source = "Test") public static final String CUSTOM_LANG = "testmod.custom.lang"; + @Trans(modId = MOD_ID, key = "gui.testmod.java_default_label", source = "Electric potential") + public static final String JAVA_DEFAULT_LABEL = "gui.testmod.java_default_label"; + private static final GlossaryTerm POTENTIAL = new GlossaryTerm("electric_potential", "electric potential", List.of(Domain.PHYSICS), Map.of(MinecraftLocale.ZH_CN, "电势")); - private static final DeclarationDefaults TECHNOLOGY = new DeclarationDefaults(List.of(Domain.ENGINEERING), TextType.ITEM, List.of(POTENTIAL)); + private static final DeclarationDefaults TECHNOLOGY = new DeclarationDefaults(List.of(Domain.ENGINEERING, Domain.PHYSICS), TextType.ITEM, List.of(POTENTIAL)); public static final class TestBlock extends Block implements EntityBlock { @@ -222,7 +226,7 @@ public TestEntity(EntityType p_i50250_1_, Level p_i50250_2_) { public static final class TestCustomRegistryEntry {} - private final Registrate registrate = Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US); + private final Registrate registrate = Registrate.create(MOD_ID).sourceLocale(MinecraftLocale.EN_US).localizationDefaults(TECHNOLOGY); @VisibleForTesting public final RegistryEntry testcreativetab = registrate.object("test_creative_mode_tab") @@ -234,7 +238,7 @@ public static final class TestCustomRegistryEntry {} @VisibleForTesting public final ItemEntry testitem = registrate.object("testitem") .item(Item::new) - .localization(text -> text.defaults(TECHNOLOGY).domain(Domain.PHYSICS).source("Testitem").translation(MinecraftLocale.ZH_CN, "测试物品")) + .localization(text -> text.domain(Domain.PHYSICS).source("Testitem").translation(MinecraftLocale.ZH_CN, "测试物品")) .onRegister(item -> sawCallback.set(registrate.get("testitem", Registries.ITEM).get() == item)) .properties(p -> p.food(new FoodProperties.Builder().nutrition(1).saturationModifier(0.2f).build())) .tag(ItemTags.BEDS) @@ -341,13 +345,16 @@ private static BlockBuilder applyDiamondDrop(BlockBui public TestMod(IEventBus eventBus, ModContainer container) { INSTANCE = this; + registrate.export().localization() + .path(Path.of("build", "localization", "testmod.json")) + .build(); var terminology = registrate.terminology(); terminology.register(Domain.PHYSICS); terminology.register(POTENTIAL); terminology.register(new MeasurementUnit("volt", "V", Map.of(MinecraftLocale.EN_US, "volt", MinecraftLocale.ZH_CN, "伏特"))); registrate.addLocalization(new TranslationKey(MOD_ID, "gui.testmod.voltage"), - text -> text.defaults(TECHNOLOGY).type(TextType.GUI_LABEL) + text -> text.type(TextType.GUI_LABEL) .source("Voltage: %s V").translation(MinecraftLocale.ZH_CN, "电压:%1$s V")); registrate.addRawLang("testmod.custom.lang.with_placeholders1", "Placeholder 1 %s Placeholder 2 %s"); registrate.addRawLang("testmod.custom.lang.with_placeholders2", "Placeholder 1 %s Placeholder 2 %2$s Placeholder 3 %s"); diff --git a/src/test/java/com/modularmc/registrate/test/mod/localization/ChineseLocaleTestMod.kt b/test/src/main/java/com/modularmc/registratetest/mod/localization/ChineseLocaleTestMod.kt similarity index 91% rename from src/test/java/com/modularmc/registrate/test/mod/localization/ChineseLocaleTestMod.kt rename to test/src/main/java/com/modularmc/registratetest/mod/localization/ChineseLocaleTestMod.kt index 85480b7..58e2c56 100644 --- a/src/test/java/com/modularmc/registrate/test/mod/localization/ChineseLocaleTestMod.kt +++ b/test/src/main/java/com/modularmc/registratetest/mod/localization/ChineseLocaleTestMod.kt @@ -1,10 +1,10 @@ -package com.modularmc.registrate.test.mod.localization +package com.modularmc.registratetest.mod.localization import com.modularmc.registrate.Registrate import com.modularmc.registrate.localization.MinecraftLocale import com.modularmc.registrate.localization.annotation.Trans import com.modularmc.registrate.localization.annotation.Translation -import com.modularmc.registrate.test.mod.TestMod +import com.modularmc.registratetest.mod.TestMod import com.modularmc.registrate.util.nullness.NonNullBiConsumer import net.minecraft.world.item.Item diff --git a/src/test/java/com/modularmc/registrate/test/mod/localization/EnglishLabels.kt b/test/src/main/java/com/modularmc/registratetest/mod/localization/EnglishLabels.kt similarity index 75% rename from src/test/java/com/modularmc/registrate/test/mod/localization/EnglishLabels.kt rename to test/src/main/java/com/modularmc/registratetest/mod/localization/EnglishLabels.kt index c33e3de..baf542f 100644 --- a/src/test/java/com/modularmc/registrate/test/mod/localization/EnglishLabels.kt +++ b/test/src/main/java/com/modularmc/registratetest/mod/localization/EnglishLabels.kt @@ -1,11 +1,11 @@ -package com.modularmc.registrate.test.mod.localization +package com.modularmc.registratetest.mod.localization import com.modularmc.registrate.localization.MinecraftLocale import com.modularmc.registrate.localization.annotation.Trans import com.modularmc.registrate.localization.annotation.TransVariants import com.modularmc.registrate.localization.annotation.Translation import com.modularmc.registrate.localization.annotation.Variant -import com.modularmc.registrate.test.mod.TestMod +import com.modularmc.registratetest.mod.TestMod @TransVariants( modId = TestMod.MOD_ID, @@ -16,6 +16,13 @@ import com.modularmc.registrate.test.mod.TestMod ], ) object EnglishLabels { + @field:Trans( + modId = TestMod.MOD_ID, + key = "gui.testmod.kotlin_default_label", + source = "Electric potential", + ) + const val DEFAULT_LABEL = "gui.testmod.kotlin_default_label" + @field:Trans( modId = TestMod.MOD_ID, key = "gui.testmod.container", diff --git a/src/test/java/com/modularmc/registrate/test/mod/package-info.java b/test/src/main/java/com/modularmc/registratetest/mod/package-info.java similarity index 73% rename from src/test/java/com/modularmc/registrate/test/mod/package-info.java rename to test/src/main/java/com/modularmc/registratetest/mod/package-info.java index c111488..9484040 100644 --- a/src/test/java/com/modularmc/registrate/test/mod/package-info.java +++ b/test/src/main/java/com/modularmc/registratetest/mod/package-info.java @@ -2,4 +2,4 @@ * Sample mod sources used as an integration harness for the public API. */ @org.jspecify.annotations.NullMarked -package com.modularmc.registrate.test.mod; +package com.modularmc.registratetest.mod; diff --git a/src/test/resources/META-INF/neoforge.mods.toml b/test/src/main/resources/META-INF/neoforge.mods.toml similarity index 100% rename from src/test/resources/META-INF/neoforge.mods.toml rename to test/src/main/resources/META-INF/neoforge.mods.toml diff --git a/src/test/resources/assets/testmod/textures/item/testentity_spawn_egg.png b/test/src/main/resources/assets/testmod/textures/item/testentity_spawn_egg.png similarity index 100% rename from src/test/resources/assets/testmod/textures/item/testentity_spawn_egg.png rename to test/src/main/resources/assets/testmod/textures/item/testentity_spawn_egg.png diff --git a/src/test/resources/assets/testmod/textures/item/testfluid_bucket.png b/test/src/main/resources/assets/testmod/textures/item/testfluid_bucket.png similarity index 100% rename from src/test/resources/assets/testmod/textures/item/testfluid_bucket.png rename to test/src/main/resources/assets/testmod/textures/item/testfluid_bucket.png diff --git a/src/test/resources/pack.mcmeta b/test/src/main/resources/pack.mcmeta similarity index 100% rename from src/test/resources/pack.mcmeta rename to test/src/main/resources/pack.mcmeta