mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
Let snippets hold several entries
A list that references a snippet file holding a JSON array now takes all of its entries in place, in both the pack Gson and the module settings decoder. A single-value reference to such a file logs an error and loads null in the pack Gson, and is a settings error in the module decoder. Snippet-file schemas accept one entry or a list, and the decorator-snippet validator checks each entry of an array file. No pins or goldens moved. v3: 8ba8c7b2d
This commit is contained in:
1 parent
3eb8566ef9
commit
ffbd0db03a
10 files changed
+393
-25
No files matched your search
@@ -22,7 +22,10 @@ import com.google.gson.ExclusionStrategy;
|
||||
import com.google.gson.FieldAttributes;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonNull;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.google.gson.Strictness;
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.TypeAdapterFactory;
|
||||
@@ -72,9 +75,12 @@ import org.jetbrains.annotations.Nullable;
|
||||
import java.io.File;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
@@ -90,6 +96,7 @@ import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Data
|
||||
public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
private static final String SNIPPET_PREFIX = "snippet/";
|
||||
private static final Map<File, IrisData> dataLoaders = new ConcurrentHashMap<>();
|
||||
// Loaders (cached or detached) that currently have registered engines; see hasActiveEngines.
|
||||
// Identity-keyed on purpose: Lombok's @Data hashCode over this class's mutable loader state
|
||||
@@ -690,12 +697,17 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
|
||||
@Override
|
||||
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
|
||||
String listedSnippetFolder = snippetFolderListedBy(typeToken);
|
||||
if (listedSnippetFolder != null) {
|
||||
return snippetListAdapter(gson, typeToken, SNIPPET_PREFIX + listedSnippetFolder + "/");
|
||||
}
|
||||
|
||||
String snippetType = snippetFolder(typeToken.getRawType());
|
||||
if (snippetType == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String snippedBase = "snippet/" + snippetType + "/";
|
||||
String snippetBase = SNIPPET_PREFIX + snippetType + "/";
|
||||
|
||||
return new TypeAdapter<>() {
|
||||
@Override
|
||||
@@ -708,24 +720,24 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
TypeAdapter<T> adapter = gson.getDelegateAdapter(IrisData.this, typeToken);
|
||||
|
||||
if (reader.peek().equals(JsonToken.STRING)) {
|
||||
String r = reader.nextString();
|
||||
if (!r.startsWith("snippet/"))
|
||||
String path = reader.getPath();
|
||||
String reference = reader.nextString();
|
||||
JsonElement snippet = readSnippetFile(reference, snippetBase, path);
|
||||
if (snippet == null) {
|
||||
return null;
|
||||
if (!r.startsWith(snippedBase))
|
||||
r = snippedBase + r.substring(8);
|
||||
|
||||
File f = new File(getDataFolder(), r + ".json");
|
||||
if (f.exists()) {
|
||||
try (JsonReader snippetReader = new JsonReader(new FileReader(f))){
|
||||
return adapter.read(snippetReader);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error("Couldn't read snippet " + r + " in " + reader.getPath() + " (" + e.getMessage() + ")");
|
||||
}
|
||||
} else {
|
||||
IrisLogging.error("Couldn't find snippet " + r + " in " + reader.getPath());
|
||||
}
|
||||
|
||||
return null;
|
||||
if (snippet.isJsonArray()) {
|
||||
IrisLogging.error("Snippet " + reference + " in " + path + " holds several entries, which only a list can take");
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return adapter.fromJsonTree(snippet);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error("Couldn't read snippet " + reference + " in " + path + " (" + e.getMessage() + ")");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
String path = reader.getPath();
|
||||
@@ -757,6 +769,99 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
return null;
|
||||
}
|
||||
|
||||
private static @Nullable String snippetFolderListedBy(TypeToken<?> typeToken) {
|
||||
if (!Collection.class.isAssignableFrom(typeToken.getRawType())
|
||||
|| !(typeToken.getType() instanceof ParameterizedType listType)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Type[] elementTypes = listType.getActualTypeArguments();
|
||||
if (elementTypes.length != 1 || !(elementTypes[0] instanceof Class<?> elementType)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return snippetFolder(elementType);
|
||||
}
|
||||
|
||||
/** A snippet file holding a JSON array stands for all of its entries, so inside a list it becomes that many items. */
|
||||
private <T> TypeAdapter<T> snippetListAdapter(Gson gson, TypeToken<T> listType, String snippetBase) {
|
||||
TypeAdapter<T> listAdapter = gson.getDelegateAdapter(this, listType);
|
||||
|
||||
return new TypeAdapter<>() {
|
||||
@Override
|
||||
public void write(JsonWriter writer, T list) throws IOException {
|
||||
listAdapter.write(writer, list);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T read(JsonReader reader) throws IOException {
|
||||
if (reader.peek() != JsonToken.BEGIN_ARRAY) {
|
||||
return listAdapter.read(reader);
|
||||
}
|
||||
|
||||
String path = reader.getPath();
|
||||
JsonArray entries = gson.getAdapter(JsonArray.class).read(reader);
|
||||
return listAdapter.fromJsonTree(withSnippetsInlined(entries, snippetBase, path));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** A snippet that can't be read keeps its slot as null, the way a single snippet reference loads. */
|
||||
private JsonArray withSnippetsInlined(JsonArray entries, String snippetBase, String path) {
|
||||
JsonArray inlined = new JsonArray();
|
||||
for (int index = 0; index < entries.size(); index++) {
|
||||
JsonElement entry = entries.get(index);
|
||||
if (!isSnippetReference(entry)) {
|
||||
inlined.add(entry);
|
||||
continue;
|
||||
}
|
||||
|
||||
JsonElement snippet = readSnippetFile(entry.getAsString(), snippetBase, path + "[" + index + "]");
|
||||
if (snippet == null) {
|
||||
inlined.add(JsonNull.INSTANCE);
|
||||
} else if (snippet.isJsonArray()) {
|
||||
entriesOfSnippet(snippet.getAsJsonArray()).forEach(inlined::add);
|
||||
} else {
|
||||
inlined.add(snippet);
|
||||
}
|
||||
}
|
||||
|
||||
return inlined;
|
||||
}
|
||||
|
||||
/** The entries a snippet file holding a list stands for. Lenient parsing reads a trailing comma as a null entry. */
|
||||
public static List<JsonElement> entriesOfSnippet(JsonArray snippet) {
|
||||
return snippet.asList().stream().filter(entry -> !entry.isJsonNull()).toList();
|
||||
}
|
||||
|
||||
private static boolean isSnippetReference(JsonElement entry) {
|
||||
return entry.isJsonPrimitive()
|
||||
&& entry.getAsJsonPrimitive().isString()
|
||||
&& entry.getAsString().startsWith(SNIPPET_PREFIX);
|
||||
}
|
||||
|
||||
/** The parsed snippet file, or null when the reference isn't a snippet or the file can't be read. */
|
||||
private @Nullable JsonElement readSnippetFile(String reference, String snippetBase, String path) {
|
||||
if (!reference.startsWith(SNIPPET_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String key = reference.startsWith(snippetBase) ? reference : snippetBase + reference.substring(SNIPPET_PREFIX.length());
|
||||
File file = new File(getDataFolder(), key + ".json");
|
||||
if (!file.exists()) {
|
||||
IrisLogging.error("Couldn't find snippet " + key + " in " + path);
|
||||
return null;
|
||||
}
|
||||
|
||||
try (JsonReader snippetReader = new JsonReader(new FileReader(file))) {
|
||||
snippetReader.setStrictness(Strictness.LENIENT);
|
||||
return JsonParser.parseReader(snippetReader);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error("Couldn't read snippet " + key + " in " + path + " (" + e.getMessage() + ")");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public KList<String> getPossibleSnippets(String f) {
|
||||
return possibleSnippets.computeIfAbsent(f, (k) -> {
|
||||
KList<String> l = new KList<>();
|
||||
|
||||
@@ -23,6 +23,7 @@ import art.arcane.volmlib.util.json.JSONObject;
|
||||
import art.arcane.volmlib.util.json.JSONTokener;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParseException;
|
||||
@@ -43,8 +44,12 @@ import com.volmit.host.FeatureDescriptor;
|
||||
import com.volmit.host.OptionsMetadata;
|
||||
import com.volmit.resource.ResourceId;
|
||||
|
||||
import art.arcane.iris.core.loader.IrisData;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.UncheckedIOException;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collection;
|
||||
@@ -336,10 +341,17 @@ public final class ModuleSettingsDecoder {
|
||||
}
|
||||
}
|
||||
|
||||
/** Lets a {@link Snippet} type be written as a reference to a snippet file. */
|
||||
/**
|
||||
* Lets a {@link Snippet} type be written as a reference to a snippet file. A list of such a type takes a snippet file
|
||||
* holding a JSON array as all of its entries, in place; a single value takes only a file holding one entry.
|
||||
*/
|
||||
private final class SnippetReferences implements TypeAdapterFactory {
|
||||
@Override
|
||||
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
|
||||
Snippet listedSnippet = snippetListedBy(type);
|
||||
if (listedSnippet != null) {
|
||||
return listAdapter(gson, type, listedSnippet);
|
||||
}
|
||||
Snippet snippet = type.getRawType().getAnnotation(Snippet.class);
|
||||
if (snippet == null) {
|
||||
return null;
|
||||
@@ -356,10 +368,62 @@ public final class ModuleSettingsDecoder {
|
||||
if (in.peek() != JsonToken.STRING) {
|
||||
return delegate.read(in);
|
||||
}
|
||||
return delegate.fromJson(readSnippet(snippet.value(), in.nextString()));
|
||||
String reference = in.nextString();
|
||||
JsonElement entry = readSnippet(snippet.value(), reference);
|
||||
if (entry.isJsonArray()) {
|
||||
throw new JsonParseException("Snippet " + reference + " holds several entries, which only a list can take");
|
||||
}
|
||||
return delegate.fromJsonTree(entry);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private <T> TypeAdapter<T> listAdapter(Gson gson, TypeToken<T> listType, Snippet snippet) {
|
||||
TypeAdapter<T> delegate = gson.getDelegateAdapter(this, listType);
|
||||
return new TypeAdapter<T>() {
|
||||
@Override
|
||||
public void write(JsonWriter out, T value) throws IOException {
|
||||
delegate.write(out, value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T read(JsonReader in) throws IOException {
|
||||
if (in.peek() != JsonToken.BEGIN_ARRAY) {
|
||||
return delegate.read(in);
|
||||
}
|
||||
JsonArray entries = gson.getAdapter(JsonArray.class).read(in);
|
||||
return delegate.fromJsonTree(withSnippetsInlined(entries, snippet.value()));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
private static Snippet snippetListedBy(TypeToken<?> type) {
|
||||
if (!Collection.class.isAssignableFrom(type.getRawType()) || !(type.getType() instanceof ParameterizedType listType)) {
|
||||
return null;
|
||||
}
|
||||
Type[] elementTypes = listType.getActualTypeArguments();
|
||||
if (elementTypes.length != 1 || !(elementTypes[0] instanceof Class<?> elementType)) {
|
||||
return null;
|
||||
}
|
||||
return elementType.getAnnotation(Snippet.class);
|
||||
}
|
||||
|
||||
private JsonArray withSnippetsInlined(JsonArray entries, String snippetFolder) {
|
||||
JsonArray inlined = new JsonArray();
|
||||
for (JsonElement entry : entries) {
|
||||
if (!entry.isJsonPrimitive() || !entry.getAsJsonPrimitive().isString()) {
|
||||
inlined.add(entry);
|
||||
continue;
|
||||
}
|
||||
JsonElement snippet = readSnippet(snippetFolder, entry.getAsString());
|
||||
if (snippet.isJsonArray()) {
|
||||
IrisData.entriesOfSnippet(snippet.getAsJsonArray()).forEach(inlined::add);
|
||||
} else {
|
||||
inlined.add(snippet);
|
||||
}
|
||||
}
|
||||
return inlined;
|
||||
}
|
||||
|
||||
/** The file name below the snippet folder: {@code snippet/<name>} and {@code snippet/<snippet folder>/<name>} name the same file. */
|
||||
@@ -369,7 +433,7 @@ public final class ModuleSettingsDecoder {
|
||||
return name.startsWith(folderPrefix) ? name.substring(folderPrefix.length()) : name;
|
||||
}
|
||||
|
||||
private String readSnippet(String snippetFolder, String reference) {
|
||||
private JsonElement readSnippet(String snippetFolder, String reference) {
|
||||
if (!reference.startsWith(SNIPPET_PREFIX)) {
|
||||
throw new JsonParseException("\"" + reference + "\" is neither an object nor a snippet reference; write the object,"
|
||||
+ " or snippet/<name> for the file " + SNIPPET_FOLDER + "/" + snippetFolder + "/<name>" + JSON_EXTENSION);
|
||||
@@ -381,7 +445,7 @@ public final class ModuleSettingsDecoder {
|
||||
+ "; a snippet reference names a file below " + SNIPPET_FOLDER + "/" + snippetFolder + "/");
|
||||
}
|
||||
try {
|
||||
return Files.readString(file);
|
||||
return JsonParser.parseString(Files.readString(file));
|
||||
} catch (IOException failure) {
|
||||
throw new UncheckedIOException("Cannot read snippet " + packFolder.relativize(file), failure);
|
||||
}
|
||||
|
||||
@@ -78,15 +78,35 @@ final class PackBiomeLayerValidator {
|
||||
snippetFiles.sort(Comparator.comparing(File::getPath));
|
||||
for (File snippetFile : snippetFiles) {
|
||||
String snippetKey = PackValidationIo.deriveKey(decoratorSnippetsFolder, snippetFile);
|
||||
String snippetPath = "Decorator snippet '" + snippetKey + "'";
|
||||
JSONObject snippet = PackValidationIo.readJson(snippetFile);
|
||||
if (snippet != null) {
|
||||
validateDecoratorPalette(snippet, "Decorator snippet '" + snippetKey + "'", blockingErrors);
|
||||
validateDecoratorPalette(snippet, snippetPath, blockingErrors);
|
||||
continue;
|
||||
}
|
||||
JSONArray snippetEntries = PackValidationIo.readJsonArray(snippetFile);
|
||||
if (snippetEntries != null) {
|
||||
validateDecoratorSnippetEntries(snippetEntries, snippetPath, blockingErrors);
|
||||
}
|
||||
}
|
||||
}
|
||||
return blockingErrors;
|
||||
}
|
||||
|
||||
private static void validateDecoratorSnippetEntries(JSONArray entries, String path, List<String> blockingErrors) {
|
||||
for (int index = 0; index < entries.length(); index++) {
|
||||
Object entry = entries.opt(index);
|
||||
if (JSONObject.NULL.equals(entry)) {
|
||||
continue;
|
||||
}
|
||||
if (!(entry instanceof JSONObject decorator)) {
|
||||
blockingErrors.add(path + "[" + index + "] must be an object.");
|
||||
continue;
|
||||
}
|
||||
validateDecoratorPalette(decorator, path + "[" + index + "]", blockingErrors);
|
||||
}
|
||||
}
|
||||
|
||||
private static void validateDecoratorArray(JSONArray decorators, String path, List<String> blockingErrors) {
|
||||
for (int index = 0; index < decorators.length(); index++) {
|
||||
Object rawDecorator = decorators.opt(index);
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.core.pack;
|
||||
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
@@ -47,6 +48,15 @@ public final class PackValidationIo {
|
||||
}
|
||||
}
|
||||
|
||||
/** The JSON array {@code file} holds, or null when it holds something else or cannot be read or parsed. */
|
||||
static JSONArray readJsonArray(File file) {
|
||||
try {
|
||||
return new JSONArray(Files.readString(file.toPath(), StandardCharsets.UTF_8));
|
||||
} catch (IOException | RuntimeException parseFailure) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static boolean isScannableJsonPath(Path path) {
|
||||
String name = path.getFileName().toString();
|
||||
if (!name.endsWith(".json")) {
|
||||
|
||||
@@ -194,12 +194,12 @@ public class IrisCodeWorkspace {
|
||||
schemaEntries.add(snippetSchemaEntry(snipType));
|
||||
File schemaFile = new File(dm.getDataFolder(), SNIPPET_SCHEMA_FOLDER + snipType + SCHEMA_SUFFIX);
|
||||
if (immediateSchemas) {
|
||||
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, dm).construct().toString(4));
|
||||
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, dm).constructSnippet().toString(4));
|
||||
} else {
|
||||
IrisData snippetData = dm;
|
||||
J.attemptAsync(() -> {
|
||||
try {
|
||||
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, snippetData).construct().toString(4));
|
||||
IO.writeAll(schemaFile, new SchemaBuilder(snippetClass, snippetData).constructSnippet().toString(4));
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
}
|
||||
|
||||
@@ -115,9 +115,30 @@ public class SchemaBuilder {
|
||||
this.root = root;
|
||||
}
|
||||
|
||||
/** The schema of a module snippet file, which holds one object of {@code type}. */
|
||||
/** The schema of a module snippet file, which holds one object of {@code type} or a list of them. */
|
||||
public static JSONObject moduleSnippet(ObjectType type, IrisData data) {
|
||||
return new SchemaBuilder(type.getClass(), data).moduleSchemas().fileSchema(type);
|
||||
return singleOrList(new SchemaBuilder(type.getClass(), data).moduleSchemas().fileSchema(type));
|
||||
}
|
||||
|
||||
/** The schema of an Iris snippet file, which holds one object of the root class or a list of them. */
|
||||
public JSONObject constructSnippet() {
|
||||
return singleOrList(construct());
|
||||
}
|
||||
|
||||
/** A list referencing the snippet takes the entries of a snippet file holding a list, in place. */
|
||||
private static JSONObject singleOrList(JSONObject entry) {
|
||||
JSONObject schema = new JSONObject();
|
||||
for (String key : List.of("$schema", "$id", "definitions")) {
|
||||
if (entry.has(key)) {
|
||||
schema.put(key, entry.remove(key));
|
||||
}
|
||||
}
|
||||
|
||||
JSONObject entryList = new JSONObject();
|
||||
entryList.put("type", "array");
|
||||
entryList.put("items", entry);
|
||||
schema.put("anyOf", new JSONArray().put(entry).put(entryList));
|
||||
return schema;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user