mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
Add list snippets (#1271)
- Expand JSON array snippet files into list entries - Read snippet values as JSON trees and skip malformed ones once - Route snippet references through one SnippetFolder lookup - Reject references that leave snippet/<type>/, including symlinks
This commit is contained in:
1 parent
fc5db87514
commit
6e078ad4a0
14 files changed
+857
-112
No files matched your search
+3
-7
@@ -20,18 +20,18 @@ package art.arcane.iris.modded;
|
||||
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.pack.loading.ResourceLoader;
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import art.arcane.iris.pack.schema.SchemaBuilder;
|
||||
import art.arcane.iris.pack.schema.annotation.Snippet;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.world.task.J;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.format.Form;
|
||||
import art.arcane.volmlib.util.io.IO;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
|
||||
public final class ModdedWorkspaceGenerator {
|
||||
private ModdedWorkspaceGenerator() {
|
||||
@@ -100,11 +100,7 @@ public final class ModdedWorkspaceGenerator {
|
||||
try {
|
||||
String snipType = snippetClass.getDeclaredAnnotation(Snippet.class).value();
|
||||
JSONObject entry = new JSONObject();
|
||||
KList<String> fileMatch = new KList<>();
|
||||
|
||||
for (int depth = 1; depth < 8; depth++) {
|
||||
fileMatch.add("/snippet/" + snipType + Form.repeat("/*", depth) + ".json");
|
||||
}
|
||||
List<String> fileMatch = new SnippetFolder(snipType).workspaceFileMatches();
|
||||
|
||||
entry.put("fileMatch", new JSONArray(fileMatch.toArray()));
|
||||
entry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json");
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
package art.arcane.iris.pack;
|
||||
|
||||
import art.arcane.iris.generation.terrain.IrisDimensionType;
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.iris.structure.object.IrisObjectScale;
|
||||
import art.arcane.iris.world.IrisWorldBoundary;
|
||||
@@ -35,6 +36,8 @@ import java.util.regex.Pattern;
|
||||
|
||||
final class PackDimensionValidator {
|
||||
private static final String BORROWED_DIMENSION_TYPE = "borrowedDimensionType";
|
||||
private static final String STYLE_SNIPPET_TYPE = "style";
|
||||
private static final String RANGE_SNIPPET_TYPE = "range";
|
||||
private static final Pattern RESOURCE_KEY = Pattern.compile("[a-z0-9_.-]+:[a-z0-9/._-]+");
|
||||
|
||||
private PackDimensionValidator() {
|
||||
@@ -248,7 +251,7 @@ final class PackDimensionValidator {
|
||||
Object rawStyle = blend.opt("style");
|
||||
boolean styleObject = rawStyle instanceof JSONObject;
|
||||
boolean styleSnippet = rawStyle instanceof String reference
|
||||
&& reference.startsWith("snippet/style/");
|
||||
&& new SnippetFolder(STYLE_SNIPPET_TYPE).holds(reference);
|
||||
if (!styleObject && !styleSnippet) {
|
||||
blockingErrors.add(context + ".blend.style must be an object or style snippet reference.");
|
||||
return;
|
||||
@@ -263,13 +266,12 @@ final class PackDimensionValidator {
|
||||
private static void validateDimensionStackStyleSnippet(File packFolder, String context, String reference,
|
||||
List<String> blockingErrors) {
|
||||
try {
|
||||
File snippetRoot = new File(packFolder, "snippet/style").getCanonicalFile();
|
||||
File snippetFile = new File(packFolder, reference + ".json").getCanonicalFile();
|
||||
if (!snippetFile.toPath().startsWith(snippetRoot.toPath()) || !snippetFile.isFile()) {
|
||||
SnippetFolder.Lookup snippet = new SnippetFolder(STYLE_SNIPPET_TYPE).find(packFolder, reference);
|
||||
if (!snippet.found()) {
|
||||
blockingErrors.add(context + " references missing style snippet '" + reference + "'.");
|
||||
return;
|
||||
}
|
||||
new JSONObject(Files.readString(snippetFile.toPath(), StandardCharsets.UTF_8));
|
||||
new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
|
||||
} catch (Throwable error) {
|
||||
blockingErrors.add(context + " references invalid style snippet '" + reference + "': "
|
||||
+ error.getMessage());
|
||||
@@ -609,17 +611,12 @@ final class PackDimensionValidator {
|
||||
if (reference == null || !reference.startsWith("snippet/")) {
|
||||
return null;
|
||||
}
|
||||
// Mirror IrisData's snippet adapter: canonical snippet/range/... is used verbatim; any other
|
||||
// snippet/... reference is re-rooted under this field's snippet folder.
|
||||
if (!reference.startsWith("snippet/range/")) {
|
||||
reference = "snippet/range/" + reference.substring("snippet/".length());
|
||||
}
|
||||
File snippet = new File(packFolder, reference + ".json");
|
||||
if (!snippet.isFile()) {
|
||||
SnippetFolder.Lookup snippet = new SnippetFolder(RANGE_SNIPPET_TYPE).find(packFolder, reference);
|
||||
if (!snippet.found()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new JSONObject(Files.readString(snippet.toPath(), StandardCharsets.UTF_8));
|
||||
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
|
||||
} catch (Throwable e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.pack;
|
||||
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
@@ -45,7 +46,7 @@ import java.util.TreeMap;
|
||||
* for a warning aimed at the copy-the-file-and-forget-the-seed mistake.
|
||||
*/
|
||||
final class PackGeneratorDuplicateValidator {
|
||||
private static final String GENERATOR_SNIPPET_FOLDER = "snippet/generator-layer/";
|
||||
private static final String GENERATOR_SNIPPET_TYPE = "generator-layer";
|
||||
|
||||
private PackGeneratorDuplicateValidator() {
|
||||
}
|
||||
@@ -125,15 +126,12 @@ final class PackGeneratorDuplicateValidator {
|
||||
if (reference == null || !reference.startsWith("snippet/")) {
|
||||
return null;
|
||||
}
|
||||
String resolved = reference.startsWith(GENERATOR_SNIPPET_FOLDER)
|
||||
? reference
|
||||
: GENERATOR_SNIPPET_FOLDER + reference.substring("snippet/".length());
|
||||
File snippet = new File(packFolder, resolved + ".json");
|
||||
if (!snippet.isFile()) {
|
||||
SnippetFolder.Lookup snippet = new SnippetFolder(GENERATOR_SNIPPET_TYPE).find(packFolder, reference);
|
||||
if (!snippet.found()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new JSONObject(Files.readString(snippet.toPath(), StandardCharsets.UTF_8));
|
||||
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
|
||||
} catch (Throwable e) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import art.arcane.iris.generation.terrain.IrisRegion;
|
||||
import art.arcane.iris.generation.terrain.ShoreBiomeLineages;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.pack.loading.IrisRegistrant;
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import art.arcane.iris.pack.schema.annotation.Snippet;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.spi.IrisPlatforms;
|
||||
@@ -172,13 +173,13 @@ final class PackHydrologyValidator {
|
||||
}
|
||||
|
||||
private static void warnUnknownSnippetKeys(String field, String reference, Class<?> type, KeyScan scan) {
|
||||
String base = SNIPPET_ROOT + type.getDeclaredAnnotation(Snippet.class).value() + "/";
|
||||
String snippet = reference.startsWith(base) ? reference : base + reference.substring(SNIPPET_ROOT.length());
|
||||
SnippetFolder.Lookup lookup = new SnippetFolder(type.getDeclaredAnnotation(Snippet.class).value())
|
||||
.find(scan.packFolder(), reference);
|
||||
String snippet = lookup.key();
|
||||
if (!scan.activeSnippets().add(snippet)) {
|
||||
return;
|
||||
}
|
||||
File file = new File(scan.packFolder(), snippet + ".json");
|
||||
JSONObject object = file.isFile() ? PackValidationIo.readJson(file) : null;
|
||||
JSONObject object = lookup.found() ? PackValidationIo.readJson(lookup.file()) : null;
|
||||
if (object != null) {
|
||||
warnUnknownFields(field + " (" + snippet + ")", object, type, scan);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package art.arcane.iris.pack;
|
||||
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import art.arcane.iris.structure.object.IrisObjectPlacementScaleInterpolator;
|
||||
import art.arcane.iris.structure.object.IrisStaticObject;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
@@ -165,16 +166,13 @@ final class PackStaticObjectValidator {
|
||||
return object;
|
||||
}
|
||||
if (value instanceof String reference && reference.startsWith("snippet/")) {
|
||||
String base = "snippet/" + snippetType + "/";
|
||||
String key = reference.startsWith(base) ? reference : base + reference.substring("snippet/".length());
|
||||
Path root = packFolder.toPath().toAbsolutePath().normalize();
|
||||
Path snippet = resolveContained(root, key + ".json");
|
||||
if (snippet == null || !snippet.startsWith(root.resolve(base)) || !Files.isRegularFile(snippet)) {
|
||||
SnippetFolder.Lookup snippet = new SnippetFolder(snippetType).find(packFolder, reference);
|
||||
if (!snippet.found()) {
|
||||
errors.add(path + " references missing " + snippetType + " snippet '" + reference + "'.");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return new JSONObject(Files.readString(snippet, StandardCharsets.UTF_8));
|
||||
return new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
errors.add(path + " could not read snippet '" + reference + "': " + e.getMessage());
|
||||
return null;
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.pack;
|
||||
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
@@ -36,7 +37,7 @@ import java.util.Locale;
|
||||
* 16-32 objects per chunk, and a caveProfile.densityThreshold of {} hollows the whole cave range.
|
||||
*/
|
||||
final class PackStyledRangeDefaultValidator {
|
||||
private static final String STYLE_RANGE_SNIPPET_FOLDER = "snippet/style-range/";
|
||||
private static final String STYLE_RANGE_SNIPPET_TYPE = "style-range";
|
||||
|
||||
record Validation(List<String> errors, List<String> warnings) {
|
||||
Validation {
|
||||
@@ -116,16 +117,13 @@ final class PackStyledRangeDefaultValidator {
|
||||
if (raw instanceof JSONObject inline) {
|
||||
range = inline;
|
||||
} else if (raw instanceof String reference && reference.startsWith("snippet/")) {
|
||||
String resolved = reference.startsWith(STYLE_RANGE_SNIPPET_FOLDER)
|
||||
? reference
|
||||
: STYLE_RANGE_SNIPPET_FOLDER + reference.substring("snippet/".length());
|
||||
File snippet = new File(packFolder, resolved + ".json");
|
||||
if (!snippet.isFile()) {
|
||||
SnippetFolder.Lookup snippet = new SnippetFolder(STYLE_RANGE_SNIPPET_TYPE).find(packFolder, reference);
|
||||
if (!snippet.found()) {
|
||||
return; // Missing snippets are reported by the content-key machinery.
|
||||
}
|
||||
try {
|
||||
range = new JSONObject(Files.readString(snippet.toPath(), StandardCharsets.UTF_8));
|
||||
via = " (via snippet '" + resolved + "')";
|
||||
range = new JSONObject(Files.readString(snippet.file().toPath(), StandardCharsets.UTF_8));
|
||||
via = " (via snippet '" + snippet.key() + "')";
|
||||
} catch (Throwable e) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package art.arcane.iris.pack;
|
||||
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import art.arcane.iris.generation.terrain.IrisTerrain3D;
|
||||
import art.arcane.iris.generation.noise.NoiseStyle;
|
||||
import com.google.gson.Gson;
|
||||
@@ -12,7 +13,6 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
@@ -169,15 +169,12 @@ final class PackTerrain3DValidator {
|
||||
return null;
|
||||
}
|
||||
String reference = raw.getAsString();
|
||||
String prefix = "snippet/" + snippetType + "/";
|
||||
String resolved = reference.startsWith(prefix) ? reference : prefix + reference.substring(8);
|
||||
Path root = packFolder.toPath().toAbsolutePath().normalize();
|
||||
Path path = root.resolve(resolved + ".json").normalize();
|
||||
if (!path.startsWith(root.resolve(prefix)) || !Files.isRegularFile(path)) {
|
||||
SnippetFolder.Lookup snippet = new SnippetFolder(snippetType).find(packFolder, reference);
|
||||
if (!snippet.found()) {
|
||||
errors.add(location + " references an unavailable " + snippetType + " snippet '" + reference + "'.");
|
||||
return null;
|
||||
}
|
||||
return readObject(path.toFile(), location + " (" + reference + ")", errors);
|
||||
return readObject(snippet.file(), location + " (" + reference + ")", errors);
|
||||
}
|
||||
|
||||
private static JsonObject readObject(File file, String location, List<String> errors) {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.pack.ingest;
|
||||
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
@@ -114,8 +115,7 @@ final class IngestPack {
|
||||
if (!reference.startsWith(SNIPPET_PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
String base = SNIPPET_PREFIX + snippetType + "/";
|
||||
String key = reference.startsWith(base) ? reference : base + reference.substring(SNIPPET_PREFIX.length());
|
||||
String key = new SnippetFolder(snippetType).keyOf(reference);
|
||||
return find(key + ".json").map(JsonObject::deepCopy).orElse(null);
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,11 @@ 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;
|
||||
import com.google.gson.reflect.TypeToken;
|
||||
@@ -92,6 +97,8 @@ 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;
|
||||
@@ -104,6 +111,7 @@ import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Set;
|
||||
@@ -968,12 +976,15 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
|
||||
@Override
|
||||
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {
|
||||
if (!typeToken.getRawType().isAnnotationPresent(Snippet.class)) {
|
||||
return null;
|
||||
String listedSnippetType = snippetTypeListedBy(typeToken);
|
||||
if (listedSnippetType != null) {
|
||||
return snippetListAdapter(gson, typeToken, listedSnippetType);
|
||||
}
|
||||
|
||||
String snippetType = typeToken.getRawType().getDeclaredAnnotation(Snippet.class).value();
|
||||
String snippedBase = "snippet/" + snippetType + "/";
|
||||
String snippetType = snippetTypeOf(typeToken.getRawType());
|
||||
if (snippetType == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new TypeAdapter<>() {
|
||||
@Override
|
||||
@@ -984,73 +995,184 @@ public class IrisData implements ExclusionStrategy, TypeAdapterFactory {
|
||||
@Override
|
||||
public T read(JsonReader reader) throws IOException {
|
||||
TypeAdapter<T> adapter = gson.getDelegateAdapter(IrisData.this, typeToken);
|
||||
String path = reader.getPath();
|
||||
|
||||
if (reader.peek().equals(JsonToken.STRING)) {
|
||||
String r = reader.nextString();
|
||||
if (!r.startsWith("snippet/"))
|
||||
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 (IrisEngineStreamType.UnknownStreamException unknownStream) {
|
||||
throw unknownStream;
|
||||
} 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 (reader.peek() == JsonToken.STRING) {
|
||||
return readSnippetReference(adapter, snippetType, reader.nextString(), path);
|
||||
}
|
||||
|
||||
JsonElement value = gson.getAdapter(JsonElement.class).read(reader);
|
||||
try {
|
||||
return adapter.read(reader);
|
||||
return adapter.fromJsonTree(value);
|
||||
} catch (IrisEngineStreamType.UnknownStreamException unknownStream) {
|
||||
throw unknownStream;
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error("Failed to read " + typeToken.getRawType().getCanonicalName() + "... faking objects a little to load the file at least.");
|
||||
IrisLogging.error("Failed to read " + typeToken.getRawType().getCanonicalName() + " at " + path
|
||||
+ " (" + e.getMessage() + "), using defaults");
|
||||
IrisLogging.reportError(e);
|
||||
try {
|
||||
return (T) typeToken.getRawType().getConstructor().newInstance();
|
||||
} catch (Throwable ignored) {
|
||||
|
||||
}
|
||||
return defaultInstance(typeToken);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
public KList<String> getPossibleSnippets(String f) {
|
||||
return possibleSnippets.computeIfAbsent(f, (k) -> {
|
||||
KList<String> l = new KList<>();
|
||||
private <T> @Nullable T readSnippetReference(TypeAdapter<T> adapter, String snippetType, String reference, String path) {
|
||||
JsonElement snippet = readSnippetFile(snippetType, reference, path);
|
||||
if (snippet == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
File snippetFolder = new File(getDataFolder(), "snippet/" + f);
|
||||
if (!snippetFolder.exists()) return l;
|
||||
if (snippet.isJsonArray()) {
|
||||
IrisLogging.error("Snippet " + reference + " in " + path + " holds several entries, which only a list can take");
|
||||
return null;
|
||||
}
|
||||
|
||||
String absPath = snippetFolder.getAbsolutePath();
|
||||
try (var stream = Files.walk(snippetFolder.toPath())) {
|
||||
stream.filter(Files::isRegularFile)
|
||||
.map(Path::toAbsolutePath)
|
||||
.map(Path::toString)
|
||||
.filter(s -> s.endsWith(".json"))
|
||||
.map(s -> s.substring(absPath.length() + 1))
|
||||
.map(s -> s.replace("\\", "/"))
|
||||
.map(s -> s.substring(0, s.length() - ".json".length()))
|
||||
.forEach(s -> l.add("snippet/" + s));
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError("Failed to scan Iris snippets in " + snippetFolder + ".", e);
|
||||
try {
|
||||
return adapter.fromJsonTree(snippet);
|
||||
} catch (IrisEngineStreamType.UnknownStreamException unknownStream) {
|
||||
throw unknownStream;
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error("Couldn't read snippet " + reference + " in " + path + " (" + e.getMessage() + ")");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> @Nullable T defaultInstance(TypeToken<T> typeToken) {
|
||||
try {
|
||||
return (T) typeToken.getRawType().getConstructor().newInstance();
|
||||
} catch (Throwable ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static @Nullable String snippetTypeOf(Class<?> type) {
|
||||
Snippet snippet = type.getDeclaredAnnotation(Snippet.class);
|
||||
return snippet == null ? null : snippet.value();
|
||||
}
|
||||
|
||||
private static @Nullable String snippetTypeListedBy(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 snippetTypeOf(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 snippetType) {
|
||||
TypeAdapter<T> listAdapter = gson.getDelegateAdapter(this, listType);
|
||||
|
||||
return new TypeAdapter<>() {
|
||||
@Override
|
||||
public void write(JsonWriter writer, T list) throws IOException {
|
||||
listAdapter.write(writer, list);
|
||||
}
|
||||
|
||||
return l;
|
||||
@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, snippetType, 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 snippetType, 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(snippetType, entry.getAsString(), 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(SnippetFolder.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 snippetType, String reference, String path) {
|
||||
if (!reference.startsWith(SnippetFolder.PREFIX)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
SnippetFolder.Lookup lookup = new SnippetFolder(snippetType).find(getDataFolder(), reference);
|
||||
if (!lookup.found()) {
|
||||
IrisLogging.error("Couldn't find snippet " + lookup.key() + " in " + path);
|
||||
return null;
|
||||
}
|
||||
|
||||
try (JsonReader snippetReader = new JsonReader(new FileReader(lookup.file()))) {
|
||||
snippetReader.setStrictness(Strictness.LENIENT);
|
||||
return JsonParser.parseReader(snippetReader);
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.error("Couldn't read snippet " + lookup.key() + " in " + path + " (" + e.getMessage() + ")");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Every snippet of the type, as "snippet/<path inside its folder>". */
|
||||
public KList<String> getPossibleSnippets(String snippetType) {
|
||||
return possibleSnippets.computeIfAbsent(snippetType, (k) -> {
|
||||
File snippetFolder = new File(getDataFolder(), new SnippetFolder(snippetType).path());
|
||||
return new KList<>(listSnippetReferences(snippetFolder));
|
||||
});
|
||||
}
|
||||
|
||||
private static List<String> listSnippetReferences(File snippetFolder) {
|
||||
if (!snippetFolder.exists()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
String absPath = snippetFolder.getAbsolutePath();
|
||||
try (var stream = Files.walk(snippetFolder.toPath())) {
|
||||
return stream.filter(Files::isRegularFile)
|
||||
.map(Path::toAbsolutePath)
|
||||
.map(Path::toString)
|
||||
.filter(s -> s.endsWith(".json"))
|
||||
.map(s -> s.substring(absPath.length() + 1))
|
||||
.map(s -> s.replace("\\", "/"))
|
||||
.map(s -> s.substring(0, s.length() - ".json".length()))
|
||||
.map(s -> SnippetFolder.PREFIX + s)
|
||||
.toList();
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError("Failed to scan Iris snippets in " + snippetFolder + ".", e);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isClosed() {
|
||||
return closed;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package art.arcane.iris.pack.loading;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.InvalidPathException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The pack folder "snippet/<type>" one snippet type keeps its files in. This is the one place a
|
||||
* "snippet/..." reference turns into a file.
|
||||
*/
|
||||
public record SnippetFolder(String snippetType) {
|
||||
public static final String PREFIX = "snippet/";
|
||||
private static final String FILE_SUFFIX = ".json";
|
||||
private static final int WORKSPACE_MATCH_DEPTH = 8;
|
||||
|
||||
public String path() {
|
||||
return PREFIX + snippetType;
|
||||
}
|
||||
|
||||
public boolean holds(String reference) {
|
||||
return reference.startsWith(path() + "/");
|
||||
}
|
||||
|
||||
/** The file key, without ".json", a reference means: "snippet/name" is short for "snippet/<type>/name". */
|
||||
public String keyOf(String reference) {
|
||||
return holds(reference) ? reference : path() + "/" + reference.substring(PREFIX.length());
|
||||
}
|
||||
|
||||
public Lookup find(File packFolder, String reference) {
|
||||
String key = keyOf(reference);
|
||||
return new Lookup(existingFileInsideFolder(packFolder, key), key);
|
||||
}
|
||||
|
||||
/** The IDE file patterns the snippet schema applies to. */
|
||||
public List<String> workspaceFileMatches() {
|
||||
List<String> matches = new ArrayList<>();
|
||||
for (int depth = 1; depth < WORKSPACE_MATCH_DEPTH; depth++) {
|
||||
matches.add("/" + path() + "/*".repeat(depth) + FILE_SUFFIX);
|
||||
}
|
||||
return matches;
|
||||
}
|
||||
|
||||
private @Nullable File existingFileInsideFolder(File packFolder, String key) {
|
||||
try {
|
||||
Path root = packFolder.toPath().toAbsolutePath().normalize();
|
||||
Path folder = root.resolve(path()).normalize();
|
||||
Path file = root.resolve(key + FILE_SUFFIX).normalize();
|
||||
if (!file.startsWith(folder) || !Files.isRegularFile(file)) {
|
||||
return null;
|
||||
}
|
||||
return file.toRealPath().startsWith(folder.toRealPath()) ? file.toFile() : null;
|
||||
} catch (InvalidPathException | IOException ignored) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The snippet file a reference names, absent when the pack has no such file. */
|
||||
public record Lookup(@Nullable File file, String key) {
|
||||
public boolean found() {
|
||||
return file != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,13 +23,12 @@ import art.arcane.iris.pack.schema.SchemaBuilder;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.pack.loading.ResourceLoader;
|
||||
import art.arcane.iris.pack.loading.SnippetFolder;
|
||||
import art.arcane.iris.pack.schema.annotation.Snippet;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.platform.bukkit.plugin.VolmitSender;
|
||||
import art.arcane.iris.world.task.J;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.collection.KMap;
|
||||
import art.arcane.volmlib.util.format.Form;
|
||||
import art.arcane.volmlib.util.io.IO;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
@@ -183,11 +182,7 @@ public class IrisCodeWorkspace {
|
||||
try {
|
||||
String snipType = snippetClass.getDeclaredAnnotation(Snippet.class).value();
|
||||
JSONObject schemaEntry = new JSONObject();
|
||||
KList<String> fileMatches = new KList<>();
|
||||
|
||||
for (int depth = 1; depth < 8; depth++) {
|
||||
fileMatches.add("/snippet/" + snipType + Form.repeat("/*", depth) + ".json");
|
||||
}
|
||||
List<String> fileMatches = new SnippetFolder(snipType).workspaceFileMatches();
|
||||
|
||||
schemaEntry.put("fileMatch", new JSONArray(fileMatches.toArray()));
|
||||
schemaEntry.put("url", "./.iris/schema/snippet/" + snipType + "-schema.json");
|
||||
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package art.arcane.iris.pack.loading;
|
||||
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.generation.runtime.PreservationRegistry;
|
||||
import art.arcane.iris.pack.value.IrisRange;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.testsupport.PlatformLeakGuard;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
public class IrisDataSnippetMalformedValueTest {
|
||||
private static final long RUNAWAY_READ_TIMEOUT_MILLISECONDS = 20_000;
|
||||
private static final double DEFAULT_RANGE_MIN = 16;
|
||||
private static final double DEFAULT_RANGE_MAX = 32;
|
||||
|
||||
@ClassRule
|
||||
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
|
||||
|
||||
@Rule
|
||||
public final TemporaryFolder temporary = new TemporaryFolder();
|
||||
|
||||
private IrisSettings previousSettings;
|
||||
private Path pack;
|
||||
private IrisData data;
|
||||
|
||||
public static class RangeListHolder {
|
||||
public List<IrisRange> ranges;
|
||||
public KList<IrisRange> keyedRanges;
|
||||
}
|
||||
|
||||
public static class RangeHolder {
|
||||
public IrisRange range;
|
||||
}
|
||||
|
||||
@Before
|
||||
public void createData() throws IOException {
|
||||
previousSettings = IrisSettings.settings;
|
||||
IrisSettings.settings = new IrisSettings();
|
||||
IrisServices.register(PreservationRegistry.class, mock(PreservationRegistry.class));
|
||||
pack = temporary.newFolder("pack").toPath();
|
||||
data = IrisData.get(new File(pack.toFile(), "."));
|
||||
}
|
||||
|
||||
@After
|
||||
public void closeData() {
|
||||
data.close();
|
||||
IrisServices.remove(PreservationRegistry.class);
|
||||
IrisSettings.settings = previousSettings;
|
||||
}
|
||||
|
||||
@Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS)
|
||||
public void numberInAListOfSnippetTypesIsReplacedByTheDefaultAndReadingMovesOn() {
|
||||
RangeListHolder holder = data.getGson().fromJson(
|
||||
"{\"ranges\":[5,{\"min\":1,\"max\":2}],\"keyedRanges\":[true]}", RangeListHolder.class);
|
||||
|
||||
assertEquals(2, holder.ranges.size());
|
||||
assertDefaultRange(holder.ranges.get(0));
|
||||
assertEquals(1, holder.ranges.get(1).getMin(), 0);
|
||||
assertEquals(1, holder.keyedRanges.size());
|
||||
assertDefaultRange(holder.keyedRanges.get(0));
|
||||
}
|
||||
|
||||
@Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS)
|
||||
public void nestedArrayInAListOfSnippetTypesIsReplacedByTheDefault() {
|
||||
RangeListHolder holder = data.getGson().fromJson("{\"ranges\":[[1,2],[[3]]]}", RangeListHolder.class);
|
||||
|
||||
assertEquals(2, holder.ranges.size());
|
||||
assertDefaultRange(holder.ranges.get(0));
|
||||
assertDefaultRange(holder.ranges.get(1));
|
||||
}
|
||||
|
||||
@Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS)
|
||||
public void malformedFieldKeepsTheDefaultAndTheValuesAfterIt() {
|
||||
RangeHolder holder = data.getGson().fromJson("{\"range\":7}", RangeHolder.class);
|
||||
|
||||
assertDefaultRange(holder.range);
|
||||
}
|
||||
|
||||
@Test(timeout = RUNAWAY_READ_TIMEOUT_MILLISECONDS)
|
||||
public void wrongTypedEntryOfAListSnippetIsReplacedByTheDefault() throws IOException {
|
||||
Path snippet = pack.resolve("snippet/range/broken.json");
|
||||
Files.createDirectories(snippet.getParent());
|
||||
Files.writeString(snippet, "[[1]]");
|
||||
|
||||
RangeListHolder holder = data.getGson().fromJson("{\"ranges\":[\"snippet/broken\"]}", RangeListHolder.class);
|
||||
|
||||
assertEquals(1, holder.ranges.size());
|
||||
assertDefaultRange(holder.ranges.get(0));
|
||||
}
|
||||
|
||||
private static void assertDefaultRange(IrisRange range) {
|
||||
assertNotNull(range);
|
||||
assertEquals(DEFAULT_RANGE_MIN, range.getMin(), 0);
|
||||
assertEquals(DEFAULT_RANGE_MAX, range.getMax(), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
package art.arcane.iris.pack.loading;
|
||||
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.noise.IrisExpression;
|
||||
import art.arcane.iris.generation.noise.IrisGenerator;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
import art.arcane.iris.generation.terrain.IrisRegion;
|
||||
import art.arcane.iris.pack.mod.IrisMod;
|
||||
import art.arcane.iris.pack.schema.annotation.Snippet;
|
||||
import art.arcane.iris.structure.jigsaw.IrisJigsawPiece;
|
||||
import art.arcane.iris.structure.jigsaw.IrisJigsawPool;
|
||||
import art.arcane.iris.structure.placement.IrisStructure;
|
||||
import art.arcane.iris.world.entity.IrisEntity;
|
||||
import art.arcane.iris.world.entity.IrisMarker;
|
||||
import art.arcane.iris.world.entity.IrisSpawner;
|
||||
import art.arcane.iris.world.loot.IrisLootTable;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
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.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.Assume.assumeTrue;
|
||||
|
||||
/**
|
||||
* Walks every snippet reference of a real pack, set through IRIS_TEST_PACK, and checks it resolves for the type of the
|
||||
* field it sits in. Reads the pack only; skipped when the variable is unset.
|
||||
*/
|
||||
public class IrisDataSnippetPackWalkTest {
|
||||
private static final String PACK_ENVIRONMENT_VARIABLE = "IRIS_TEST_PACK";
|
||||
private static final String ENGINE_PACKAGE_PREFIX = "art.arcane.iris";
|
||||
private static final List<Class<? extends IrisRegistrant>> PACK_ROOT_TYPES = List.of(
|
||||
IrisBiome.class, IrisRegion.class, IrisDimension.class, IrisGenerator.class, IrisEntity.class,
|
||||
IrisLootTable.class, IrisSpawner.class, IrisMarker.class, IrisExpression.class, IrisMod.class,
|
||||
IrisStructure.class, IrisJigsawPool.class, IrisJigsawPiece.class);
|
||||
|
||||
private File pack;
|
||||
private final Map<String, Class<?>> snippetTypesByFolder = new HashMap<>();
|
||||
private final List<String> unresolved = new ArrayList<>();
|
||||
private int resolved;
|
||||
private int outsideSnippetFields;
|
||||
private int snippetFilesWalked;
|
||||
private final List<String> untypedSnippetFiles = new ArrayList<>();
|
||||
|
||||
@Test
|
||||
public void everySnippetReferenceInThePackResolves() throws Exception {
|
||||
String packPath = System.getenv(PACK_ENVIRONMENT_VARIABLE);
|
||||
assumeTrue(PACK_ENVIRONMENT_VARIABLE + " is not set", packPath != null && !packPath.isBlank());
|
||||
pack = new File(packPath);
|
||||
assumeTrue(pack + " is not a folder", pack.isDirectory());
|
||||
|
||||
Set<Class<?>> visitedTypes = new HashSet<>();
|
||||
PACK_ROOT_TYPES.forEach(root -> collectSnippetTypes(root, visitedTypes));
|
||||
for (Class<? extends IrisRegistrant> root : PACK_ROOT_TYPES) {
|
||||
walkRootFolder(root);
|
||||
}
|
||||
walkSnippetFiles();
|
||||
|
||||
System.out.println("snippet pack walk: resolved=" + resolved + " unresolved=" + unresolved.size()
|
||||
+ " outsideSnippetFields=" + outsideSnippetFields + " snippetFilesWalked=" + snippetFilesWalked
|
||||
+ " untypedSnippetFiles=" + untypedSnippetFiles.size());
|
||||
untypedSnippetFiles.forEach(file -> System.out.println("untyped snippet file: " + file));
|
||||
assertTrue("unresolved snippet references:\n" + String.join("\n", unresolved), unresolved.isEmpty());
|
||||
assertTrue("the pack holds no snippet references", resolved > 0);
|
||||
}
|
||||
|
||||
private void walkRootFolder(Class<? extends IrisRegistrant> root) throws Exception {
|
||||
String folderName = root.getConstructor().newInstance().getFolderName();
|
||||
for (File file : jsonFilesUnder(new File(pack, folderName))) {
|
||||
walk(parse(file), root, relative(file));
|
||||
}
|
||||
}
|
||||
|
||||
private void walkSnippetFiles() throws IOException {
|
||||
for (File file : jsonFilesUnder(new File(pack, "snippet"))) {
|
||||
Class<?> type = typeOfSnippetFile(file);
|
||||
if (type == null) {
|
||||
untypedSnippetFiles.add(relative(file));
|
||||
continue;
|
||||
}
|
||||
snippetFilesWalked++;
|
||||
JsonElement content = parse(file);
|
||||
if (content != null && content.isJsonArray()) {
|
||||
content.getAsJsonArray().forEach(entry -> walk(entry, type, relative(file)));
|
||||
} else {
|
||||
walk(content, type, relative(file));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Class<?> typeOfSnippetFile(File file) {
|
||||
String[] segments = relative(file).split("/");
|
||||
return snippetTypesByFolder.get(segments[1]);
|
||||
}
|
||||
|
||||
private void walk(JsonElement value, Type type, String path) {
|
||||
if (value == null || value.isJsonNull()) {
|
||||
return;
|
||||
}
|
||||
Class<?> raw = rawClass(type);
|
||||
if (value.isJsonPrimitive()) {
|
||||
checkReference(value, raw, path);
|
||||
return;
|
||||
}
|
||||
if (value.isJsonArray()) {
|
||||
walkElements(value.getAsJsonArray(), elementTypeOf(type), path);
|
||||
return;
|
||||
}
|
||||
walkObject(value.getAsJsonObject(), type, raw, path);
|
||||
}
|
||||
|
||||
private void walkElements(JsonArray elements, Type elementType, String path) {
|
||||
for (int index = 0; index < elements.size(); index++) {
|
||||
walk(elements.get(index), elementType, path + "[" + index + "]");
|
||||
}
|
||||
}
|
||||
|
||||
private void walkObject(JsonObject object, Type type, Class<?> raw, String path) {
|
||||
if (raw == null) {
|
||||
return;
|
||||
}
|
||||
if (Map.class.isAssignableFrom(raw)) {
|
||||
Type valueType = typeArgument(type, 1);
|
||||
object.entrySet().forEach(entry -> walk(entry.getValue(), valueType, path + "." + entry.getKey()));
|
||||
return;
|
||||
}
|
||||
Map<String, Type> fields = fieldTypesOf(raw);
|
||||
object.entrySet().forEach(entry -> {
|
||||
Type fieldType = fields.get(entry.getKey());
|
||||
if (fieldType != null) {
|
||||
walk(entry.getValue(), fieldType, path + "." + entry.getKey());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void checkReference(JsonElement value, Class<?> raw, String path) {
|
||||
if (!value.getAsJsonPrimitive().isString() || !value.getAsString().startsWith(SnippetFolder.PREFIX)) {
|
||||
return;
|
||||
}
|
||||
String reference = value.getAsString();
|
||||
SnippetFolder folder = raw == null ? null : folderOf(raw);
|
||||
if (folder == null) {
|
||||
outsideSnippetFields++;
|
||||
return;
|
||||
}
|
||||
if (folder.find(pack, reference).found()) {
|
||||
resolved++;
|
||||
return;
|
||||
}
|
||||
unresolved.add(path + " -> " + reference + " (tried " + folder.keyOf(reference) + ")");
|
||||
}
|
||||
|
||||
private SnippetFolder folderOf(Class<?> type) {
|
||||
Snippet snippet = type.getDeclaredAnnotation(Snippet.class);
|
||||
return snippet == null ? null : new SnippetFolder(snippet.value());
|
||||
}
|
||||
|
||||
private void collectSnippetTypes(Type type, Set<Class<?>> visited) {
|
||||
if (type instanceof ParameterizedType parameterized) {
|
||||
for (Type argument : parameterized.getActualTypeArguments()) {
|
||||
collectSnippetTypes(argument, visited);
|
||||
}
|
||||
}
|
||||
Class<?> raw = rawClass(type);
|
||||
if (raw == null) {
|
||||
return;
|
||||
}
|
||||
if (raw.isArray()) {
|
||||
collectSnippetTypes(raw.getComponentType(), visited);
|
||||
return;
|
||||
}
|
||||
if (!raw.getName().startsWith(ENGINE_PACKAGE_PREFIX) || raw.isEnum() || raw.isInterface() || !visited.add(raw)) {
|
||||
return;
|
||||
}
|
||||
Snippet snippet = raw.getDeclaredAnnotation(Snippet.class);
|
||||
if (snippet != null) {
|
||||
snippetTypesByFolder.putIfAbsent(snippet.value(), raw);
|
||||
}
|
||||
fieldTypesOf(raw).values().forEach(fieldType -> collectSnippetTypes(fieldType, visited));
|
||||
}
|
||||
|
||||
private static Map<String, Type> fieldTypesOf(Class<?> type) {
|
||||
Map<String, Type> fields = new HashMap<>();
|
||||
for (Class<?> current = type; current != null && current != Object.class; current = current.getSuperclass()) {
|
||||
for (Field field : current.getDeclaredFields()) {
|
||||
if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) {
|
||||
fields.putIfAbsent(field.getName(), field.getGenericType());
|
||||
}
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
private static Class<?> rawClass(Type type) {
|
||||
if (type instanceof Class<?> raw) {
|
||||
return raw;
|
||||
}
|
||||
if (type instanceof ParameterizedType parameterized && parameterized.getRawType() instanceof Class<?> raw) {
|
||||
return raw;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static Type elementTypeOf(Type type) {
|
||||
if (type instanceof Class<?> raw && raw.isArray()) {
|
||||
return raw.getComponentType();
|
||||
}
|
||||
return typeArgument(type, 0);
|
||||
}
|
||||
|
||||
private static Type typeArgument(Type type, int index) {
|
||||
if (type instanceof ParameterizedType parameterized && index < parameterized.getActualTypeArguments().length) {
|
||||
return parameterized.getActualTypeArguments()[index];
|
||||
}
|
||||
return Object.class;
|
||||
}
|
||||
|
||||
private static JsonElement parse(File file) {
|
||||
try {
|
||||
return JsonParser.parseString(Files.readString(file.toPath()));
|
||||
} catch (Exception unreadable) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static List<File> jsonFilesUnder(File folder) {
|
||||
if (!folder.isDirectory()) {
|
||||
return List.of();
|
||||
}
|
||||
try (Stream<Path> files = Files.walk(folder.toPath())) {
|
||||
return files.filter(Files::isRegularFile)
|
||||
.filter(file -> file.getFileName().toString().endsWith(".json"))
|
||||
.map(Path::toFile)
|
||||
.sorted()
|
||||
.toList();
|
||||
} catch (IOException unreadable) {
|
||||
throw new IllegalStateException(unreadable);
|
||||
}
|
||||
}
|
||||
|
||||
private String relative(File file) {
|
||||
return pack.toPath().relativize(file.toPath()).toString().replace('\\', '/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
package art.arcane.iris.pack.loading;
|
||||
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.generation.runtime.PreservationRegistry;
|
||||
import art.arcane.iris.pack.value.IrisRate;
|
||||
import art.arcane.iris.spi.IrisServices;
|
||||
import art.arcane.iris.testsupport.PlatformLeakGuard;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.ClassRule;
|
||||
import org.junit.Rule;
|
||||
import org.junit.Test;
|
||||
import org.junit.rules.TemporaryFolder;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
|
||||
public class IrisDataSnippetTest {
|
||||
@ClassRule
|
||||
public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean();
|
||||
|
||||
@Rule
|
||||
public final TemporaryFolder temporary = new TemporaryFolder();
|
||||
|
||||
private IrisSettings previousSettings;
|
||||
private Path pack;
|
||||
private IrisData data;
|
||||
|
||||
public static class RateHolder {
|
||||
public IrisRate rate;
|
||||
}
|
||||
|
||||
public static class RateListHolder {
|
||||
public List<IrisRate> rates;
|
||||
public KList<IrisRate> keyedRates;
|
||||
}
|
||||
|
||||
@Before
|
||||
public void createPack() throws IOException {
|
||||
previousSettings = IrisSettings.settings;
|
||||
IrisSettings.settings = new IrisSettings();
|
||||
IrisServices.register(PreservationRegistry.class, mock(PreservationRegistry.class));
|
||||
pack = temporary.newFolder("pack").toPath();
|
||||
}
|
||||
|
||||
@After
|
||||
public void closeData() {
|
||||
if (data != null) {
|
||||
data.close();
|
||||
}
|
||||
IrisServices.remove(PreservationRegistry.class);
|
||||
IrisSettings.settings = previousSettings;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void nestedPathResolves() throws IOException {
|
||||
write("snippet/rate/groups/fast.json", "{\"amount\":8}");
|
||||
|
||||
assertEquals(8, rateOf("\"snippet/groups/fast\"").getAmount());
|
||||
assertEquals(8, rateOf("\"snippet/rate/groups/fast\"").getAmount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void shortAndFullReferencesResolve() throws IOException {
|
||||
write("snippet/rate/slow.json", "{\"amount\":3}");
|
||||
|
||||
assertEquals(3, rateOf("\"snippet/slow\"").getAmount());
|
||||
assertEquals(3, rateOf("\"snippet/rate/slow\"").getAmount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void snippetsOfAnotherTypeAreNotUsed() throws IOException {
|
||||
write("snippet/duration/fast.json", "{\"amount\":7}");
|
||||
|
||||
assertNull(rateOf("\"snippet/fast\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void referenceCannotLeaveItsSnippetFolder() throws IOException {
|
||||
write("snippet/duration/fast.json", "{\"amount\":7}");
|
||||
write("snippet/rate/other.json", "{\"amount\":1}");
|
||||
|
||||
assertNull(rateOf("\"snippet/rate/../duration/fast\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void symlinkLeadingOutOfItsSnippetFolderIsNotFound() throws IOException {
|
||||
write("snippet/duration/fast.json", "{\"amount\":7}");
|
||||
link("snippet/rate/fast.json", "snippet/duration/fast.json");
|
||||
|
||||
assertNull(rateOf("\"snippet/fast\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void symlinkStayingInsideItsSnippetFolderResolves() throws IOException {
|
||||
write("snippet/rate/real.json", "{\"amount\":4}");
|
||||
link("snippet/rate/alias.json", "snippet/rate/real.json");
|
||||
|
||||
assertEquals(4, rateOf("\"snippet/alias\"").getAmount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void missingSnippetYieldsNull() throws IOException {
|
||||
write("snippet/rate/other.json", "{\"amount\":1}");
|
||||
|
||||
assertNull(rateOf("\"snippet/absent\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void arraySnippetInAListStandsForAllItsEntries() throws IOException {
|
||||
write("snippet/rate/many.json", "[{\"amount\":1},{\"amount\":2},]");
|
||||
write("snippet/rate/one.json", "{\"amount\":5}");
|
||||
|
||||
RateListHolder holder = data().getGson().fromJson(
|
||||
"{\"rates\":[\"snippet/many\",\"snippet/one\",{\"amount\":9}],"
|
||||
+ "\"keyedRates\":[\"snippet/many\",{\"amount\":9}]}",
|
||||
RateListHolder.class);
|
||||
|
||||
assertEquals(List.of(1, 2, 5, 9), amountsOf(holder.rates));
|
||||
assertEquals(List.of(1, 2, 9), amountsOf(holder.keyedRates));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void unreadableSnippetKeepsItsSlotInAList() throws IOException {
|
||||
write("snippet/rate/one.json", "{\"amount\":5}");
|
||||
|
||||
RateListHolder holder = data().getGson().fromJson(
|
||||
"{\"rates\":[\"snippet/missing\",\"snippet/one\"]}", RateListHolder.class);
|
||||
|
||||
assertEquals(2, holder.rates.size());
|
||||
assertNull(holder.rates.get(0));
|
||||
assertEquals(5, holder.rates.get(1).getAmount());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void singleReferenceToAnArraySnippetYieldsNull() throws IOException {
|
||||
write("snippet/rate/many.json", "[{\"amount\":1},{\"amount\":2}]");
|
||||
|
||||
assertNull(rateOf("\"snippet/many\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void listsWithoutReferencesStillLoad() {
|
||||
RateListHolder holder = data().getGson().fromJson(
|
||||
"{\"rates\":[{\"amount\":4},{\"amount\":6}]}", RateListHolder.class);
|
||||
|
||||
assertEquals(List.of(4, 6), amountsOf(holder.rates));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void possibleSnippetsListTheTypeFolderAsShortReferences() throws IOException {
|
||||
write("snippet/rate/a.json", "{}");
|
||||
write("snippet/rate/nested/c.json", "{}");
|
||||
write("snippet/duration/other.json", "{}");
|
||||
|
||||
assertEquals(List.of("snippet/a", "snippet/nested/c"),
|
||||
data().getPossibleSnippets("rate").stream().sorted().toList());
|
||||
}
|
||||
|
||||
private IrisRate rateOf(String jsonValue) {
|
||||
return data().getGson().fromJson("{\"rate\":" + jsonValue + "}", RateHolder.class).rate;
|
||||
}
|
||||
|
||||
private IrisData data() {
|
||||
if (data == null) {
|
||||
data = IrisData.get(new File(pack.toFile(), "."));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private void write(String relative, String content) throws IOException {
|
||||
Path file = pack.resolve(relative);
|
||||
Files.createDirectories(file.getParent());
|
||||
Files.writeString(file, content);
|
||||
}
|
||||
|
||||
private void link(String relative, String target) throws IOException {
|
||||
Path link = pack.resolve(relative);
|
||||
Files.createDirectories(link.getParent());
|
||||
Files.createSymbolicLink(link, pack.resolve(target));
|
||||
}
|
||||
|
||||
private static List<Integer> amountsOf(List<IrisRate> rates) {
|
||||
assertNotNull(rates);
|
||||
List<Integer> amounts = new ArrayList<>();
|
||||
for (IrisRate rate : rates) {
|
||||
assertNotNull(rate);
|
||||
amounts.add(rate.getAmount());
|
||||
}
|
||||
return amounts;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user