forked from MinecraftFreecam/Freecam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidateRegexImpl.java
59 lines (51 loc) · 2.2 KB
/
ValidateRegexImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package net.xolt.freecam.config.gui;
import me.shedaniel.autoconfig.gui.registry.GuiRegistry;
import me.shedaniel.clothconfig2.gui.entries.StringListEntry;
import me.shedaniel.clothconfig2.gui.entries.StringListListEntry;
import net.minecraft.network.chat.Component;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import static net.xolt.freecam.config.gui.AutoConfigExtensions.isArrayOrListOfType;
class ValidateRegexImpl {
private ValidateRegexImpl() {}
static void apply(GuiRegistry registry) {
registry.registerAnnotationTransformer(
(guis, i18n, field, config, defaults, guiProvider) -> {
guis.stream()
.filter(StringListEntry.class::isInstance)
.map(StringListEntry.class::cast)
.forEach(entry -> entry.setErrorSupplier(() -> regexCompileError(entry.getValue())));
return guis;
},
field -> Objects.equals(String.class, field.getType()),
ValidateRegex.class
);
registry.registerAnnotationTransformer(
(guis, i18n, field, config, defaults, guiProvider) -> {
guis.stream()
.filter(StringListListEntry.class::isInstance)
.map(StringListListEntry.class::cast)
.forEach(entry -> entry.setCellErrorSupplier(ValidateRegexImpl::regexCompileError));
return guis;
},
isArrayOrListOfType(String.class),
ValidateRegex.class
);
}
/**
* Supplies an error message when the text is not a valid {@link Pattern regex pattern}.
*
* @param text the text that should compile to a regex.
* @return an optional error message.
*/
private static Optional<Component> regexCompileError(String text) {
try {
Pattern.compile(text);
return Optional.empty();
} catch (PatternSyntaxException e) {
return Optional.of(Component.literal(e.getLocalizedMessage()));
}
}
}