fix: do not send trailing/preceding whitespace to translate service (based on impl in Translater)
ci/woodpecker/push/jfmod Pipeline was successful Details

This commit is contained in:
Johannes Frohnmeyer 2023-11-20 14:39:21 +01:00
parent 88d44b6737
commit 49bdf4b921
Signed by: Johannes
GPG Key ID: E76429612C2929F4
1 changed files with 6 additions and 1 deletions

View File

@ -12,6 +12,8 @@ import net.minecraft.text.*;
import java.util.*;
import java.util.concurrent.ForkJoinPool;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GoogleChat implements ModInitializer {
public static final String MOD_ID = "google-chat";
@ -128,19 +130,22 @@ public class GoogleChat implements ModInitializer {
return style.withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, hoverText));
}
private static final Pattern SURROUNDING_SPACE_PATTERN = Pattern.compile("^(\\s*)(.*\\S+)(\\s*)$", Pattern.MULTILINE);
public static String translateIfNeeded(String source, TranslationDirection direction, boolean respectRegex) {
if (source == null) return null;
if (direction.shouldSkipOutright()) return source;
if (respectRegex && direction.failsRegex(source)) return source;
return computeIfAbsent2(direction == TranslationDirection.C2S ? c2ss : s2cs, source, t -> {
try {
Matcher m = SURROUNDING_SPACE_PATTERN.matcher(source);
if (!m.find()) return source;
// Ignore generics since this is apparently not something java supports
@SuppressWarnings("rawtypes") TranslateService svc = GoogleChat.TRANSLATE_SERVICE;
if (svc == null) throw new NullPointerException("Translate service uninitialized");
Language sourceLang = svc.parseLang(direction.source());
Language targetLang = svc.parseLang(direction.target());
//noinspection unchecked
return svc.translate(source, sourceLang, targetLang);
return m.group(1) + svc.translate(m.group(2), sourceLang, targetLang) + m.group(3);
} catch (Throwable e) {
LOGGER.error("Could not translate text: " + source, e);
return source;