Skip to content

Commit

Permalink
convert array comments to json5 comments
Browse files Browse the repository at this point in the history
  • Loading branch information
deirn committed Aug 8, 2024
1 parent cddc322 commit df305af
Show file tree
Hide file tree
Showing 8 changed files with 81 additions and 80 deletions.
12 changes: 9 additions & 3 deletions src/api/java/mcp/mobius/waila/api/IJsonConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.nio.file.Path;
import java.util.function.Function;
import java.util.function.ObjIntConsumer;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
Expand Down Expand Up @@ -87,7 +86,7 @@ default void backup() {
/**
* Adds comment for this value.
*
* @see Builder1#commenter(Function)
* @see Builder1#commenter(Commenter)
*/
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
Expand All @@ -100,6 +99,13 @@ default void backup() {

}

interface Commenter {

@Nullable
String getComment(String path);

}

interface Builder0<T> {

Builder1<T> file(File file);
Expand All @@ -116,7 +122,7 @@ interface Builder1<T> {

Builder1<T> json5();

Builder1<T> commenter(Function<String, @Nullable String> commenter);
Builder1<T> commenter(Commenter commenter);

Builder1<T> gson(Gson gson);

Expand Down
1 change: 1 addition & 0 deletions src/main/java/mcp/mobius/waila/Waila.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ public abstract class Waila {
.file(WailaConstants.NAMESPACE + "/blacklist")
.version(BlacklistConfig.VERSION, BlacklistConfig::getConfigVersion, BlacklistConfig::setConfigVersion)
.json5()
.commenter(BlacklistConfig.COMMENTER)
.gson(new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(BlacklistConfig.class, new BlacklistConfig.Adapter())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashSet;
import java.util.function.Function;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
Expand All @@ -14,11 +13,11 @@
public record AnnotationCommenter(
Type type,
Gson gson,
Function<String, @Nullable String> extra
) implements Function<String, @Nullable String> {
IJsonConfig.Commenter extra
) implements IJsonConfig.Commenter {

@Override
public @Nullable String apply(String path) {
public @Nullable String getComment(String path) {
String annotationComment = null;
if (type instanceof Class<?> cls) {
AnnotatedElement element = null;
Expand Down Expand Up @@ -53,7 +52,7 @@ public record AnnotationCommenter(
}
}

var extraComment = extra.apply(path);
var extraComment = extra.getComment(path);

if (annotationComment == null) return extraComment;
if (extraComment == null) return annotationComment;
Expand Down
24 changes: 10 additions & 14 deletions src/main/java/mcp/mobius/waila/config/BlacklistConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import com.google.gson.JsonSerializer;
import mcp.mobius.waila.Waila;
import mcp.mobius.waila.api.IBlacklistConfig;
import mcp.mobius.waila.api.IJsonConfig;
import mcp.mobius.waila.api.IRegistryFilter;
import mcp.mobius.waila.util.Log;
import net.minecraft.core.Registry;
Expand All @@ -32,11 +33,20 @@ public class BlacklistConfig {
private static final String BLACKLIST_TAG = "#" + Waila.id("blacklist");

public static final int VERSION = 0;
public static final IJsonConfig.Commenter COMMENTER = path -> !path.equals("$") ? null : """
Run `/waila reload` to apply changes server-wide.
Run `/wailac reload` to apply changes to only your client.
%s
The `%s` tag rule can not be removed"""
.formatted(IRegistryFilter.getHeader(), BLACKLIST_TAG);

public final LinkedHashSet<String> blocks = new LinkedHashSet<>();
public final LinkedHashSet<String> blockEntityTypes = new LinkedHashSet<>();
public final LinkedHashSet<String> entityTypes = new LinkedHashSet<>();

@IJsonConfig.Comment("\nThe values below are used internally by WTHIT, you SHOULD NOT modify it!")
private int configVersion = 0;
public int[] pluginHash = {0, 0, 0};

Expand Down Expand Up @@ -119,20 +129,6 @@ public static class Adapter implements JsonSerializer<BlacklistConfig>, JsonDese
public JsonElement serialize(BlacklistConfig src, Type typeOfSrc, JsonSerializationContext context) {
var object = new JsonObject();

var comments = """
Run /waila reload to apply changes server-wide.
Run /wailac reload to apply changes to only your client.
%s
The %s tag rule can not be removed"""
.formatted(IRegistryFilter.getHeader(), BLACKLIST_TAG)
.split("\n");

var commentArray = new JsonArray();
for (var line : comments) commentArray.add(line);
object.add("_comment", commentArray);

src.addBlacklistTags();

object.add("blocks", context.serialize(src.blocks));
Expand Down
12 changes: 6 additions & 6 deletions src/main/java/mcp/mobius/waila/config/JsonConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import java.util.Date;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.function.Function;
import java.util.function.ObjIntConsumer;
import java.util.function.Supplier;
import java.util.function.ToIntFunction;
Expand All @@ -24,7 +23,6 @@
import mcp.mobius.waila.mcless.config.ConfigIo;
import mcp.mobius.waila.util.CachedSupplier;
import mcp.mobius.waila.util.Log;
import org.apache.commons.io.FilenameUtils;
import org.jetbrains.annotations.Nullable;

public class JsonConfig<T> implements IJsonConfig<T> {
Expand All @@ -41,9 +39,11 @@ public class JsonConfig<T> implements IJsonConfig<T> {
private final CachedSupplier<T> getter;

@SuppressWarnings("unchecked")
JsonConfig(Path path, Type type, Supplier<T> factory, boolean json5, Function<String, @Nullable String> commenter, Gson gson, int currentVersion, ToIntFunction<T> versionGetter, ObjIntConsumer<T> versionSetter) {
JsonConfig(Path path, Type type, Supplier<T> factory, boolean json5, Commenter commenter, Gson gson, int currentVersion, ToIntFunction<T> versionGetter, ObjIntConsumer<T> versionSetter) {
this.path = path.toAbsolutePath();
this.io = new ConfigIo<>(LOG::warn, LOG::error, json5, new AnnotationCommenter(type, gson, commenter), gson, type, factory, currentVersion, versionGetter, versionSetter);

var annotationCommenter = new AnnotationCommenter(type, gson, commenter);
this.io = new ConfigIo<>(LOG::warn, LOG::error, json5, annotationCommenter::getComment, gson, type, factory, currentVersion, versionGetter, versionSetter);
this.getter = new CachedSupplier<>(() -> io.read(this.path));

INSTANCES.add((JsonConfig<Object>) this);
Expand Down Expand Up @@ -103,7 +103,7 @@ public static class Builder<T> implements Builder0<T>, Builder1<T> {
final Type type;
Supplier<Path> path;
boolean json5;
Function<String, @Nullable String> commenter;
Commenter commenter;
Gson gson;
int currentVersion;
ToIntFunction<T> versionGetter;
Expand Down Expand Up @@ -178,7 +178,7 @@ public Builder1<T> json5() {
}

@Override
public Builder1<T> commenter(Function<String, @Nullable String> commenter) {
public Builder1<T> commenter(Commenter commenter) {
this.commenter = commenter;
return this;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// - Remove unused members
// - Directly extends GSON's JsonWriter
// - Added generic commenter function
// - Fixed issue with character replacement table (https://github.com/QuiltMC/quilt-parsers/pull/5)
// https://github.com/QuiltMC/quilt-parsers/blob/00803c4e70fb0cf93765593eaae5c781b1505bee/json/src/main/java/org/quiltmc/parsers/json/JsonWriter.java
// @formatter:off

Expand Down Expand Up @@ -182,16 +183,16 @@ public final class Json5Writer extends JsonWriter {
private String deferredName;
private String deferredComment;

private final Function<String, @Nullable String> commenter;
private String[] pathNames = new String[32];
private final Function<String, @Nullable String> commenter;
private String[] pathNames = new String[32];

// API methods

public Json5Writer(Writer out, Function<String, @Nullable String> commenter) {
super(Writer.nullWriter());
Objects.requireNonNull(out, "Writer cannot be null");
this.out = out;
this.commenter = commenter;
this.commenter = commenter;
}

/**
Expand All @@ -211,8 +212,8 @@ public Json5Writer name(String name) throws IOException {
throw new IllegalStateException("JsonWriter is closed.");
}
deferredName = name;
pathNames[stackSize - 1] = name;
comment(commenter.apply(getPath()));
pathNames[stackSize - 1] = name;
comment(commenter.apply(getPath()));
return this;
}

Expand Down Expand Up @@ -455,7 +456,7 @@ private Json5Writer close(int empty, int nonempty, char closeBracket)
}

stackSize--;
pathNames[stackSize] = null;
pathNames[stackSize] = null;
if (context == nonempty) {
commentAndNewline();
}
Expand All @@ -465,9 +466,9 @@ private Json5Writer close(int empty, int nonempty, char closeBracket)

private void push(int newTop) {
if (stackSize == stack.length) {
int newLength = stackSize * 2;
int newLength = stackSize * 2;
stack = Arrays.copyOf(stack, newLength);
pathNames = Arrays.copyOf(pathNames, newLength);
pathNames = Arrays.copyOf(pathNames, newLength);
}
stack[stackSize++] = newTop;
}
Expand Down Expand Up @@ -536,17 +537,16 @@ private void string(String value, boolean quotes, boolean escapeQuotes) throws I
out.write('\"');
}

if (!escapeQuotes) {
replacements['\"'] = null;
}

int last = 0;
int length = value.length();

for (int i = 0; i < length; i++) {
char c = value.charAt(i);
String replacement;
if (c < 128) {
if (c == '"' && !escapeQuotes) {
continue;
}
replacement = replacements[c];
if (replacement == null) {
continue;
Expand Down Expand Up @@ -611,7 +611,7 @@ private void beforeValue() throws IOException {
"JSON must have only one top-level value.");
// fall-through
case Json5Scope.EMPTY_DOCUMENT: // first in document
comment(commenter.apply("$"));
comment(commenter.apply("$"));
writeDeferredComment();
replaceTop(Json5Scope.NONEMPTY_DOCUMENT);
break;
Expand All @@ -636,29 +636,29 @@ private void beforeValue() throws IOException {
}
}

public String getPath() {
StringBuilder result = new StringBuilder().append('$');
for (int i = 0; i < stackSize; i++) {
switch (stack[i]) {
case Json5Scope.EMPTY_ARRAY:
case Json5Scope.NONEMPTY_ARRAY:
break;

case Json5Scope.EMPTY_OBJECT:
case Json5Scope.DANGLING_NAME:
case Json5Scope.NONEMPTY_OBJECT:
result.append('.');
if (pathNames[i] != null) {
result.append(pathNames[i]);
}
break;

case Json5Scope.NONEMPTY_DOCUMENT:
case Json5Scope.EMPTY_DOCUMENT:
case Json5Scope.CLOSED:
break;
}
}
return result.toString();
}
public String getPath() {
StringBuilder result = new StringBuilder().append('$');
for (int i = 0; i < stackSize; i++) {
switch (stack[i]) {
case Json5Scope.EMPTY_ARRAY:
case Json5Scope.NONEMPTY_ARRAY:
break;

case Json5Scope.EMPTY_OBJECT:
case Json5Scope.DANGLING_NAME:
case Json5Scope.NONEMPTY_OBJECT:
result.append('.');
if (pathNames[i] != null) {
result.append(pathNames[i]);
}
break;

case Json5Scope.NONEMPTY_DOCUMENT:
case Json5Scope.EMPTY_DOCUMENT:
case Json5Scope.CLOSED:
break;
}
}
return result.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import mcp.mobius.waila.api.IJsonConfig;
import mcp.mobius.waila.api.IRegistryFilter;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceLocation;
Expand All @@ -33,6 +34,17 @@ public View getView() {
return view;
}

public static IJsonConfig.Commenter commenter(ResourceLocation tag) {
return p -> !p.equals("$") ? null : """
Run `/waila reload` to apply changes server-wide.
Run `/wailac reload` to apply changes to only your client.
%s
The #%s tag rule can not be removed"""
.formatted(IRegistryFilter.getHeader(), tag);
}

public class View {

public final IRegistryFilter<Block> blockFilter;
Expand All @@ -59,20 +71,6 @@ public Adapter(ResourceLocation tagId) {
public JsonElement serialize(ExtraBlacklistConfig src, Type typeOfSrc, JsonSerializationContext context) {
var object = new JsonObject();

var comments = """
Run /waila reload to apply changes server-wide.
Run /wailac reload to apply changes to only your client.
%s
The %s tag rule can not be removed"""
.formatted(IRegistryFilter.getHeader(), tagRule)
.split("\n");

var commentArray = new JsonArray();
for (var line : comments) commentArray.add(line);
object.add("_comment", commentArray);

object.add("blocks", context.serialize(src.blocks));
object.add("blockEntityTypes", context.serialize(src.blockEntityTypes));
object.add("entityTypes", context.serialize(src.entityTypes));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ protected DataProvider(IData.Type<A> type, StreamCodec<RegistryFriendlyByteBuf,
blacklistConfig = IJsonConfig.of(ExtraBlacklistConfig.class)
.file(WailaConstants.NAMESPACE + "/extra/" + type.id().getPath() + "_blacklist")
.json5()
.commenter(ExtraBlacklistConfig.commenter(tagId))
.gson(new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(ExtraBlacklistConfig.class, new ExtraBlacklistConfig.Adapter(tagId))
Expand Down

0 comments on commit df305af

Please sign in to comment.