Updates KnarLib, uses improved formatting and removes redundant code
This commit is contained in:
@@ -192,10 +192,10 @@ public final class EconomyConfig {
|
||||
this.vault = vault;
|
||||
return true;
|
||||
} else {
|
||||
Stargate.logInfo(Stargate.getString(Message.ECONOMY_LOAD_ERROR));
|
||||
Stargate.logInfo(new SGFormatBuilder(Message.ECONOMY_LOAD_ERROR).toString());
|
||||
}
|
||||
} else {
|
||||
Stargate.logInfo(Stargate.getString(Message.VAULT_LOAD_ERROR));
|
||||
Stargate.logInfo(new SGFormatBuilder(Message.VAULT_LOAD_ERROR).toString());
|
||||
}
|
||||
configOptions.put(ConfigOption.USE_ECONOMY, false);
|
||||
return false;
|
||||
|
@@ -113,10 +113,10 @@ public final class LanguageLoader {
|
||||
private void updateLanguage(@NotNull String language) {
|
||||
Map<Message, String> currentLanguageValues = load(language);
|
||||
|
||||
InputStream inputStream = getClass().getResourceAsStream("/lang/" + language + ".txt");
|
||||
InputStream inputStream = FileHelper.getInputStreamForInternalFile("/lang/" + language + ".txt");
|
||||
if (inputStream == null) {
|
||||
Stargate.logInfo(String.format("The language %s is not available. Falling back to english, You can add a " +
|
||||
"custom language by creating a new text file in the lang directory.", language));
|
||||
Stargate.logInfo(String.format("Unable to find internal language file for %s. This will normally not " +
|
||||
"cause any problems, except newly added translatable strings won't be automatically added", language));
|
||||
Stargate.debug("LanguageLoader::updateLanguage", String.format("Unable to load /lang/%s.txt", language));
|
||||
return;
|
||||
}
|
||||
@@ -209,6 +209,7 @@ public final class LanguageLoader {
|
||||
* @param lang <p>The language to load</p>
|
||||
* @return <p>A mapping between loaded string indexes and the strings to display</p>
|
||||
*/
|
||||
@Nullable
|
||||
private Map<Message, String> load(@NotNull String lang) {
|
||||
return load(lang, null);
|
||||
}
|
||||
@@ -220,6 +221,7 @@ public final class LanguageLoader {
|
||||
* @param inputStream <p>An optional input stream to use. Defaults to using a file input stream</p>
|
||||
* @return <p>A mapping between loaded string indexes and the strings to display</p>
|
||||
*/
|
||||
@Nullable
|
||||
private Map<Message, String> load(@NotNull String lang, @Nullable InputStream inputStream) {
|
||||
BufferedReader bufferedReader;
|
||||
try {
|
||||
@@ -257,6 +259,12 @@ public final class LanguageLoader {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a map from string key to message into a map from message key to message
|
||||
*
|
||||
* @param configurationStrings <p>The map to convert</p>
|
||||
* @return <p>The converted map</p>
|
||||
*/
|
||||
@NotNull
|
||||
private Map<Message, String> fromStringMap(@NotNull Map<String, String> configurationStrings) {
|
||||
Map<Message, String> output = new EnumMap<>(Message.class);
|
||||
|
@@ -1,62 +0,0 @@
|
||||
package net.knarcraft.stargate.config;
|
||||
|
||||
import net.md_5.bungee.api.ChatColor;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* The message sender is responsible sending messages to players with correct coloring and formatting
|
||||
*/
|
||||
public final class MessageSender {
|
||||
|
||||
private final LanguageLoader languageLoader;
|
||||
|
||||
/**
|
||||
* Instantiates a new message sender
|
||||
*
|
||||
* @param languageLoader <p>The language loader to get translated strings from</p>
|
||||
*/
|
||||
public MessageSender(@NotNull LanguageLoader languageLoader) {
|
||||
this.languageLoader = languageLoader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an error message to a player
|
||||
*
|
||||
* @param player <p>The player to send the message to</p>
|
||||
* @param message <p>The message to send</p>
|
||||
*/
|
||||
public void sendErrorMessage(@NotNull CommandSender player, @NotNull String message) {
|
||||
sendMessage(player, message, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a success message to a player
|
||||
*
|
||||
* @param player <p>The player to send the message to</p>
|
||||
* @param message <p>The message to send</p>
|
||||
*/
|
||||
public void sendSuccessMessage(@NotNull CommandSender player, @NotNull String message) {
|
||||
sendMessage(player, message, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message to a player
|
||||
*
|
||||
* @param sender <p>The player to send the message to</p>
|
||||
* @param message <p>The message to send</p>
|
||||
* @param error <p>Whether the message sent is an error</p>
|
||||
*/
|
||||
private void sendMessage(@NotNull CommandSender sender, @NotNull String message, boolean error) {
|
||||
if (message.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
message = ChatColor.translateAlternateColorCodes('&', message);
|
||||
if (error) {
|
||||
sender.sendMessage(ChatColor.RED + languageLoader.getString(Message.PREFIX) + ChatColor.WHITE + message);
|
||||
} else {
|
||||
sender.sendMessage(ChatColor.GREEN + languageLoader.getString(Message.PREFIX) + ChatColor.WHITE + message);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,40 @@
|
||||
package net.knarcraft.stargate.config;
|
||||
|
||||
import net.knarcraft.knarlib.formatting.FormatBuilder;
|
||||
import net.knarcraft.stargate.Stargate;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
/**
|
||||
* A customized format builder for automatic translation of Stargate messages
|
||||
*/
|
||||
public class SGFormatBuilder extends FormatBuilder {
|
||||
|
||||
/**
|
||||
* Instantiates a new format builder
|
||||
*/
|
||||
public SGFormatBuilder() {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Instantiates a new format builder
|
||||
*
|
||||
* <p>If the input is a list, it will be joined using the default delimiter: ",".</p>
|
||||
*
|
||||
* @param input <p>The input to use as the initial string of this format builder</p>
|
||||
* @throws IllegalStateException <p>If the string formatter has not been set, and the input is a translatable message</p>
|
||||
*/
|
||||
public <K> SGFormatBuilder(@NotNull K input) throws IllegalStateException {
|
||||
super(input);
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
protected <K> String asString(@NotNull K input, @NotNull String delimiter) {
|
||||
if (input instanceof Message message) {
|
||||
return Stargate.getStargateConfig().getLanguageLoader().getString(message);
|
||||
}
|
||||
return super.asString(input, delimiter);
|
||||
}
|
||||
|
||||
}
|
@@ -1,7 +1,9 @@
|
||||
package net.knarcraft.stargate.config;
|
||||
|
||||
import net.knarcraft.knarlib.formatting.StringFormatter;
|
||||
import net.knarcraft.knarlib.formatting.Translator;
|
||||
import net.knarcraft.knarlib.property.ColorConversion;
|
||||
import net.knarcraft.knarlib.util.FileHelper;
|
||||
import net.knarcraft.knarlib.util.ConfigHelper;
|
||||
import net.knarcraft.stargate.Stargate;
|
||||
import net.knarcraft.stargate.container.BlockChangeRequest;
|
||||
import net.knarcraft.stargate.listener.BungeeCordListener;
|
||||
@@ -14,16 +16,12 @@ import net.knarcraft.stargate.utility.PortalFileHelper;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.World;
|
||||
import org.bukkit.command.CommandSender;
|
||||
import org.bukkit.configuration.MemorySection;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.plugin.messaging.Messenger;
|
||||
import org.dynmap.DynmapAPI;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Map;
|
||||
@@ -44,7 +42,6 @@ public final class StargateConfig {
|
||||
private final HashSet<String> managedWorlds = new HashSet<>();
|
||||
|
||||
private StargateGateConfig stargateGateConfig;
|
||||
private MessageSender messageSender;
|
||||
private final LanguageLoader languageLoader;
|
||||
private EconomyConfig economyConfig;
|
||||
private final Logger logger;
|
||||
@@ -100,7 +97,9 @@ public final class StargateConfig {
|
||||
languageLoader.setChosenLanguage(languageName);
|
||||
languageLoader.reload();
|
||||
|
||||
messageSender = new MessageSender(languageLoader);
|
||||
// Update prefix of the format builder
|
||||
SGFormatBuilder.setStringFormatter(getStringFormatter());
|
||||
|
||||
if (isDebuggingEnabled()) {
|
||||
languageLoader.debug();
|
||||
}
|
||||
@@ -253,7 +252,10 @@ public final class StargateConfig {
|
||||
//Reload portal markers
|
||||
DynmapManager.addAllPortalMarkers();
|
||||
|
||||
messageSender.sendErrorMessage(sender, languageLoader.getString(Message.RELOADED));
|
||||
// Update prefix of the format builder
|
||||
SGFormatBuilder.setStringFormatter(getStringFormatter());
|
||||
|
||||
new SGFormatBuilder(Message.RELOADED).error(sender);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -398,14 +400,14 @@ public final class StargateConfig {
|
||||
*/
|
||||
public void loadConfig() {
|
||||
Stargate.getInstance().reloadConfig();
|
||||
FileConfiguration newConfig = Stargate.getInstance().getConfiguration();
|
||||
FileConfiguration newConfig = Stargate.getInstance().getConfig();
|
||||
|
||||
boolean isMigrating = false;
|
||||
if (newConfig.getString("lang") != null || newConfig.getString("economy.taxAccount") == null) {
|
||||
migrateConfig(newConfig);
|
||||
ConfigHelper.migrateConfig(Stargate.getInstance());
|
||||
isMigrating = true;
|
||||
Stargate.getInstance().reloadConfig();
|
||||
newConfig = Stargate.getInstance().getConfiguration();
|
||||
newConfig = Stargate.getInstance().getConfig();
|
||||
}
|
||||
|
||||
//Copy missing default values if any values are missing
|
||||
@@ -498,79 +500,6 @@ public final class StargateConfig {
|
||||
Stargate.logInfo(String.format("Loaded %s gate layouts", GateHandler.getGateCount()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes all configuration values from the old name to the new name
|
||||
*
|
||||
* @param currentConfiguration <p>The current config to back up</p>
|
||||
*/
|
||||
private void migrateConfig(@NotNull FileConfiguration currentConfiguration) {
|
||||
String debugPath = "StargateConfig::migrateConfig";
|
||||
|
||||
//Save the old config just in case something goes wrong
|
||||
try {
|
||||
currentConfiguration.save(new File(dataFolderPath, "config.yml.old"));
|
||||
} catch (IOException exception) {
|
||||
Stargate.debug(debugPath, "Unable to save old backup and do migration");
|
||||
return;
|
||||
}
|
||||
|
||||
//Load old and new configuration
|
||||
Stargate.getInstance().reloadConfig();
|
||||
FileConfiguration oldConfiguration = Stargate.getInstance().getConfig();
|
||||
InputStream configStream = FileHelper.getInputStreamForInternalFile("/config.yml");
|
||||
if (configStream == null) {
|
||||
Stargate.logSevere("Could not migrate the configuration, as the internal configuration could not be read!");
|
||||
return;
|
||||
}
|
||||
YamlConfiguration newConfiguration = StargateYamlConfiguration.loadConfiguration(
|
||||
FileHelper.getBufferedReaderFromInputStream(configStream));
|
||||
|
||||
//Read all available config migrations
|
||||
Map<String, String> migrationFields;
|
||||
try {
|
||||
InputStream migrationStream = FileHelper.getInputStreamForInternalFile("/config-migrations.txt");
|
||||
if (migrationStream == null) {
|
||||
Stargate.logSevere("Could not migrate the configuration, as the internal migration paths could not be read!");
|
||||
return;
|
||||
}
|
||||
migrationFields = FileHelper.readKeyValuePairs(FileHelper.getBufferedReaderFromInputStream(migrationStream),
|
||||
"=", ColorConversion.NORMAL);
|
||||
} catch (IOException exception) {
|
||||
Stargate.debug(debugPath, "Unable to load config migration file");
|
||||
return;
|
||||
}
|
||||
|
||||
//Replace old config names with the new ones
|
||||
for (String key : migrationFields.keySet()) {
|
||||
if (oldConfiguration.contains(key)) {
|
||||
String newPath = migrationFields.get(key);
|
||||
Object oldValue = oldConfiguration.get(key);
|
||||
if (!newPath.trim().isEmpty()) {
|
||||
oldConfiguration.set(newPath, oldValue);
|
||||
}
|
||||
oldConfiguration.set(key, null);
|
||||
}
|
||||
}
|
||||
|
||||
// Copy all keys to the new config
|
||||
for (String key : oldConfiguration.getKeys(true)) {
|
||||
if (oldConfiguration.get(key) instanceof MemorySection) {
|
||||
continue;
|
||||
}
|
||||
Stargate.debug(debugPath, "Setting " + key + " to " +
|
||||
oldConfiguration.get(key));
|
||||
newConfiguration.set(key, oldConfiguration.get(key));
|
||||
}
|
||||
|
||||
try {
|
||||
newConfiguration.save(new File(dataFolderPath, "config.yml"));
|
||||
} catch (IOException exception) {
|
||||
Stargate.debug(debugPath, "Unable to save migrated config");
|
||||
}
|
||||
|
||||
Stargate.getInstance().reloadConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads economy from Vault
|
||||
*/
|
||||
@@ -579,7 +508,7 @@ public final class StargateConfig {
|
||||
if (economyConfig.setupEconomy(Stargate.getPluginManager()) && economyConfig.getEconomy() != null &&
|
||||
economyConfig.getVault() != null) {
|
||||
String vaultVersion = economyConfig.getVault().getDescription().getVersion();
|
||||
Stargate.logInfo(Stargate.replacePlaceholders(Stargate.getString(Message.VAULT_LOADED), "%version%", vaultVersion));
|
||||
Stargate.logInfo(new SGFormatBuilder(Message.VAULT_LOADED).replace("%version%", vaultVersion).toString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -642,16 +571,6 @@ public final class StargateConfig {
|
||||
return gateFolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the sender for sending messages to players
|
||||
*
|
||||
* @return <p>The sender for sending messages to players</p>
|
||||
*/
|
||||
@NotNull
|
||||
public MessageSender getMessageSender() {
|
||||
return messageSender;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the language loader containing translated strings
|
||||
*
|
||||
@@ -662,4 +581,42 @@ public final class StargateConfig {
|
||||
return languageLoader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string formatter to use
|
||||
*/
|
||||
@NotNull
|
||||
private StringFormatter getStringFormatter() {
|
||||
// In order to allow automatic customization of prefix color, parse it properly
|
||||
String rawPrefix = getLanguageLoader().getString(Message.PREFIX);
|
||||
String colorPattern = "(?:[&§][a-fA-F0-9klmnor]|&?#[0-9a-fA-F]{6}|§x(?:§[a-fA-F0-9]){6})*";
|
||||
Pattern pattern = Pattern.compile("(" + colorPattern + "\\[" + colorPattern + ")(\\w+)(" +
|
||||
colorPattern + "]" + colorPattern + ")");
|
||||
|
||||
return getStringFormatter(rawPrefix, pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the string formatter to use
|
||||
*
|
||||
* @param rawPrefix <p>The formatter prefix to parse</p>
|
||||
* @param pattern <p>The pattern to use for parsing</p>
|
||||
*/
|
||||
private static @NotNull StringFormatter getStringFormatter(String rawPrefix, Pattern pattern) {
|
||||
String prefix = rawPrefix;
|
||||
String namePrefix = "[";
|
||||
String nameSuffix = "]";
|
||||
Matcher matcher = pattern.matcher(rawPrefix);
|
||||
if (matcher.find()) {
|
||||
namePrefix = matcher.group(1).trim();
|
||||
prefix = matcher.group(2).trim();
|
||||
nameSuffix = matcher.group(3).trim();
|
||||
}
|
||||
|
||||
StringFormatter stringFormatter = new StringFormatter(prefix, new Translator());
|
||||
stringFormatter.setColorConversion(ColorConversion.RGB);
|
||||
stringFormatter.setNamePrefix(namePrefix);
|
||||
stringFormatter.setNameSuffix(nameSuffix);
|
||||
return stringFormatter;
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -1,227 +0,0 @@
|
||||
package net.knarcraft.stargate.config;
|
||||
|
||||
import org.bukkit.configuration.InvalidConfigurationException;
|
||||
import org.bukkit.configuration.file.FileConfiguration;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.jetbrains.annotations.NotNull;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A YAML configuration which retains all comments
|
||||
*
|
||||
* <p>This configuration converts all comments to YAML values when loaded, which all start with comment_. When saved,
|
||||
* those YAML values are converted to normal text comments. This ensures that the comments aren't removed by the
|
||||
* YamlConfiguration during its parsing.</p>
|
||||
*
|
||||
* @author Kristian Knarvik
|
||||
* @author Thorin
|
||||
*/
|
||||
public class StargateYamlConfiguration extends YamlConfiguration {
|
||||
|
||||
private static final String START_OF_COMMENT_LINE = "[HASHTAG]";
|
||||
private static final String END_OF_COMMENT = "_endOfComment_";
|
||||
private static final String START_OF_COMMENT = "comment_";
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
@SuppressWarnings("deprecation")
|
||||
protected String buildHeader() {
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
@NotNull
|
||||
public String saveToString() {
|
||||
// Convert YAML comments to normal comments
|
||||
return this.convertYAMLMappingsToComments(super.saveToString());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void loadFromString(@NotNull String contents) throws InvalidConfigurationException {
|
||||
// Convert normal comments to YAML comments to prevent them from disappearing
|
||||
super.loadFromString(this.convertCommentsToYAMLMappings(contents));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a file with comments, and recreates them into yaml mappings
|
||||
*
|
||||
* <p>A mapping follows this format: comment_{CommentNumber}: "The comment"
|
||||
* This needs to be done as comments otherwise get removed using
|
||||
* the {@link FileConfiguration#save(File)} method. The config
|
||||
* needs to be saved if a config value has changed.</p>
|
||||
*/
|
||||
@NotNull
|
||||
private String convertCommentsToYAMLMappings(@NotNull String configString) {
|
||||
StringBuilder yamlBuilder = new StringBuilder();
|
||||
List<String> currentComment = new ArrayList<>();
|
||||
int commentId = 0;
|
||||
int previousIndentation = 0;
|
||||
|
||||
for (String line : configString.split("\n")) {
|
||||
String trimmed = line.trim();
|
||||
if (trimmed.startsWith("#")) {
|
||||
// Store the indentation of the block
|
||||
if (currentComment.isEmpty()) {
|
||||
previousIndentation = getIndentation(line);
|
||||
}
|
||||
//Temporarily store the comment line
|
||||
addComment(currentComment, trimmed);
|
||||
} else {
|
||||
addYamlString(yamlBuilder, currentComment, line, previousIndentation, commentId);
|
||||
commentId++;
|
||||
previousIndentation = 0;
|
||||
}
|
||||
}
|
||||
return yamlBuilder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a YAML string to the given string builder
|
||||
*
|
||||
* @param yamlBuilder <p>The string builder used for building YAML</p>
|
||||
* @param currentComment <p>The comment to add as a YAML string</p>
|
||||
* @param line <p>The current line</p>
|
||||
* @param previousIndentation <p>The indentation of the current block comment</p>
|
||||
* @param commentId <p>The id of the comment</p>
|
||||
*/
|
||||
private void addYamlString(@NotNull StringBuilder yamlBuilder, @NotNull List<String> currentComment,
|
||||
@NotNull String line, int previousIndentation, int commentId) {
|
||||
String trimmed = line.trim();
|
||||
//Write the full formatted comment to the StringBuilder
|
||||
if (!currentComment.isEmpty()) {
|
||||
int indentation = trimmed.isEmpty() ? previousIndentation : getIndentation(line);
|
||||
generateCommentYAML(yamlBuilder, currentComment, commentId, indentation);
|
||||
currentComment.clear();
|
||||
}
|
||||
//Add the non-comment line assuming it isn't empty
|
||||
if (!trimmed.isEmpty()) {
|
||||
yamlBuilder.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the given comment to the given list
|
||||
*
|
||||
* @param commentParts <p>The list to add to</p>
|
||||
* @param comment <p>The comment to add</p>
|
||||
*/
|
||||
private void addComment(@NotNull List<String> commentParts, @NotNull String comment) {
|
||||
if (comment.startsWith("# ")) {
|
||||
commentParts.add(comment.replaceFirst("# ", START_OF_COMMENT_LINE));
|
||||
} else {
|
||||
commentParts.add(comment.replaceFirst("#", START_OF_COMMENT_LINE));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a YAML-compatible string for one comment block
|
||||
*
|
||||
* @param yamlBuilder <p>The string builder to add the generated YAML to</p>
|
||||
* @param commentLines <p>The lines of the comment to convert into YAML</p>
|
||||
* @param commentId <p>The unique id of the comment</p>
|
||||
* @param indentation <p>The indentation to add to every line</p>
|
||||
*/
|
||||
private void generateCommentYAML(@NotNull StringBuilder yamlBuilder, @NotNull List<String> commentLines,
|
||||
int commentId, int indentation) {
|
||||
String subIndentation = this.addIndentation(indentation + 2);
|
||||
//Add the comment start marker
|
||||
yamlBuilder.append(this.addIndentation(indentation)).append(START_OF_COMMENT).append(commentId).append(": |\n");
|
||||
for (String commentLine : commentLines) {
|
||||
//Add each comment line with the proper indentation
|
||||
yamlBuilder.append(subIndentation).append(commentLine).append("\n");
|
||||
}
|
||||
//Add the comment end marker
|
||||
yamlBuilder.append(subIndentation).append(subIndentation).append(END_OF_COMMENT).append("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the internal YAML mapping format to a readable config file
|
||||
*
|
||||
* <p>The internal YAML structure is converted to a string with the same format as a standard configuration file.
|
||||
* The internal structure has comments in the format: START_OF_COMMENT + id + multi-line YAML string +
|
||||
* END_OF_COMMENT.</p>
|
||||
*
|
||||
* @param yamlString <p>A string using the YAML format</p>
|
||||
* @return <p>The corresponding comment string</p>
|
||||
*/
|
||||
@NotNull
|
||||
private String convertYAMLMappingsToComments(@NotNull String yamlString) {
|
||||
StringBuilder finalText = new StringBuilder();
|
||||
|
||||
String[] lines = yamlString.split("\n");
|
||||
for (int currentIndex = 0; currentIndex < lines.length; currentIndex++) {
|
||||
String line = lines[currentIndex];
|
||||
String possibleComment = line.trim();
|
||||
|
||||
if (possibleComment.startsWith(START_OF_COMMENT)) {
|
||||
//Add an empty line before every comment block
|
||||
finalText.append("\n");
|
||||
currentIndex = readComment(finalText, lines, currentIndex + 1, getIndentation(line));
|
||||
} else {
|
||||
//Output the configuration key
|
||||
finalText.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
return finalText.toString().trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully reads a comment
|
||||
*
|
||||
* @param builder <p>The string builder to write to</p>
|
||||
* @param lines <p>The lines to read from</p>
|
||||
* @param startIndex <p>The index to start reading from</p>
|
||||
* @param commentIndentation <p>The indentation of the read comment</p>
|
||||
* @return <p>The index containing the next non-comment line</p>
|
||||
*/
|
||||
private int readComment(@NotNull StringBuilder builder, @NotNull String[] lines, int startIndex,
|
||||
int commentIndentation) {
|
||||
for (int currentIndex = startIndex; currentIndex < lines.length; currentIndex++) {
|
||||
String line = lines[currentIndex];
|
||||
String possibleComment = line.trim();
|
||||
if (!line.contains(END_OF_COMMENT)) {
|
||||
possibleComment = possibleComment.replace(START_OF_COMMENT_LINE, "");
|
||||
builder.append(addIndentation(commentIndentation)).append("# ").append(possibleComment).append("\n");
|
||||
} else {
|
||||
return currentIndex;
|
||||
}
|
||||
}
|
||||
|
||||
return startIndex;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a string containing the given indentation
|
||||
*
|
||||
* @param indentationSpaces <p>The number spaces to use for indentation</p>
|
||||
* @return <p>A string containing the number of spaces specified</p>
|
||||
*/
|
||||
@NotNull
|
||||
private String addIndentation(int indentationSpaces) {
|
||||
return " ".repeat(Math.max(0, indentationSpaces));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets the indentation (number of spaces) of the given line
|
||||
*
|
||||
* @param line <p>The line to get indentation of</p>
|
||||
* @return <p>The number of spaces in the line's indentation</p>
|
||||
*/
|
||||
private int getIndentation(@NotNull String line) {
|
||||
int spacesFound = 0;
|
||||
for (char aCharacter : line.toCharArray()) {
|
||||
if (aCharacter == ' ') {
|
||||
spacesFound++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return spacesFound;
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user