Allow rules to declare they only accept a set of options (#1560)

This commit is contained in:
altrisi authored and GitHub committed 2022-10-12 16:13:59 +02:00
1 parent b798d76d10
commit 635fb586c4
3 files changed
+20 -3

No files matched your search

@@ -85,6 +85,18 @@ public interface CarpetRule<T> {
*/
T defaultValue();
/**
* <p>Returns whether this rule is strict.</p>
*
* <p>A rule being strict means that it will only accept the suggestions returned by {@link #suggestions()} as valid values.</p>
*
* <p>Note that a rule implementation may return {@code false} in this method but still not accept options other than those
* returned in {@link #suggestions()}, only the opposite is guaranteed.</p>
*/
default boolean strict() {
return false;
}
/**
* <p>Sets this rule's value to the provided {@link String}, after first converting the {@link String} into a suitable type.</p>
*
@@ -533,7 +533,7 @@ public class SettingsManager {
ps.println("* Type: `" + rule.type().getSimpleName() + "` ");
ps.println("* Default value: `" + RuleHelper.toRuleString(rule.defaultValue()) + "` ");
String options = rule.suggestions().stream().map(s -> "`" + s + "`").collect(Collectors.joining(", "));
if (!options.isEmpty()) ps.println((rule instanceof ParsedRule<?> pr && pr.isStrict?"* Required":"* Suggested")+" options: " + options + " ");
if (!options.isEmpty()) ps.println((rule.strict() ? "* Required" : "* Suggested") + " options: " + options + " ");
ps.println("* Categories: " + rule.categories().stream().map(s -> "`" + s.toUpperCase(Locale.ROOT) + "`").collect(Collectors.joining(", ")) + " ");
if (rule instanceof ParsedRule<?>)
{
@@ -85,9 +85,9 @@ public final class ParsedRule<T> implements CarpetRule<T>, Comparable<ParsedRule
@Deprecated(forRemoval = true) // to private (and rename?)
public final List<String> options;
/**
* @deprecated No replacement for this
* @deprecated Use {@link CarpetRule#strict()} instead
*/
@Deprecated(forRemoval = true) // to pckg private (for printRulesToLog, or get a different way)
@Deprecated(forRemoval = true) // to remove or fix
public boolean isStrict;
/**
* @deprecated Use {@link CarpetRule#canBeToggledClientSide()} instead
@@ -391,6 +391,11 @@ public final class ParsedRule<T> implements CarpetRule<T>, Comparable<ParsedRule
set(source, value, RuleHelper.toRuleString(value));
}
@Override
public boolean strict() {
return !realValidators.isEmpty() && realValidators.get(0) instanceof Validator.StrictValidator;
}
private static <T> Map.Entry<Class<T>, FromStringConverter<T>> numericalConverter(Class<T> outputClass, Function<String, T> converter) {
return Map.entry(outputClass, str -> {
try {