| 1 | package net.minecraft.commands.functions;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableList;
|
| 4 | import com.google.common.collect.ImmutableList.Builder;
|
| 5 | import java.util.List;
|
| 6 |
|
| 7 | public record StringTemplate(List<String> segments, List<String> variables) {
|
| 8 | public static StringTemplate fromString(final String input) {
|
| 9 | Builder<String> segments = ImmutableList.builder();
|
| 10 | Builder<String> variables = ImmutableList.builder();
|
| 11 | int length = input.length();
|
| 12 | int start = 0;
|
| 13 | int index = input.indexOf(36);
|
| 14 |
|
| 15 | while (index != -1) {
|
| 16 | if (index != length - 1 && input.charAt(index + 1) == '(') {
|
| 17 | segments.add(input.substring(start, index));
|
| 18 | int variableEnd = input.indexOf(41, index + 1);
|
| 19 | if (variableEnd == -1) {
|
| 20 | throw new IllegalArgumentException("Unterminated macro variable");
|
| 21 | }
|
| 22 |
|
| 23 | String variable = input.substring(index + 2, variableEnd);
|
| 24 | if (!isValidVariableName(variable)) {
|
| 25 | throw new IllegalArgumentException("Invalid macro variable name '" + variable + "'");
|
| 26 | }
|
| 27 |
|
| 28 | variables.add(variable);
|
| 29 | start = variableEnd + 1;
|
| 30 | index = input.indexOf(36, start);
|
| 31 | } else {
|
| 32 | index = input.indexOf(36, index + 1);
|
| 33 | }
|
| 34 | }
|
| 35 |
|
| 36 | if (start == 0) {
|
| 37 | throw new IllegalArgumentException("No variables in macro");
|
| 38 | }
|
| 39 |
|
| 40 | if (start != length) {
|
| 41 | segments.add(input.substring(start));
|
| 42 | }
|
| 43 |
|
| 44 | return new StringTemplate(segments.build(), variables.build());
|
| 45 | }
|
| 46 |
|
| 47 | public static boolean isValidVariableName(final String variable) {
|
| 48 | for (int i = 0; i < variable.length(); i++) {
|
| 49 | char character = variable.charAt(i);
|
| 50 | if (!Character.isLetterOrDigit(character) && character != '_') {
|
| 51 | return false;
|
| 52 | }
|
| 53 | }
|
| 54 |
|
| 55 | return true;
|
| 56 | }
|
| 57 |
|
| 58 | public String substitute(final List<String> arguments) {
|
| 59 | StringBuilder builder = new StringBuilder();
|
| 60 |
|
| 61 | for (int i = 0; i < this.variables.size(); i++) {
|
| 62 | builder.append(this.segments.get(i)).append(arguments.get(i));
|
| 63 | CommandFunction.checkCommandLineLength(builder);
|
| 64 | }
|
| 65 |
|
| 66 | if (this.segments.size() > this.variables.size()) {
|
| 67 | builder.append(this.segments.getLast());
|
| 68 | }
|
| 69 |
|
| 70 | CommandFunction.checkCommandLineLength(builder);
|
| 71 | return builder.toString();
|
| 72 | }
|
| 73 | }
|
| 74 |
|