Skip to content

Commit

Permalink
feat: added a few more command substitutions
Browse files Browse the repository at this point in the history
Also re-did the templating algorithm; should be more performant as the
number of overrides increases

FTBTeam/FTB-Mods-Issues#1311
  • Loading branch information
desht committed Aug 16, 2024
1 parent b23a74a commit ffd3a44
Showing 1 changed file with 36 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,16 @@
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.server.level.ServerPlayer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommandReward extends Reward {
private static final String DEFAULT_COMMAND = "/say Hi, @p!";
public static final Pattern PATTERN = Pattern.compile("[{](\\w+)}");

private String command;
private boolean elevatePerms;
Expand Down Expand Up @@ -93,17 +98,15 @@ public void claim(ServerPlayer player, boolean notify) {
}

overrides.put("quest", quest);
overrides.put("team", FTBTeamsAPI.api().getManager().getTeamForPlayer(player)
.map(team -> team.getName().getString())
.orElse(player.getGameProfile().getName())
);

String cmd = command;
for (Map.Entry<String, Object> entry : overrides.entrySet()) {
if (entry.getValue() != null) {
cmd = cmd.replace("{" + entry.getKey() + "}", entry.getValue().toString());
}
}
FTBTeamsAPI.api().getManager().getTeamForPlayer(player).ifPresent(team -> {
overrides.put("team", team.getName().getString());
overrides.put("team_id", team.getShortName());
overrides.put("long_team_id", team.getId().toString());
overrides.put("member_count", team.getMembers().size());
overrides.put("online_member_count", team.getOnlineMembers().size());
});

String cmd = format(command, overrides);

CommandSourceStack source = player.createCommandSourceStack();
if (elevatePerms) source = source.withPermission(2);
Expand All @@ -117,4 +120,26 @@ public void claim(ServerPlayer player, boolean notify) {
public MutableComponent getAltTitle() {
return Component.translatable("ftbquests.reward.ftbquests.command").append(": ").append(Component.literal(command).withStyle(ChatFormatting.RED));
}

public static String format(String template, Map<String, Object> parameters) {
StringBuilder newTemplate = new StringBuilder(template);
List<Object> valueList = new ArrayList<>();

Matcher matcher = PATTERN.matcher(template);

while (matcher.find()) {
String key = matcher.group(1);

if (parameters.containsKey(key)) {
String paramName = "{" + key + "}";
int index = newTemplate.indexOf(paramName);
if (index != -1) {
newTemplate.replace(index, index + paramName.length(), "%s");
valueList.add(parameters.get(key));
}
}
}

return String.format(newTemplate.toString(), valueList.toArray());
}
}

0 comments on commit ffd3a44

Please sign in to comment.