From a536c6c558030b4b4ce70225eb6333d390b7d476 Mon Sep 17 00:00:00 2001 From: Ayham Al-Ali <20037329+AyhamAl-Ali@users.noreply.github.com> Date: Mon, 19 Feb 2024 04:06:08 +0300 Subject: [PATCH] WIP - Options Enum Values --- .../java/ch/njol/skript/SkriptConfig.java | 335 ++++++++---------- 1 file changed, 156 insertions(+), 179 deletions(-) diff --git a/src/main/java/ch/njol/skript/SkriptConfig.java b/src/main/java/ch/njol/skript/SkriptConfig.java index a8cb74a869b..ed800968390 100644 --- a/src/main/java/ch/njol/skript/SkriptConfig.java +++ b/src/main/java/ch/njol/skript/SkriptConfig.java @@ -58,42 +58,41 @@ /** * Important: don't save values from the config, a '/skript reload config/configs/all' won't work correctly otherwise! - * + * * @author Peter Güttinger */ @SuppressWarnings("unused") public class SkriptConfig { @Nullable - static Config mainConfig; + public static Config mainConfig; static Collection configs = new ArrayList<>(); - - static final Option version = new Option<>("version", Skript.getVersion().toString()) - .optional(true); - - public static final Option language = new Option<>("language", "english") + + + @SuppressWarnings("null") + private static final DateFormat shortDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); + + public enum Options { + VERSION(new Option<>("version", Skript.getVersion().toString()) + .optional(true)), + LANGUAGE(new Option<>("language", "english") .optional(true) .setter(s -> { if (!Language.load(s)) { Skript.error("No language file found for '" + s + "'!"); } - }); - - static final Option checkForNewVersion = new Option<>("check for new version", false) + })), + CHECK_FOR_NEW_VERSION(new Option<>("check for new version", false) .setter(t -> { SkriptUpdater updater = Skript.getInstance().getUpdater(); if (updater != null) updater.setEnabled(t); - }); - static final Option updateCheckInterval = new Option<>("update check interval", new Timespan(12 * 60 * 60 * 1000)) - .setter(t -> { - SkriptUpdater updater = Skript.getInstance().getUpdater(); - if (updater != null) - updater.setCheckFrequency(t.getTicks()); - }); - static final Option updaterDownloadTries = new Option<>("updater download tries", 7) - .optional(true); - static final Option releaseChannel = new Option<>("release channel", "none") + })), + UPDATE_CHECK_INTERVAL(new Option<>("updater download tries", 7) + .optional(true)), + UPDATER_DOWNLOAD_TRIES(new Option<>("updater download tries", 7) + .optional(true)), + RELEASE_CHANNEL(new Option<>("release channel", "none") .setter(t -> { ReleaseChannel channel; switch (t) { @@ -119,87 +118,55 @@ public class SkriptConfig { if (updater != null) { updater.setReleaseChannel(channel); } - }); - - public static final Option enableEffectCommands = new Option<>("enable effect commands", false); - public static final Option effectCommandToken = new Option<>("effect command token", "!"); - public static final Option allowOpsToUseEffectCommands = new Option<>("allow ops to use effect commands", false); - - /* - * @deprecated Will be removed in 2.8.0. Use {@link #logEffectCommands} instead. - */ - @Deprecated - public static final Option logPlayerCommands = new Option<>("log player commands", false).optional(true); - public static final Option logEffectCommands = new Option<>("log effect commands", false); - - // everything handled by Variables - public static final OptionSection databases = new OptionSection("databases"); - - public static final Option usePlayerUUIDsInVariableNames = new Option<>("use player UUIDs in variable names", false); // TODO change to true later (as well as in the default config) - public static final Option enablePlayerVariableFix = new Option<>("player variable fix", true); - - @SuppressWarnings("null") - private static final DateFormat shortDateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT); - private static final Option dateFormat = new Option<>("date format", shortDateFormat, s -> { - try { - if (s.equalsIgnoreCase("default")) - return null; - return new SimpleDateFormat(s); - } catch (final IllegalArgumentException e) { - Skript.error("'" + s + "' is not a valid date format. Please refer to https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html for instructions on the format."); - } - return null; - }); - - public static String formatDate(final long timestamp) { - final DateFormat f = dateFormat.value(); - synchronized (f) { - return "" + f.format(timestamp); - } - } - - static final Option verbosity = new Option<>("verbosity", Verbosity.NORMAL, new EnumParser<>(Verbosity.class, "verbosity")) - .setter(SkriptLogger::setVerbosity); - - public static final Option defaultEventPriority = new Option<>("plugin priority", EventPriority.NORMAL, s -> { - try { - return EventPriority.valueOf(s.toUpperCase(Locale.ENGLISH)); - } catch (final IllegalArgumentException e) { - Skript.error("The plugin priority has to be one of lowest, low, normal, high, or highest."); + })), + ENABLE_EFFECT_COMMANDS(new Option<>("enable effect commands", false)), + EFFECT_COMMAND_TOKEN(new Option<>("effect command token", "!")), + ALLOW_OPS_TO_USE_EFFECT_COMMANDS(new Option<>("allow ops to use effect commands", false)), + /* + * @deprecated Will be removed in 2.8.0. Use {@link #logEffectCommands} instead. + */ + @Deprecated + LOG_PLAYER_COMMANDS(new Option<>("log player commands", false).optional(true)), + LOG_EFFECT_COMMANDS(new Option<>("log effect commands", false)), + DATABASES(new OptionSection("databases")), + USE_PLAYER_UUIDS_IN_VARIABLE_NAMES(new Option<>("use player UUIDs in variable names", false)), + ENABLE_PLAYER_VARIABLE_FIX(new Option<>("player variable fix", true)), + DATE_FORMAT(new Option<>("date format", shortDateFormat, s -> { + try { + if (s.equalsIgnoreCase("default")) + return null; + return new SimpleDateFormat(s); + } catch (final IllegalArgumentException e) { + Skript.error("'" + s + "' is not a valid date format. Please refer to https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html for instructions on the format."); + } return null; - } - }); - - - /** - * Maximum number of digits to display after the period for floats and doubles - */ - public static final Option numberAccuracy = new Option<>("number accuracy", 2); - - public static final Option maxTargetBlockDistance = new Option<>("maximum target block distance", 100); - - public static final Option caseSensitive = new Option<>("case sensitive", false); - public static final Option allowFunctionsBeforeDefs = new Option<>("allow function calls before definations", false) - .optional(true); - - public static final Option disableObjectCannotBeSavedWarnings = new Option<>("disable variable will not be saved warnings", false); - public static final Option disableMissingAndOrWarnings = new Option<>("disable variable missing and/or warnings", false); - public static final Option disableVariableStartingWithExpressionWarnings = - new Option<>("disable starting a variable's name with an expression warnings", false); - - @Deprecated - public static final Option enableScriptCaching = new Option<>("enable script caching", false) - .optional(true); - - public static final Option keepConfigsLoaded = new Option<>("keep configs loaded", false) - .optional(true); - - public static final Option addonSafetyChecks = new Option<>("addon safety checks", false) - .optional(true); - - public static final Option apiSoftExceptions = new Option<>("soft api exceptions", false); - - public static final Option enableTimings = new Option<>("enable timings", false) + })), + VERBOSITY(new Option<>("verbosity", Verbosity.NORMAL, new EnumParser<>(Verbosity.class, "verbosity")) + .setter(SkriptLogger::setVerbosity)), + DEFAULT_EVENT_PRIORITY(new Option<>("plugin priority", EventPriority.NORMAL, s -> { + try { + return EventPriority.valueOf(s.toUpperCase(Locale.ENGLISH)); + } catch (final IllegalArgumentException e) { + Skript.error("The plugin priority has to be one of lowest, low, normal, high, or highest."); + return null; + } + })), + NUMBER_ACCURACY(new Option<>("number accuracy", 2)), + MAX_TARGET_BLOCK_DISTANCE(new Option<>("maximum target block distance", 100)), + CASE_SENSITIVE(new Option<>("case sensitive", false)), + ALLOW_FUNCTIONS_BEFORE_DEFS(new Option<>("allow function calls before definations", false) + .optional(true)), + DISABLE_OBJECT_CANNOT_BE_SAVED_WARNINGS(new Option<>("disable variable will not be saved warnings", false)), + DISABLE_MISSING_AND_OR_WARNINGS(new Option<>("disable variable missing and/or warnings", false)), + DISABLE_VARIABLE_STARTING_WITH_EXPRESSION_WARNINGS(new Option<>("disable starting a variable's name with an expression warnings", false)), + ENABLE_SCRIPT_CACHING(new Option<>("enable script caching", false) + .optional(true)), + KEEP_CONFIGS_LOADED(new Option<>("keep configs loaded", false) + .optional(true)), + ADDON_SAFETY_CHECKS(new Option<>("addon safety checks", false) + .optional(true)), + API_SOFT_EXCEPTIONS(new Option<>("soft api exceptions", false)), + ENABLE_TIMINGS(new Option<>("enable timings", false) .setter(t -> { if (!Skript.classExists("co.aikar.timings.Timings")) { // Check for Timings if (t) // Warn the server admin that timings won't work @@ -217,9 +184,8 @@ public static String formatDate(final long timestamp) { if (t) Skript.info("Timings support enabled!"); SkriptTimings.setEnabled(t); // Config option will be used - }); - - public static final Option parseLinks = new Option<>("parse links in chat messages", "disabled") + })), + PARSE_LINKS(new Option<>("parse links in chat messages", "disabled") .setter(t -> { try { switch (t) { @@ -241,24 +207,21 @@ public static String formatDate(final long timestamp) { } catch (Error e) { // Ignore it, we're on unsupported server platform and class loading failed } - }); - - public static final Option caseInsensitiveVariables = new Option<>("case-insensitive variables", true) - .setter(t -> Variables.caseInsensitiveVariables = t); - - public static final Option colorResetCodes = new Option<>("color codes reset formatting", true) + })), + CASE_INSENSITIVE_VARIABLES(new Option<>("case-insensitive variables", true) + .setter(t -> Variables.caseInsensitiveVariables = t)), + COLOR_RESET_CODES(new Option<>("color codes reset formatting", true) .setter(t -> { try { ChatMessages.colorResetCodes = t; } catch (Error e) { // Ignore it, we're on unsupported server platform and class loading failed } - }); - - public static final Option scriptLoaderThreadSize = new Option<>("script loader thread size", "0") + })), + SCRIPT_LOADER_THREAD_SIZE(new Option<>("script loader thread size", "0") .setter(s -> { int asyncLoaderSize; - + if (s.equalsIgnoreCase("processor count")) { asyncLoaderSize = Runtime.getRuntime().availableProcessors(); } else { @@ -269,49 +232,74 @@ public static String formatDate(final long timestamp) { return; } } - + ScriptLoader.setAsyncLoaderSize(asyncLoaderSize); }) - .optional(true); - - public static final Option allowUnsafePlatforms = new Option<>("allow unsafe platforms", false) - .optional(true); + .optional(true)), + ALLOW_UNSAFE_PLATFORMS(new Option<>("allow unsafe platforms", false) + .optional(true)), + KEEP_LAST_USAGE_DATES(new Option<>("keep command last usage dates", false) + .optional(true)), + LOAD_DEFAULT_ALIASES(new Option<>("load default aliases", true) + .optional(true)), + EXECUTE_FUNCTIONS_WITH_MISSING_PARAMS(new Option<>("execute functions with missing parameters", true) + .optional(true) + .setter(t -> Function.executeWithNulls = t)), + DISABLE_HOOK_VAULT(new Option<>("disable hooks.vault", false) + .optional(true) + .setter(value -> { + userDisableHooks(VaultHook.class, value); + })), + DISABLE_HOOK_GRIEF_PREVENTION(new Option<>("disable hooks.regions.grief prevention", false) + .optional(true) + .setter(value -> { + userDisableHooks(GriefPreventionHook.class, value); + })), + DISABLE_HOOK_PRECIOUS_STONES(new Option<>("disable hooks.regions.precious stones", false) + .optional(true) + .setter(value -> { + userDisableHooks(PreciousStonesHook.class, value); + })), + DISABLE_HOOK_RESIDENCE(new Option<>("disable hooks.regions.residence", false) + .optional(true) + .setter(value -> { + userDisableHooks(ResidenceHook.class, value); + })), + DISABLE_HOOK_WORLD_GUARD(new Option<>("disable hooks.regions.worldguard", false) + .optional(true) + .setter(value -> { + userDisableHooks(WorldGuardHook.class, value); + })), + PLAYER_NAME_REGEX_PATTERN(new Option<>("player name regex pattern", Pattern.compile("[a-zA-Z0-9_]{1,16}"), s -> { + try { + return Pattern.compile(s); + } catch (PatternSyntaxException e) { + Skript.error("Invalid player name regex pattern: " + e.getMessage()); + return null; + } + }).optional(true)), + LONG_PARSE_TIME_WARNING_THRESHOLD(new Option<>("long parse time warning threshold", new Timespan(0))); - public static final Option keepLastUsageDates = new Option<>("keep command last usage dates", false) - .optional(true); - - public static final Option loadDefaultAliases = new Option<>("load default aliases", true) - .optional(true); + private Option option; + private OptionSection optionSection; - public static final Option executeFunctionsWithMissingParams = new Option<>("execute functions with missing parameters", true) - .optional(true) - .setter(t -> Function.executeWithNulls = t); + Options(Option option) { + this.option = option; + } + + Options(OptionSection optionSection) { + this.optionSection = optionSection; + } + + public Option getOption() { + return option; + } + + public void setOption(Option option) { + this.option = option; + } + } - public final static Option disableHookVault = new Option<>("disable hooks.vault", false) - .optional(true) - .setter(value -> { - userDisableHooks(VaultHook.class, value); - }); - public final static Option disableHookGriefPrevention = new Option<>("disable hooks.regions.grief prevention", false) - .optional(true) - .setter(value -> { - userDisableHooks(GriefPreventionHook.class, value); - }); - public final static Option disableHookPreciousStones = new Option<>("disable hooks.regions.precious stones", false) - .optional(true) - .setter(value -> { - userDisableHooks(PreciousStonesHook.class, value); - }); - public final static Option disableHookResidence = new Option<>("disable hooks.regions.residence", false) - .optional(true) - .setter(value -> { - userDisableHooks(ResidenceHook.class, value); - }); - public final static Option disableHookWorldGuard = new Option<>("disable hooks.regions.worldguard", false) - .optional(true) - .setter(value -> { - userDisableHooks(WorldGuardHook.class, value); - }); /** * Disables the specified hook depending on the option value, or gives an error if this isn't allowed at this time. */ @@ -326,17 +314,6 @@ private static void userDisableHooks(Class> hookClass, boolean } } - public final static Option playerNameRegexPattern = new Option<>("player name regex pattern", Pattern.compile("[a-zA-Z0-9_]{1,16}"), s -> { - try { - return Pattern.compile(s); - } catch (PatternSyntaxException e) { - Skript.error("Invalid player name regex pattern: " + e.getMessage()); - return null; - } - }).optional(true); - - public static final Option longParseTimeWarningThreshold = new Option<>("long parse time warning threshold", new Timespan(0)); - /** * This should only be used in special cases */ @@ -344,7 +321,7 @@ private static void userDisableHooks(Class> hookClass, boolean public static Config getConfig() { return mainConfig; } - + // also used for reloading static boolean load() { try { @@ -366,7 +343,7 @@ static boolean load() { Skript.error("Config file 'config.sk' cannot be read!"); return false; } - + Config mc; try { mc = new Config(configFile, false, false, ":"); @@ -376,7 +353,7 @@ static boolean load() { } mainConfig = mc; - String configVersion = mc.get(version.key); + String configVersion = mc.get(Options.VERSION.option.key); if (configVersion == null || Skript.getVersion().compareTo(new Version(configVersion)) != 0) { try { final InputStream in = Skript.getInstance().getResource("config.sk"); @@ -386,27 +363,27 @@ static boolean load() { } final Config newConfig = new Config(in, "Skript.jar/config.sk", false, false, ":"); in.close(); - + boolean forceUpdate = false; - + if (mc.getMainNode().get("database") != null) { // old database layout forceUpdate = true; try { final SectionNode oldDB = (SectionNode) mc.getMainNode().get("database"); assert oldDB != null; - final SectionNode newDBs = (SectionNode) newConfig.getMainNode().get(databases.key); + final SectionNode newDBs = (SectionNode) newConfig.getMainNode().get(Options.DATABASES.optionSection.key); assert newDBs != null; final SectionNode newDB = (SectionNode) newDBs.get("database 1"); assert newDB != null; - + newDB.setValues(oldDB); - + // '.db' was dynamically added before final String file = newDB.getValue("file"); assert file != null; if (!file.endsWith(".db")) newDB.set("file", file + ".db"); - + final SectionNode def = (SectionNode) newDBs.get("default"); assert def != null; def.set("backup interval", "" + mc.get("variables backup interval")); @@ -418,26 +395,26 @@ static boolean load() { return false; } } - - if (newConfig.setValues(mc, version.key, databases.key) || forceUpdate) { // new config is different + + if (newConfig.setValues(mc, Options.VERSION.option.key, Options.DATABASES.optionSection.key) || forceUpdate) { // new config is different final File bu = FileUtils.backup(configFile); - newConfig.getMainNode().set(version.key, Skript.getVersion().toString()); - if (mc.getMainNode().get(databases.key) != null) - newConfig.getMainNode().set(databases.key, mc.getMainNode().get(databases.key)); + newConfig.getMainNode().set(Options.VERSION.option.key, Skript.getVersion().toString()); + if (mc.getMainNode().get(Options.DATABASES.optionSection.key) != null) + newConfig.getMainNode().set(Options.DATABASES.optionSection.key, mc.getMainNode().get(Options.DATABASES.optionSection.key)); mc = mainConfig = newConfig; mc.save(configFile); Skript.info("Your configuration has been updated to the latest version. A backup of your old config file has been created as " + bu.getName()); } else { // only the version changed - mc.getMainNode().set(version.key, Skript.getVersion().toString()); + mc.getMainNode().set(Options.VERSION.option.key, Skript.getVersion().toString()); mc.save(configFile); } } catch (final IOException e) { Skript.error("Could not load the new config from the jar file: " + e.getLocalizedMessage()); } } - + mc.load(SkriptConfig.class); - + // if (!keepConfigsLoaded.value()) // mainConfig = null; } catch (final RuntimeException e) {