Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automatically add missing translation keys #73

Merged
merged 1 commit into from
Dec 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions src/main/java/com/dre/brewery/BreweryPlugin.java
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,16 @@ public void onEnable() {
SimpleItem.registerItemLoader(this);
PluginItem.registerItemLoader(this);

// Load config and lang
// Load config
Config config = ConfigManager.getConfig(Config.class);
ConfigManager.newInstance(Lang.class, false);

if (config.isFirstCreation()) {
config.onFirstCreation();
}

// Load lang
TranslationManager.getInstance().updateTranslationFiles();
ConfigManager.newInstance(Lang.class, false);

BSealer.registerRecipe(); // Sealing table recipe
ConfigManager.registerDefaultPluginItems(); // Register plugin items

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public void execute(BreweryPlugin breweryPlugin, Lang lang, CommandSender sender
try {
// Reload translation manager
TranslationManager.newInstance(breweryPlugin.getDataFolder());
TranslationManager.getInstance().updateTranslationFiles();

// Reload each config
for (var file : ConfigManager.LOADED_CONFIGS.values()) {
Expand Down
15 changes: 13 additions & 2 deletions src/main/java/com/dre/brewery/configuration/ConfigHead.java
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,11 @@ public <T extends AbstractOkaeriConfigFile> T createConfig(Class<T> configClass,
/**
* Create a new config instance using a config class' annotation
* @param configClass The class of the config to create
* @param file The file to use
* @return The new config instance
* @param <T> The type of the config
*/
public <T extends AbstractOkaeriConfigFile> T createConfig(Class<T> configClass) {
public <T extends AbstractOkaeriConfigFile> T createConfig(Class<T> configClass, Path file) {
OkaeriConfigFileOptions options = getOkaeriConfigFileOptions(configClass);

Configurer configurer = CONFIGURERS.get(options.configurer());
Expand All @@ -164,9 +165,19 @@ public <T extends AbstractOkaeriConfigFile> T createConfig(Class<T> configClass)
configurer = CONFIGURERS.get(BreweryXConfigurer.class);
}

return createConfig(configClass, getFilePath(configClass), configurer, new StandardSerdes(), options.update(), options.removeOrphans());
return createConfig(configClass, file, configurer, new StandardSerdes(), options.update(), options.removeOrphans());
}

/**
* Create a new config instance using a config class' annotation
* @param configClass The class of the config to create
* @return The new config instance
* @param <T> The type of the config
*/
public <T extends AbstractOkaeriConfigFile> T createConfig(Class<T> configClass) {
return createConfig(configClass, getFilePath(configClass));
}

@Nullable
public <T extends AbstractOkaeriConfigFile> T createBlankConfigInstance(Class<T> configClass) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,10 @@
package com.dre.brewery.configuration.configurer;

import com.dre.brewery.BreweryPlugin;
import com.dre.brewery.configuration.ConfigHead;
import com.dre.brewery.configuration.ConfigManager;
import com.dre.brewery.configuration.files.Config;
import com.dre.brewery.configuration.files.Lang;
import com.dre.brewery.utility.BUtil;
import com.dre.brewery.utility.Logging;
import lombok.Getter;
Expand All @@ -33,6 +35,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;

@Getter
Expand Down Expand Up @@ -108,6 +111,50 @@ public void createLanguageFile(Translation translation) {
ConfigManager.createFileFromResources("languages/" + translation.getFilename(), dataFolder.toPath().resolve("languages").resolve(translation.getFilename()));
}

// Okaeri would do this normally, but since default values in Lang changes based on language,
// we have to manually go through each file.
/**
* Updates all translation files by adding all missing keys.
* If a key hasn't been translated yet, english is used as a fallback.
*/
public void updateTranslationFiles() {
ConfigHead tempHead = new ConfigHead(); // Prevent polluting ConfigManager global state

Lang fallback = loadFromResources(tempHead, Translation.EN);
for (Translation trans : Translation.values()) {
if (trans == Translation.EN) {
continue;
}

String langFilePathStr = "languages/" + trans.getFilename();
Path langFilePath = dataFolder.toPath().resolve(langFilePathStr);

Lang langFromFile = tempHead.createConfig(Lang.class, langFilePath);
Lang langFromResources = loadFromResources(tempHead, trans);

langFromFile.updateMissingValuesFrom(langFromResources);
langFromFile.updateMissingValuesFrom(fallback);
langFromFile.save();
}
}

// Loads a lang from resources... by loading from file then overwriting with resources InputStream
// A bit of a hack, but avoids having to modify Okaeri
@Nullable
private Lang loadFromResources(ConfigHead tempHead, Translation translation) {
String langFilePathStr = "languages/" + translation.getFilename();
Path langFilePath = dataFolder.toPath().resolve(langFilePathStr);

Lang langFromResources = tempHead.createConfig(Lang.class, langFilePath);
try (InputStream inputStream = BreweryPlugin.class.getClassLoader().getResourceAsStream(langFilePathStr)) {
langFromResources.load(inputStream);
return langFromResources;
} catch (IOException e) {
Logging.errorLog("Failed to load " + langFilePathStr + " from resources", e);
return null;
}
}


public static void newInstance(File dataFolder) {
newInstance(dataFolder, false);
Expand Down
23 changes: 23 additions & 0 deletions src/main/java/com/dre/brewery/configuration/files/Lang.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import eu.okaeri.configs.annotation.Header;
import lombok.SneakyThrows;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.lang.reflect.Field;
Expand Down Expand Up @@ -70,6 +71,28 @@ public void reload() {
this.mapStrings();
}

public void updateMissingValuesFrom(@Nullable Lang other) {
if (other == null) {
return;
}

for (Field field : this.getClass().getDeclaredFields()) {
if (field.getType() != String.class) {
continue;
}

try {
String thisValue = (String) field.get(this);
String otherValue = (String) field.get(other);
if (thisValue == null && otherValue != null) {
field.set(this, otherValue);
}
} catch (IllegalAccessException e) {
Logging.errorLog("Lang failed to get a field value! &6(" + field.getName() + ")", e);
}
}
}

public void mapStrings() {
BreweryPlugin plugin = BreweryPlugin.getInstance();
Logging.log("Using language&7: &a" + this.getBindFile().getFileName());
Expand Down
1 change: 0 additions & 1 deletion src/main/resources/languages/ru.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,6 @@ Help_Delete: '&6/brew delete &9Удаляет зелье в твоей руке'
Help_Help: '&6/brew help [Page] &9Показывает определённую страницу помощи'
Help_Info: '&6/brew info&9 Показывает твоё текущее опьянение и качество'
Help_InfoOther: '&6/brew info [Player]&9 показывает текущее опьянение и качество [Player]'
Help_Player: '&6/brew <Player> <%Drunkeness> [Quality]&9 Даёт опьянение (и качество) игроку'
Help_Reload: '&6/brew reload &9Перезагружает конфиг'
Help_Configname: '&6/brew ItemName &9Показывает название предмета в руке для конфига'
Help_Static: '&6/brew static &9Make Статичная бражка -> Не будет стареть, не будет дистиллироваться'
Expand Down
1 change: 0 additions & 1 deletion src/main/resources/languages/zh.yml
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ Help_Delete: '&6/brew delete &9删除手中的饮品.'
Help_Help: '&6/brew help [页数] &9显示某一页的帮助.'
Help_Info: '&6/brew info &9显示你目前的醉酒程度与质量, 醉酒质量将会影响宿醉程度.'
Help_InfoOther: '&6/brew info [指定玩家] &9显示指定玩家目前的醉酒程度与质量.'
Help_Player: '&6/brew <目标玩家> <%醉酒程度> [醉酒质量] &9设定目标玩家的醉酒程度与质量.'
Help_Reload: '&6/brew reload &9重载插件配置, 可用以重载饮品配方.'
Help_Configname: '&6/brew ItemName &9显示手中物品的配置名称'
Help_Static: '&6/brew static &9将手中饮品静滞化, 这将阻止其被蒸馏或继续熟成.'
Expand Down