Discover snippet folders once per validation run

- Add PackSnippets to discover each snippet type's folders once per run and use it in the pack validators and IngestPack
- Escape regex syntax characters in snippet folder names for the schema pattern
- Reject snippet files that a symlink leads out of their snippet folder
- Test folder discovery reuse, pattern escaping and symlinked snippets
This commit is contained in:
piexel committed 2026-11-22 20:38:05 +01:00
1 parent 08df9a4ca4
commit 3ada6c2639
14 files changed
+240 -81

No files matched your search

@@ -19,6 +19,7 @@
package art.arcane.iris.pack; package art.arcane.iris.pack;
import art.arcane.iris.generation.terrain.IrisDimensionType; import art.arcane.iris.generation.terrain.IrisDimensionType;
import art.arcane.iris.pack.loading.PackSnippets;
import art.arcane.iris.pack.loading.SnippetFolders; import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.iris.spi.IrisPlatforms; import art.arcane.iris.spi.IrisPlatforms;
import art.arcane.iris.structure.object.IrisObjectScale; import art.arcane.iris.structure.object.IrisObjectScale;
@@ -47,6 +48,7 @@ final class PackDimensionValidator {
File regionsFolder = new File(packFolder, "regions"); File regionsFolder = new File(packFolder, "regions");
File biomesFolder = new File(packFolder, "biomes"); File biomesFolder = new File(packFolder, "biomes");
File dimensionsFolder = new File(packFolder, PackValidator.DIMENSIONS_FOLDER); File dimensionsFolder = new File(packFolder, PackValidator.DIMENSIONS_FOLDER);
PackSnippets snippets = new PackSnippets(packFolder);
Set<String> dimensionKeys = new LinkedHashSet<>(); Set<String> dimensionKeys = new LinkedHashSet<>();
for (File dimensionFile : dimensionFiles) { for (File dimensionFile : dimensionFiles) {
dimensionKeys.add(PackValidationIo.deriveKey(dimensionsFolder, dimensionFile)); dimensionKeys.add(PackValidationIo.deriveKey(dimensionsFolder, dimensionFile));
@@ -63,15 +65,15 @@ final class PackDimensionValidator {
} }
validateImportedStructurePolicy(dimensionKey, dimJson, blockingErrors, warnings); validateImportedStructurePolicy(dimensionKey, dimJson, blockingErrors, warnings);
validateDimensionHeights(packFolder, dimensionKey, dimJson, blockingErrors); validateDimensionHeights(snippets, dimensionKey, dimJson, blockingErrors);
validateBorrowedDimensionType(dimensionKey, dimJson, borrowedDimensionTypesSupported(), blockingErrors); validateBorrowedDimensionType(dimensionKey, dimJson, borrowedDimensionTypesSupported(), blockingErrors);
validateSamplingStep(dimensionKey, dimJson, "terrainSamplingStep", 1, blockingErrors); validateSamplingStep(dimensionKey, dimJson, "terrainSamplingStep", 1, blockingErrors);
validateSamplingStep(dimensionKey, dimJson, "caveDensitySamplingStep", 1, blockingErrors); validateSamplingStep(dimensionKey, dimJson, "caveDensitySamplingStep", 1, blockingErrors);
validateSamplingStep(dimensionKey, dimJson, "biomeBoundsSamplingStep", 4, blockingErrors); validateSamplingStep(dimensionKey, dimJson, "biomeBoundsSamplingStep", 4, blockingErrors);
validateWorldBoundary(dimensionKey, dimJson, blockingErrors); validateWorldBoundary(dimensionKey, dimJson, blockingErrors);
validateStaticObjects(packFolder, dimensionKey, dimJson, blockingErrors); validateStaticObjects(snippets, dimensionKey, dimJson, blockingErrors);
validateObjectScaleFactor(dimensionKey, dimJson, blockingErrors); validateObjectScaleFactor(dimensionKey, dimJson, blockingErrors);
validateDimensionStack(packFolder, dimensionKey, dimJson, dimensionKeys, blockingErrors); validateDimensionStack(snippets, dimensionKey, dimJson, dimensionKeys, blockingErrors);
validateUpperDimension(dimensionKey, dimJson, dimensionKeys, blockingErrors); validateUpperDimension(dimensionKey, dimJson, dimensionKeys, blockingErrors);
JSONArray regionsArray = dimJson.optJSONArray("regions"); JSONArray regionsArray = dimJson.optJSONArray("regions");
@@ -177,7 +179,7 @@ final class PackDimensionValidator {
+ minimum * 2 + ", " + minimum * 4 + ", or " + minimum * 8 + "."); + minimum * 2 + ", " + minimum * 4 + ", or " + minimum * 8 + ".");
} }
static void validateDimensionStack(File packFolder, String dimensionKey, JSONObject dimension, Set<String> dimensionKeys, static void validateDimensionStack(PackSnippets snippets, String dimensionKey, JSONObject dimension, Set<String> dimensionKeys,
List<String> blockingErrors) { List<String> blockingErrors) {
if (!dimension.has("dimensionStack")) { if (!dimension.has("dimensionStack")) {
return; return;
@@ -231,10 +233,10 @@ final class PackDimensionValidator {
} }
validateInteger(stack, "spacer", 0, 256, context, blockingErrors); validateInteger(stack, "spacer", 0, 256, context, blockingErrors);
validateDimensionStackBlend(packFolder, context, stack, blockingErrors); validateDimensionStackBlend(snippets, context, stack, blockingErrors);
} }
private static void validateDimensionStackBlend(File packFolder, String context, JSONObject stack, private static void validateDimensionStackBlend(PackSnippets snippets, String context, JSONObject stack,
List<String> blockingErrors) { List<String> blockingErrors) {
if (!stack.has("blend")) { if (!stack.has("blend")) {
return; return;
@@ -251,7 +253,7 @@ final class PackDimensionValidator {
Object rawStyle = blend.opt("style"); Object rawStyle = blend.opt("style");
boolean styleObject = rawStyle instanceof JSONObject; boolean styleObject = rawStyle instanceof JSONObject;
boolean styleSnippet = rawStyle instanceof String reference boolean styleSnippet = rawStyle instanceof String reference
&& SnippetFolders.discover(packFolder, STYLE_SNIPPET_TYPE).folders().stream() && snippets.folders(STYLE_SNIPPET_TYPE).folders().stream()
.anyMatch(folder -> reference.startsWith(folder + "/")); .anyMatch(folder -> reference.startsWith(folder + "/"));
if (!styleObject && !styleSnippet) { if (!styleObject && !styleSnippet) {
blockingErrors.add(context + ".blend.style must be an object or style snippet reference."); blockingErrors.add(context + ".blend.style must be an object or style snippet reference.");
@@ -259,15 +261,15 @@ final class PackDimensionValidator {
} }
if (styleSnippet) { if (styleSnippet) {
validateDimensionStackStyleSnippet( validateDimensionStackStyleSnippet(
packFolder, context + ".blend.style", (String) rawStyle, blockingErrors); snippets, context + ".blend.style", (String) rawStyle, blockingErrors);
} }
} }
} }
private static void validateDimensionStackStyleSnippet(File packFolder, String context, String reference, private static void validateDimensionStackStyleSnippet(PackSnippets snippets, String context, String reference,
List<String> blockingErrors) { List<String> blockingErrors) {
try { try {
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, STYLE_SNIPPET_TYPE).find(packFolder, reference); SnippetFolders.Lookup snippet = snippets.find(STYLE_SNIPPET_TYPE, reference);
if (!snippet.found()) { if (!snippet.found()) {
blockingErrors.add(context + " references missing style snippet '" + reference + "'."); blockingErrors.add(context + " references missing style snippet '" + reference + "'.");
return; return;
@@ -281,13 +283,18 @@ final class PackDimensionValidator {
static void validateStaticObjects(File packFolder, String dimensionKey, JSONObject dimension, static void validateStaticObjects(File packFolder, String dimensionKey, JSONObject dimension,
List<String> blockingErrors) { List<String> blockingErrors) {
validateStaticObjects(new PackSnippets(packFolder), dimensionKey, dimension, blockingErrors);
}
private static void validateStaticObjects(PackSnippets snippets, String dimensionKey, JSONObject dimension,
List<String> blockingErrors) {
if (!dimension.has("staticObjects")) { if (!dimension.has("staticObjects")) {
return; return;
} }
JSONObject height = resolveDimensionHeight(packFolder, dimension); JSONObject height = resolveDimensionHeight(snippets, dimension);
int minY = height == null ? -64 : (int) height.optDouble("min", 16D); int minY = height == null ? -64 : (int) height.optDouble("min", 16D);
int maxY = height == null ? 320 : (int) height.optDouble("max", 32D); int maxY = height == null ? 320 : (int) height.optDouble("max", 32D);
PackStaticObjectValidator.validate(packFolder, dimensionKey, dimension, minY, maxY, blockingErrors); PackStaticObjectValidator.validate(snippets, dimensionKey, dimension, minY, maxY, blockingErrors);
} }
static void validateImportedStructurePolicy(String dimensionKey, JSONObject dimension, static void validateImportedStructurePolicy(String dimensionKey, JSONObject dimension,
@@ -434,12 +441,12 @@ final class PackDimensionValidator {
* the IrisDimension field initializer (-64..320); present-but-partial means the IrisRange field * the IrisDimension field initializer (-64..320); present-but-partial means the IrisRange field
* initializers (min 16, max 32); logicalHeight absent means 256. * initializers (min 16, max 32); logicalHeight absent means 256.
*/ */
static void validateDimensionHeights(File packFolder, String dimensionKey, JSONObject dimJson, List<String> blockingErrors) { static void validateDimensionHeights(PackSnippets snippets, String dimensionKey, JSONObject dimJson, List<String> blockingErrors) {
if (dimJson.has("dimensionHeight") && dimJson.isNull("dimensionHeight")) { if (dimJson.has("dimensionHeight") && dimJson.isNull("dimensionHeight")) {
blockingErrors.add("Dimension '" + dimensionKey + "' dimensionHeight must be an object or a range snippet reference."); blockingErrors.add("Dimension '" + dimensionKey + "' dimensionHeight must be an object or a range snippet reference.");
return; return;
} }
JSONObject range = resolveDimensionHeight(packFolder, dimJson); JSONObject range = resolveDimensionHeight(snippets, dimJson);
if (range == null && dimJson.has("dimensionHeight")) { if (range == null && dimJson.has("dimensionHeight")) {
blockingErrors.add("Dimension '" + dimensionKey + "' dimensionHeight must be an object or a resolvable range snippet reference."); blockingErrors.add("Dimension '" + dimensionKey + "' dimensionHeight must be an object or a resolvable range snippet reference.");
return; return;
@@ -598,7 +605,7 @@ final class PackDimensionValidator {
return true; return true;
} }
private static JSONObject resolveDimensionHeight(File packFolder, JSONObject dimJson) { private static JSONObject resolveDimensionHeight(PackSnippets snippets, JSONObject dimJson) {
if (!dimJson.has("dimensionHeight") || dimJson.isNull("dimensionHeight")) { if (!dimJson.has("dimensionHeight") || dimJson.isNull("dimensionHeight")) {
return null; return null;
} }
@@ -612,7 +619,7 @@ final class PackDimensionValidator {
if (reference == null || !reference.startsWith("snippet/")) { if (reference == null || !reference.startsWith("snippet/")) {
return null; return null;
} }
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, RANGE_SNIPPET_TYPE).find(packFolder, reference); SnippetFolders.Lookup snippet = snippets.find(RANGE_SNIPPET_TYPE, reference);
if (!snippet.found()) { if (!snippet.found()) {
return null; return null;
} }
@@ -18,6 +18,7 @@
package art.arcane.iris.pack; package art.arcane.iris.pack;
import art.arcane.iris.pack.loading.PackSnippets;
import art.arcane.iris.pack.loading.SnippetFolders; import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.json.JSONObject;
@@ -96,6 +97,7 @@ final class PackGeneratorDuplicateValidator {
if (!biomesFolder.isDirectory()) { if (!biomesFolder.isDirectory()) {
return referenced; return referenced;
} }
PackSnippets snippets = new PackSnippets(packFolder);
for (File biomeFile : PackValidationIo.listJsonRecursive(biomesFolder)) { for (File biomeFile : PackValidationIo.listJsonRecursive(biomesFolder)) {
JSONObject biome; JSONObject biome;
try { try {
@@ -111,7 +113,7 @@ final class PackGeneratorDuplicateValidator {
JSONObject link = links.optJSONObject(i); JSONObject link = links.optJSONObject(i);
if (link == null) { if (link == null) {
String reference = links.optString(i, null); String reference = links.optString(i, null);
link = resolveGeneratorLayerSnippet(packFolder, reference); link = resolveGeneratorLayerSnippet(snippets, reference);
if (link == null) { if (link == null) {
continue; continue;
} }
@@ -122,11 +124,11 @@ final class PackGeneratorDuplicateValidator {
return referenced; return referenced;
} }
private static JSONObject resolveGeneratorLayerSnippet(File packFolder, String reference) { private static JSONObject resolveGeneratorLayerSnippet(PackSnippets snippets, String reference) {
if (reference == null || !reference.startsWith("snippet/")) { if (reference == null || !reference.startsWith("snippet/")) {
return null; return null;
} }
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, GENERATOR_SNIPPET_TYPE).find(packFolder, reference); SnippetFolders.Lookup snippet = snippets.find(GENERATOR_SNIPPET_TYPE, reference);
if (!snippet.found()) { if (!snippet.found()) {
return null; return null;
} }
@@ -17,6 +17,7 @@ import art.arcane.iris.generation.terrain.IrisRegion;
import art.arcane.iris.generation.terrain.ShoreBiomeLineages; import art.arcane.iris.generation.terrain.ShoreBiomeLineages;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.IrisRegistrant; import art.arcane.iris.pack.loading.IrisRegistrant;
import art.arcane.iris.pack.loading.PackSnippets;
import art.arcane.iris.pack.loading.SnippetFolders; import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.iris.pack.schema.annotation.Snippet; import art.arcane.iris.pack.schema.annotation.Snippet;
import art.arcane.iris.spi.IrisLogging; import art.arcane.iris.spi.IrisLogging;
@@ -85,10 +86,11 @@ final class PackHydrologyValidator {
sortedDimensions.sort(Comparator.comparing(File::getPath)); sortedDimensions.sort(Comparator.comparing(File::getPath));
File dimensionsFolder = new File(packFolder, PackValidator.DIMENSIONS_FOLDER); File dimensionsFolder = new File(packFolder, PackValidator.DIMENSIONS_FOLDER);
Findings findings = new Findings(errors, warnings); Findings findings = new Findings(errors, warnings);
PackSnippets snippets = new PackSnippets(packFolder);
IrisData data = null; IrisData data = null;
try { try {
for (File dimensionFile : sortedDimensions) { for (File dimensionFile : sortedDimensions) {
data = validateDimension(packFolder, dimensionsFolder, dimensionFile, data, findings); data = validateDimension(snippets, dimensionsFolder, dimensionFile, data, findings);
} }
} finally { } finally {
close(packFolder, data, errors); close(packFolder, data, errors);
@@ -96,7 +98,7 @@ final class PackHydrologyValidator {
return new Validation(errors, warnings); return new Validation(errors, warnings);
} }
private static IrisData validateDimension(File packFolder, File dimensionsFolder, File dimensionFile, IrisData data, private static IrisData validateDimension(PackSnippets snippets, File dimensionsFolder, File dimensionFile, IrisData data,
Findings findings) { Findings findings) {
List<String> errors = findings.errors(); List<String> errors = findings.errors();
JSONObject dimension = PackValidationIo.readJson(dimensionFile); JSONObject dimension = PackValidationIo.readJson(dimensionFile);
@@ -109,7 +111,7 @@ final class PackHydrologyValidator {
errors.add(path + " must be an object."); errors.add(path + " must be an object.");
return data; return data;
} }
warnUnknownKeys(path, hydrology, IrisHydrology.class, packFolder, findings.warnings()); warnUnknownKeys(path, hydrology, IrisHydrology.class, snippets, findings.warnings());
if (!hydrology.optBoolean("enabled", false)) { if (!hydrology.optBoolean("enabled", false)) {
return data; return data;
} }
@@ -119,13 +121,13 @@ final class PackHydrologyValidator {
Set<String> fluids = fluidNames(hydrology); Set<String> fluids = fluidNames(hydrology);
Set<String> seams = seamNames(hydrology); Set<String> seams = seamNames(hydrology);
validateFluidReferences(path, hydrology, fluids, errors); validateFluidReferences(path, hydrology, fluids, errors);
IrisData loaded = data == null ? IrisData.openDatapackCompiler(packFolder) : data; IrisData loaded = data == null ? IrisData.openDatapackCompiler(snippets.packFolder()) : data;
IrisDimension loadedDimension = loaded.getDimensionLoader().load(dimensionKey, false); IrisDimension loadedDimension = loaded.getDimensionLoader().load(dimensionKey, false);
if (loadedDimension == null) { if (loadedDimension == null) {
return loaded; return loaded;
} }
warnMantleOff("Dimension '" + dimensionKey + "'", loadedDimension, findings.warnings()); warnMantleOff("Dimension '" + dimensionKey + "'", loadedDimension, findings.warnings());
validatePolicies(path, dimensionKey, loaded, loadedDimension, new PolicyFluids(fluids, seams), errors, findings.warnings()); validatePolicies(path, dimensionKey, loaded, loadedDimension, new PolicyFluids(fluids, seams), snippets, findings);
warnShoreBiomesWithoutWidth(dimensionKey, loaded, loadedDimension, findings.warnings()); warnShoreBiomesWithoutWidth(dimensionKey, loaded, loadedDimension, findings.warnings());
if (errors.size() == reported && validateCompile(path, loadedDimension, errors)) { if (errors.size() == reported && validateCompile(path, loadedDimension, errors)) {
validateDecoratorBlocks(path, loaded, loadedDimension.getHydrology(), errors); validateDecoratorBlocks(path, loaded, loadedDimension.getHydrology(), errors);
@@ -134,8 +136,8 @@ final class PackHydrologyValidator {
return loaded; return loaded;
} }
static void warnUnknownKeys(String field, Object value, Type type, File packFolder, List<String> warnings) { static void warnUnknownKeys(String field, Object value, Type type, PackSnippets snippets, List<String> warnings) {
warnUnknownKeys(field, value, type, new KeyScan(packFolder, warnings, new HashSet<>())); warnUnknownKeys(field, value, type, new KeyScan(snippets, warnings, new HashSet<>()));
} }
private static void warnUnknownKeys(String field, Object value, Type type, KeyScan scan) { private static void warnUnknownKeys(String field, Object value, Type type, KeyScan scan) {
@@ -173,8 +175,7 @@ final class PackHydrologyValidator {
} }
private static void warnUnknownSnippetKeys(String field, String reference, Class<?> type, KeyScan scan) { private static void warnUnknownSnippetKeys(String field, String reference, Class<?> type, KeyScan scan) {
SnippetFolders.Lookup lookup = SnippetFolders.discover(scan.packFolder(), type.getDeclaredAnnotation(Snippet.class).value()) SnippetFolders.Lookup lookup = scan.snippets().find(type.getDeclaredAnnotation(Snippet.class).value(), reference);
.find(scan.packFolder(), reference);
String snippet = lookup.found() ? lookup.key() : lookup.triedKeys().get(0); String snippet = lookup.found() ? lookup.key() : lookup.triedKeys().get(0);
if (!scan.activeSnippets().add(snippet)) { if (!scan.activeSnippets().add(snippet)) {
return; return;
@@ -391,14 +392,16 @@ final class PackHydrologyValidator {
} }
private static void validatePolicies(String path, String dimensionKey, IrisData data, IrisDimension dimension, PolicyFluids fluids, private static void validatePolicies(String path, String dimensionKey, IrisData data, IrisDimension dimension, PolicyFluids fluids,
List<String> errors, List<String> warnings) { PackSnippets snippets, Findings findings) {
warnUnknownPolicyKeys("Dimension '" + dimensionKey + "'." + POLICY, dimension, data, warnings); List<String> errors = findings.errors();
List<String> warnings = findings.warnings();
warnUnknownPolicyKeys("Dimension '" + dimensionKey + "'." + POLICY, dimension, snippets, warnings);
validatePolicy("Dimension '" + dimensionKey + "'." + POLICY, dimension.getHydrologyPolicy(), data, fluids, path, errors); validatePolicy("Dimension '" + dimensionKey + "'." + POLICY, dimension.getHydrologyPolicy(), data, fluids, path, errors);
List<IrisRegion> regions = new ArrayList<>(dimension.getAllRegions(() -> data)); List<IrisRegion> regions = new ArrayList<>(dimension.getAllRegions(() -> data));
regions.sort(Comparator.comparing(IrisRegion::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder()))); regions.sort(Comparator.comparing(IrisRegion::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder())));
for (IrisRegion region : regions) { for (IrisRegion region : regions) {
if (region != null) { if (region != null) {
warnUnknownPolicyKeys("Region '" + region.getLoadKey() + "'." + POLICY, region, data, warnings); warnUnknownPolicyKeys("Region '" + region.getLoadKey() + "'." + POLICY, region, snippets, warnings);
validatePolicy("Region '" + region.getLoadKey() + "'." + POLICY, region.getHydrologyPolicy(), data, fluids, path, errors); validatePolicy("Region '" + region.getLoadKey() + "'." + POLICY, region.getHydrologyPolicy(), data, fluids, path, errors);
} }
} }
@@ -406,17 +409,17 @@ final class PackHydrologyValidator {
biomes.sort(Comparator.comparing(IrisBiome::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder()))); biomes.sort(Comparator.comparing(IrisBiome::getLoadKey, Comparator.nullsFirst(Comparator.naturalOrder())));
for (IrisBiome biome : biomes) { for (IrisBiome biome : biomes) {
if (biome != null) { if (biome != null) {
warnUnknownPolicyKeys("Biome '" + biome.getLoadKey() + "'." + POLICY, biome, data, warnings); warnUnknownPolicyKeys("Biome '" + biome.getLoadKey() + "'." + POLICY, biome, snippets, warnings);
validatePolicy("Biome '" + biome.getLoadKey() + "'." + POLICY, biome.getHydrologyPolicy(), data, fluids, path, errors); validatePolicy("Biome '" + biome.getLoadKey() + "'." + POLICY, biome.getHydrologyPolicy(), data, fluids, path, errors);
} }
} }
} }
private static void warnUnknownPolicyKeys(String field, IrisRegistrant owner, IrisData data, List<String> warnings) { private static void warnUnknownPolicyKeys(String field, IrisRegistrant owner, PackSnippets snippets, List<String> warnings) {
File file = owner.getLoadFile(); File file = owner.getLoadFile();
JSONObject json = file == null ? null : PackValidationIo.readJson(file); JSONObject json = file == null ? null : PackValidationIo.readJson(file);
if (json != null) { if (json != null) {
warnUnknownKeys(field, json.opt(POLICY), IrisHydrologyPolicy.class, data.getDataFolder(), warnings); warnUnknownKeys(field, json.opt(POLICY), IrisHydrologyPolicy.class, snippets, warnings);
} }
} }
@@ -623,6 +626,6 @@ final class PackHydrologyValidator {
private record Findings(List<String> errors, List<String> warnings) { private record Findings(List<String> errors, List<String> warnings) {
} }
private record KeyScan(File packFolder, List<String> warnings, Set<String> activeSnippets) { private record KeyScan(PackSnippets snippets, List<String> warnings, Set<String> activeSnippets) {
} }
} }
@@ -1,12 +1,12 @@
package art.arcane.iris.pack; package art.arcane.iris.pack;
import art.arcane.iris.pack.loading.PackSnippets;
import art.arcane.iris.pack.loading.SnippetFolders; import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.iris.structure.object.IrisObjectPlacementScaleInterpolator; import art.arcane.iris.structure.object.IrisObjectPlacementScaleInterpolator;
import art.arcane.iris.structure.object.IrisStaticObject; import art.arcane.iris.structure.object.IrisStaticObject;
import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.json.JSONObject;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@@ -19,7 +19,7 @@ final class PackStaticObjectValidator {
private PackStaticObjectValidator() { private PackStaticObjectValidator() {
} }
static void validate(File packFolder, String dimensionKey, JSONObject dimension, static void validate(PackSnippets snippets, String dimensionKey, JSONObject dimension,
int minY, int maxY, List<String> errors) { int minY, int maxY, List<String> errors) {
if (!dimension.has("staticObjects")) { if (!dimension.has("staticObjects")) {
return; return;
@@ -30,7 +30,7 @@ final class PackStaticObjectValidator {
errors.add(path + " must be an array."); errors.add(path + " must be an array.");
return; return;
} }
Path objectsRoot = packFolder.toPath().toAbsolutePath().normalize().resolve("objects"); Path objectsRoot = snippets.packFolder().toPath().toAbsolutePath().normalize().resolve("objects");
for (int index = 0; index < entries.length(); index++) { for (int index = 0; index < entries.length(); index++) {
String entryPath = path + "[" + index + "]"; String entryPath = path + "[" + index + "]";
JSONObject entry = entries.optJSONObject(index); JSONObject entry = entries.optJSONObject(index);
@@ -39,7 +39,7 @@ final class PackStaticObjectValidator {
continue; continue;
} }
validateObjectKey(entryPath, entry, objectsRoot, errors); validateObjectKey(entryPath, entry, objectsRoot, errors);
validatePosition(packFolder, entryPath, entry, minY, maxY, errors); validatePosition(snippets, entryPath, entry, minY, maxY, errors);
validateRotation(entryPath, entry, errors); validateRotation(entryPath, entry, errors);
validateNumber(entryPath, entry, "scale", IrisStaticObject.MINIMUM_SCALE, validateNumber(entryPath, entry, "scale", IrisStaticObject.MINIMUM_SCALE,
IrisStaticObject.MAXIMUM_SCALE, errors); IrisStaticObject.MAXIMUM_SCALE, errors);
@@ -47,7 +47,7 @@ final class PackStaticObjectValidator {
validateBoolean(entryPath, entry, "bore", errors); validateBoolean(entryPath, entry, "bore", errors);
validateBoolean(entryPath, entry, "smartBore", errors); validateBoolean(entryPath, entry, "smartBore", errors);
validateSeed(entryPath, entry, errors); validateSeed(entryPath, entry, errors);
validateEdits(packFolder, entryPath, entry, errors); validateEdits(snippets, entryPath, entry, errors);
} }
} }
@@ -64,9 +64,9 @@ final class PackStaticObjectValidator {
} }
} }
private static void validatePosition(File packFolder, String path, JSONObject entry, private static void validatePosition(PackSnippets snippets, String path, JSONObject entry,
int minY, int maxY, List<String> errors) { int minY, int maxY, List<String> errors) {
JSONObject position = resolveObject(packFolder, entry.opt("position"), "position-3d", JSONObject position = resolveObject(snippets, entry.opt("position"), "position-3d",
path + ".position", errors); path + ".position", errors);
if (position == null) { if (position == null) {
return; return;
@@ -121,7 +121,7 @@ final class PackStaticObjectValidator {
errors.add(path + ".seed must be an integer between " + Long.MIN_VALUE + " and " + Long.MAX_VALUE + "."); errors.add(path + ".seed must be an integer between " + Long.MIN_VALUE + " and " + Long.MAX_VALUE + ".");
} }
private static void validateEdits(File packFolder, String path, JSONObject entry, List<String> errors) { private static void validateEdits(PackSnippets snippets, String path, JSONObject entry, List<String> errors) {
if (!entry.has("edit")) { if (!entry.has("edit")) {
return; return;
} }
@@ -132,12 +132,12 @@ final class PackStaticObjectValidator {
} }
for (int index = 0; index < edits.length(); index++) { for (int index = 0; index < edits.length(); index++) {
String editPath = path + ".edit[" + index + "]"; String editPath = path + ".edit[" + index + "]";
JSONObject edit = resolveObject(packFolder, edits.opt(index), "object-block-replacer", editPath, errors); JSONObject edit = resolveObject(snippets, edits.opt(index), "object-block-replacer", editPath, errors);
if (edit == null) { if (edit == null) {
continue; continue;
} }
validateBlockList(editPath + ".find", edit.optJSONArray("find"), errors); validateBlockList(editPath + ".find", edit.optJSONArray("find"), errors);
JSONObject replacement = resolveObject(packFolder, edit.opt("replace"), "palette", JSONObject replacement = resolveObject(snippets, edit.opt("replace"), "palette",
editPath + ".replace", errors); editPath + ".replace", errors);
if (replacement != null) { if (replacement != null) {
validateBlockList(editPath + ".replace.palette", replacement.optJSONArray("palette"), errors); validateBlockList(editPath + ".replace.palette", replacement.optJSONArray("palette"), errors);
@@ -160,13 +160,13 @@ final class PackStaticObjectValidator {
} }
} }
private static JSONObject resolveObject(File packFolder, Object value, String snippetType, private static JSONObject resolveObject(PackSnippets snippets, Object value, String snippetType,
String path, List<String> errors) { String path, List<String> errors) {
if (value instanceof JSONObject object) { if (value instanceof JSONObject object) {
return object; return object;
} }
if (value instanceof String reference && reference.startsWith("snippet/")) { if (value instanceof String reference && reference.startsWith("snippet/")) {
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, snippetType).find(packFolder, reference); SnippetFolders.Lookup snippet = snippets.find(snippetType, reference);
if (!snippet.found()) { if (!snippet.found()) {
errors.add(path + " references missing " + snippetType + " snippet '" + reference + "'."); errors.add(path + " references missing " + snippetType + " snippet '" + reference + "'.");
return null; return null;
@@ -18,6 +18,7 @@
package art.arcane.iris.pack; package art.arcane.iris.pack;
import art.arcane.iris.pack.loading.PackSnippets;
import art.arcane.iris.pack.loading.SnippetFolders; import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.volmlib.util.json.JSONArray; import art.arcane.volmlib.util.json.JSONArray;
import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.json.JSONObject;
@@ -56,6 +57,7 @@ final class PackStyledRangeDefaultValidator {
return new Validation(errors, warnings); return new Validation(errors, warnings);
} }
PackSnippets snippets = new PackSnippets(packFolder);
for (String folderName : PackValidator.STRUCTURE_HOST_FOLDERS) { for (String folderName : PackValidator.STRUCTURE_HOST_FOLDERS) {
File resourceFolder = new File(packFolder, folderName); File resourceFolder = new File(packFolder, folderName);
if (!resourceFolder.isDirectory()) { if (!resourceFolder.isDirectory()) {
@@ -73,14 +75,14 @@ final class PackStyledRangeDefaultValidator {
continue; continue;
} }
validateObjectPlacements(packFolder, type, key, json, errors, warnings); validateObjectPlacements(snippets, type, key, json, errors, warnings);
validateCaveProfileThreshold(packFolder, type, key, json.optJSONObject("caveProfile"), errors, warnings); validateCaveProfileThreshold(snippets, type, key, json.optJSONObject("caveProfile"), errors, warnings);
} }
} }
return new Validation(errors, warnings); return new Validation(errors, warnings);
} }
private static void validateObjectPlacements(File packFolder, String type, String key, JSONObject json, private static void validateObjectPlacements(PackSnippets snippets, String type, String key, JSONObject json,
List<String> errors, List<String> warnings) { List<String> errors, List<String> warnings) {
JSONArray objects = json.optJSONArray("objects"); JSONArray objects = json.optJSONArray("objects");
if (objects == null) { if (objects == null) {
@@ -91,33 +93,33 @@ final class PackStyledRangeDefaultValidator {
if (placement == null || !placement.has("densityStyle") || placement.isNull("densityStyle")) { if (placement == null || !placement.has("densityStyle") || placement.isNull("densityStyle")) {
continue; continue;
} }
checkRange(packFolder, placement.opt("densityStyle"), checkRange(snippets, placement.opt("densityStyle"),
type + " '" + key + "' objects[" + i + "].densityStyle", type + " '" + key + "' objects[" + i + "].densityStyle",
"16-32 objects per chunk", "remove densityStyle to use the scalar density field", "16-32 objects per chunk", "remove densityStyle to use the scalar density field",
errors, warnings); errors, warnings);
} }
} }
private static void validateCaveProfileThreshold(File packFolder, String type, String key, JSONObject caveProfile, private static void validateCaveProfileThreshold(PackSnippets snippets, String type, String key, JSONObject caveProfile,
List<String> errors, List<String> warnings) { List<String> errors, List<String> warnings) {
if (caveProfile == null || !caveProfile.has("densityThreshold") || caveProfile.isNull("densityThreshold")) { if (caveProfile == null || !caveProfile.has("densityThreshold") || caveProfile.isNull("densityThreshold")) {
return; return;
} }
checkRange(packFolder, caveProfile.opt("densityThreshold"), checkRange(snippets, caveProfile.opt("densityThreshold"),
type + " '" + key + "' caveProfile.densityThreshold", type + " '" + key + "' caveProfile.densityThreshold",
"a carve threshold of 16-32, hollowing the entire vertical range", "a carve threshold of 16-32, hollowing the entire vertical range",
"remove densityThreshold to keep the cave profile default", "remove densityThreshold to keep the cave profile default",
errors, warnings); errors, warnings);
} }
private static void checkRange(File packFolder, Object raw, String path, String consequence, String removal, private static void checkRange(PackSnippets snippets, Object raw, String path, String consequence, String removal,
List<String> errors, List<String> warnings) { List<String> errors, List<String> warnings) {
JSONObject range = null; JSONObject range = null;
String via = ""; String via = "";
if (raw instanceof JSONObject inline) { if (raw instanceof JSONObject inline) {
range = inline; range = inline;
} else if (raw instanceof String reference && reference.startsWith("snippet/")) { } else if (raw instanceof String reference && reference.startsWith("snippet/")) {
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, STYLE_RANGE_SNIPPET_TYPE).find(packFolder, reference); SnippetFolders.Lookup snippet = snippets.find(STYLE_RANGE_SNIPPET_TYPE, reference);
if (!snippet.found()) { if (!snippet.found()) {
return; // Missing snippets are reported by the content-key machinery. return; // Missing snippets are reported by the content-key machinery.
} }
@@ -1,5 +1,6 @@
package art.arcane.iris.pack; package art.arcane.iris.pack;
import art.arcane.iris.pack.loading.PackSnippets;
import art.arcane.iris.pack.loading.SnippetFolders; import art.arcane.iris.pack.loading.SnippetFolders;
import art.arcane.iris.generation.terrain.IrisTerrain3D; import art.arcane.iris.generation.terrain.IrisTerrain3D;
import art.arcane.iris.generation.noise.NoiseStyle; import art.arcane.iris.generation.noise.NoiseStyle;
@@ -35,12 +36,13 @@ final class PackTerrain3DValidator {
if (packFolder == null || !packFolder.isDirectory()) { if (packFolder == null || !packFolder.isDirectory()) {
return errors; return errors;
} }
PackSnippets snippets = new PackSnippets(packFolder);
File biomeFolder = new File(packFolder, "biomes"); File biomeFolder = new File(packFolder, "biomes");
for (File biomeFile : files(biomeFolder)) { for (File biomeFile : files(biomeFolder)) {
JsonObject biome = readObject(biomeFile, "Biome '" + PackValidationIo.deriveKey(biomeFolder, biomeFile) JsonObject biome = readObject(biomeFile, "Biome '" + PackValidationIo.deriveKey(biomeFolder, biomeFile)
+ "'", errors); + "'", errors);
if (biome != null && biome.has("terrain3D") && !biome.get("terrain3D").isJsonNull()) { if (biome != null && biome.has("terrain3D") && !biome.get("terrain3D").isJsonNull()) {
validateProfile(packFolder, biome.get("terrain3D"), validateProfile(snippets, biome.get("terrain3D"),
"Biome '" + PackValidationIo.deriveKey(biomeFolder, biomeFile) + "' terrain3D", errors); "Biome '" + PackValidationIo.deriveKey(biomeFolder, biomeFile) + "' terrain3D", errors);
} }
} }
@@ -49,7 +51,7 @@ final class PackTerrain3DValidator {
String location = "Terrain3D snippet '" + PackValidationIo.deriveKey(snippetFolder, snippetFile) + "'"; String location = "Terrain3D snippet '" + PackValidationIo.deriveKey(snippetFolder, snippetFile) + "'";
JsonObject profile = readObject(snippetFile, location, errors); JsonObject profile = readObject(snippetFile, location, errors);
if (profile != null) { if (profile != null) {
validateProfile(packFolder, profile, location, errors); validateProfile(snippets, profile, location, errors);
} }
} }
return errors; return errors;
@@ -64,8 +66,8 @@ final class PackTerrain3DValidator {
return files; return files;
} }
private static void validateProfile(File packFolder, JsonElement raw, String location, List<String> errors) { private static void validateProfile(PackSnippets snippets, JsonElement raw, String location, List<String> errors) {
JsonObject object = resolveObject(packFolder, raw, "terrain-3d", location, errors); JsonObject object = resolveObject(snippets, raw, "terrain-3d", location, errors);
if (object == null) { if (object == null) {
return; return;
} }
@@ -88,7 +90,7 @@ final class PackTerrain3DValidator {
} }
case "seed" -> requireInteger(value, path, errors); case "seed" -> requireInteger(value, path, errors);
case "densityStyle", "crackStyle" -> { case "densityStyle", "crackStyle" -> {
JsonObject style = validateStyle(packFolder, value, path, 0, errors); JsonObject style = validateStyle(snippets, value, path, 0, errors);
if (style != null) { if (style != null) {
normalized.add(field, style); normalized.add(field, style);
} }
@@ -106,13 +108,13 @@ final class PackTerrain3DValidator {
} }
} }
private static JsonObject validateStyle(File packFolder, JsonElement raw, String location, private static JsonObject validateStyle(PackSnippets snippets, JsonElement raw, String location,
int depth, List<String> errors) { int depth, List<String> errors) {
if (depth > 32) { if (depth > 32) {
errors.add(location + " exceeds the maximum style nesting depth of 32."); errors.add(location + " exceeds the maximum style nesting depth of 32.");
return null; return null;
} }
JsonObject object = resolveObject(packFolder, raw, "style", location, errors); JsonObject object = resolveObject(snippets, raw, "style", location, errors);
if (object == null) { if (object == null) {
return null; return null;
} }
@@ -139,7 +141,7 @@ final class PackTerrain3DValidator {
} }
case "fracture" -> { case "fracture" -> {
if (!value.isJsonNull()) { if (!value.isJsonNull()) {
JsonObject fracture = validateStyle(packFolder, value, path, depth + 1, errors); JsonObject fracture = validateStyle(snippets, value, path, depth + 1, errors);
if (fracture != null) { if (fracture != null) {
normalized.add(field, fracture); normalized.add(field, fracture);
} }
@@ -158,7 +160,7 @@ final class PackTerrain3DValidator {
return normalized; return normalized;
} }
private static JsonObject resolveObject(File packFolder, JsonElement raw, String snippetType, private static JsonObject resolveObject(PackSnippets snippets, JsonElement raw, String snippetType,
String location, List<String> errors) { String location, List<String> errors) {
if (raw.isJsonObject()) { if (raw.isJsonObject()) {
return raw.getAsJsonObject(); return raw.getAsJsonObject();
@@ -169,7 +171,7 @@ final class PackTerrain3DValidator {
return null; return null;
} }
String reference = raw.getAsString(); String reference = raw.getAsString();
SnippetFolders.Lookup snippet = SnippetFolders.discover(packFolder, snippetType).find(packFolder, reference); SnippetFolders.Lookup snippet = snippets.find(snippetType, reference);
if (!snippet.found()) { if (!snippet.found()) {
errors.add(location + " references an unavailable " + snippetType + " snippet '" + reference + "'."); errors.add(location + " references an unavailable " + snippetType + " snippet '" + reference + "'.");
return null; return null;
@@ -18,7 +18,7 @@
package art.arcane.iris.pack.ingest; package art.arcane.iris.pack.ingest;
import art.arcane.iris.pack.loading.SnippetFolders; import art.arcane.iris.pack.loading.PackSnippets;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
@@ -40,12 +40,14 @@ final class IngestPack {
private static final String SNIPPET_PREFIX = "snippet/"; private static final String SNIPPET_PREFIX = "snippet/";
private final Path root; private final Path root;
private final PackSnippets snippets;
private final Map<String, JsonObject> loaded = new HashMap<>(); private final Map<String, JsonObject> loaded = new HashMap<>();
private final Map<String, JsonObject> pending = new TreeMap<>(); private final Map<String, JsonObject> pending = new TreeMap<>();
private final Set<String> generated = new TreeSet<>(); private final Set<String> generated = new TreeSet<>();
IngestPack(Path root) { IngestPack(Path root) {
this.root = root; this.root = root;
this.snippets = new PackSnippets(root.toFile());
} }
Path root() { Path root() {
@@ -115,7 +117,7 @@ final class IngestPack {
if (!reference.startsWith(SNIPPET_PREFIX)) { if (!reference.startsWith(SNIPPET_PREFIX)) {
return null; return null;
} }
for (String key : SnippetFolders.discover(root.toFile(), snippetType).candidateKeys(reference)) { for (String key : snippets.folders(snippetType).candidateKeys(reference)) {
Optional<JsonObject> snippet = find(key + ".json"); Optional<JsonObject> snippet = find(key + ".json");
if (snippet.isPresent()) { if (snippet.isPresent()) {
return snippet.get().deepCopy(); return snippet.get().deepCopy();
@@ -0,0 +1,30 @@
package art.arcane.iris.pack.loading;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* One pack's snippet folders, discovered at most once per snippet type. Create one per validation run rather than
* sharing it, since pack files change between runs during hotload.
*/
public final class PackSnippets {
private final File packFolder;
private final Map<String, SnippetFolders> foldersByType = new HashMap<>();
public PackSnippets(File packFolder) {
this.packFolder = packFolder;
}
public File packFolder() {
return packFolder;
}
public SnippetFolders folders(String snippetType) {
return foldersByType.computeIfAbsent(snippetType, type -> SnippetFolders.discover(packFolder, type));
}
public SnippetFolders.Lookup find(String snippetType, String reference) {
return folders(snippetType).find(packFolder, reference);
}
}
@@ -3,6 +3,7 @@ package art.arcane.iris.pack.loading;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.io.File; import java.io.File;
import java.io.IOException;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.InvalidPathException; import java.nio.file.InvalidPathException;
import java.nio.file.Path; import java.nio.file.Path;
@@ -60,8 +61,8 @@ public record SnippetFolders(String legacy, List<String> namespaced) {
List<String> candidates = candidateKeys(reference); List<String> candidates = candidateKeys(reference);
Path root = packFolder.toPath().toAbsolutePath().normalize(); Path root = packFolder.toPath().toAbsolutePath().normalize();
for (String key : candidates) { for (String key : candidates) {
Path file = fileInsideFolder(root, key); Path file = existingFileInsideFolder(root, key);
if (file != null && Files.isRegularFile(file)) { if (file != null) {
return new Lookup(file.toFile(), key, candidates); return new Lookup(file.toFile(), key, candidates);
} }
} }
@@ -79,7 +80,7 @@ public record SnippetFolders(String legacy, List<String> namespaced) {
return matches; return matches;
} }
private @Nullable Path fileInsideFolder(Path root, String key) { private @Nullable Path existingFileInsideFolder(Path root, String key) {
String folder = folders().stream().filter(candidate -> key.startsWith(candidate + "/")).findFirst().orElse(null); String folder = folders().stream().filter(candidate -> key.startsWith(candidate + "/")).findFirst().orElse(null);
if (folder == null) { if (folder == null) {
return null; return null;
@@ -87,8 +88,12 @@ public record SnippetFolders(String legacy, List<String> namespaced) {
try { try {
Path file = root.resolve(key + FILE_SUFFIX).normalize(); Path file = root.resolve(key + FILE_SUFFIX).normalize();
return file.startsWith(root.resolve(folder).normalize()) ? file : null; Path folderPath = root.resolve(folder).normalize();
} catch (InvalidPathException ignored) { if (!file.startsWith(folderPath) || !Files.isRegularFile(file)) {
return null;
}
return file.toRealPath().startsWith(folderPath.toRealPath()) ? file : null;
} catch (InvalidPathException | IOException ignored) {
return null; return null;
} }
} }
@@ -39,6 +39,7 @@ import java.util.Map;
public class SchemaBuilder { public class SchemaBuilder {
static final String SYMBOL_LIMIT__N = "*"; static final String SYMBOL_LIMIT__N = "*";
static final String SYMBOL_TYPE__N = ""; static final String SYMBOL_TYPE__N = "";
private static final String REGEX_SYNTAX_CHARACTERS = "\\^$.*+?()[]{}|";
final KMap<String, JSONObject> definitions; final KMap<String, JSONObject> definitions;
final KList<String> warnings; final KList<String> warnings;
final IrisData data; final IrisData data;
@@ -139,18 +140,29 @@ public class SchemaBuilder {
} }
} }
private String snippetPattern(String snippetType) { static String snippetPattern(String snippetType, List<String> namespacedFolders) {
List<String> namespacedFolders = data.getNamespacedSnippetFolders(snippetType); String legacyFolder = escapeRegex("snippet/" + snippetType);
if (namespacedFolders.isEmpty()) { if (namespacedFolders.isEmpty()) {
return "^snippet/" + snippetType + "/"; return "^" + legacyFolder + "/";
} }
List<String> folders = new ArrayList<>(); List<String> folders = new ArrayList<>();
folders.add("snippet/" + snippetType); folders.add(legacyFolder);
folders.addAll(namespacedFolders); namespacedFolders.stream().map(SchemaBuilder::escapeRegex).forEach(folders::add);
return "^(?:" + String.join("|", folders) + ")/"; return "^(?:" + String.join("|", folders) + ")/";
} }
private static String escapeRegex(String literal) {
StringBuilder escaped = new StringBuilder(literal.length());
for (char character : literal.toCharArray()) {
if (REGEX_SYNTAX_CHARACTERS.indexOf(character) >= 0) {
escaped.append('\\');
}
escaped.append(character);
}
return escaped.toString();
}
JSONObject buildSnippet(JSONObject prop, Class<?> type) { JSONObject buildSnippet(JSONObject prop, Class<?> type) {
Snippet snippet = type.getDeclaredAnnotation(Snippet.class); Snippet snippet = type.getDeclaredAnnotation(Snippet.class);
if (snippet == null) return prop; if (snippet == null) return prop;
@@ -169,7 +181,7 @@ public class SchemaBuilder {
enumObj.put("enum", snl); enumObj.put("enum", snl);
JSONObject patternObj = new JSONObject(); JSONObject patternObj = new JSONObject();
patternObj.put("type", "string"); patternObj.put("type", "string");
patternObj.put("pattern", snippetPattern(snippet.value())); patternObj.put("pattern", snippetPattern(snippet.value(), data.getNamespacedSnippetFolders(snippet.value())));
JSONArray snippetAlt = new JSONArray(); JSONArray snippetAlt = new JSONArray();
snippetAlt.put(enumObj); snippetAlt.put(enumObj);
snippetAlt.put(patternObj); snippetAlt.put(patternObj);
@@ -11,6 +11,7 @@ import art.arcane.iris.generation.hydrology.plan.HydrologySettings;
import art.arcane.iris.generation.noise.IrisGeneratorStyle; import art.arcane.iris.generation.noise.IrisGeneratorStyle;
import art.arcane.iris.generation.terrain.IrisMaterialPalette; import art.arcane.iris.generation.terrain.IrisMaterialPalette;
import art.arcane.iris.pack.loading.IrisData; import art.arcane.iris.pack.loading.IrisData;
import art.arcane.iris.pack.loading.PackSnippets;
import art.arcane.iris.testsupport.CompatTestPlatform; import art.arcane.iris.testsupport.CompatTestPlatform;
import art.arcane.volmlib.util.json.JSONObject; import art.arcane.volmlib.util.json.JSONObject;
import com.google.gson.Gson; import com.google.gson.Gson;
@@ -362,7 +363,7 @@ public class PackHydrologyValidatorTest {
{"zones": {"swamp": {"min": 0.7, "max": 1}, "desert": {"minimum": 0.1}}} {"zones": {"swamp": {"min": 0.7, "max": 1}, "desert": {"minimum": 0.1}}}
"""); """);
PackHydrologyValidator.warnUnknownKeys("root", written, NamedZones.class, temporaryFolder.getRoot(), warnings); PackHydrologyValidator.warnUnknownKeys("root", written, NamedZones.class, new PackSnippets(temporaryFolder.getRoot()), warnings);
assertContains(warnings, "root.zones.desert.minimum is not a known key"); assertContains(warnings, "root.zones.desert.minimum is not a known key");
assertEquals(warnings.toString(), 1, warnings.size()); assertEquals(warnings.toString(), 1, warnings.size());
@@ -467,7 +468,7 @@ public class PackHydrologyValidatorTest {
"""); """);
List<String> warnings = new ArrayList<>(); List<String> warnings = new ArrayList<>();
PackHydrologyValidator.warnUnknownKeys("style", "snippet/style/loop", IrisGeneratorStyle.class, pack, warnings); PackHydrologyValidator.warnUnknownKeys("style", "snippet/style/loop", IrisGeneratorStyle.class, new PackSnippets(pack), warnings);
assertContains(warnings, "style (snippet/style/loop).fractures is not a known key"); assertContains(warnings, "style (snippet/style/loop).fractures is not a known key");
assertEquals(warnings.toString(), 1, warnings.size()); assertEquals(warnings.toString(), 1, warnings.size());
@@ -498,7 +499,7 @@ public class PackHydrologyValidatorTest {
List<String> warnings = new ArrayList<>(); List<String> warnings = new ArrayList<>();
JSONObject written = new JSONObject("{\"tiers\": {\"name\": \"stream\"}, \"fluids\": {\"elementData\": 1}}"); JSONObject written = new JSONObject("{\"tiers\": {\"name\": \"stream\"}, \"fluids\": {\"elementData\": 1}}");
PackHydrologyValidator.warnUnknownKeys("root", written, IrisHydrology.class, temporaryFolder.getRoot(), warnings); PackHydrologyValidator.warnUnknownKeys("root", written, IrisHydrology.class, new PackSnippets(temporaryFolder.getRoot()), warnings);
assertEquals(List.of(), warnings); assertEquals(List.of(), warnings);
} }
@@ -125,6 +125,22 @@ public class IrisDataSnippetTest {
assertNull(rateOf("\"snippet/rate/../duration/fast\"")); 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 @Test
public void missingSnippetYieldsNull() throws IOException { public void missingSnippetYieldsNull() throws IOException {
write("snippet/rate/other.json", "{\"amount\":1}"); write("snippet/rate/other.json", "{\"amount\":1}");
@@ -240,6 +256,12 @@ public class IrisDataSnippetTest {
Files.writeString(file, content); 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) { private static List<Integer> amountsOf(List<IrisRate> rates) {
assertNotNull(rates); assertNotNull(rates);
List<Integer> amounts = new ArrayList<>(); List<Integer> amounts = new ArrayList<>();
@@ -0,0 +1,35 @@
package art.arcane.iris.pack.loading;
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.util.List;
import static org.junit.Assert.assertEquals;
public class PackSnippetsTest {
@Rule
public final TemporaryFolder temporary = new TemporaryFolder();
@Test
public void foldersOfATypeAreDiscoveredOncePerInstance() throws IOException {
File pack = temporary.newFolder("pack");
createFolder(pack, "snippet/iris/spawn/rate");
PackSnippets snippets = new PackSnippets(pack);
assertEquals(List.of("snippet/iris/spawn/rate"), snippets.folders("rate").namespaced());
createFolder(pack, "snippet/iris/creatures/rate");
assertEquals(List.of("snippet/iris/spawn/rate"), snippets.folders("rate").namespaced());
assertEquals(List.of("snippet/iris/creatures/rate", "snippet/iris/spawn/rate"),
new PackSnippets(pack).folders("rate").namespaced());
}
private static void createFolder(File pack, String relative) throws IOException {
Files.createDirectories(pack.toPath().resolve(relative));
}
}
@@ -0,0 +1,36 @@
package art.arcane.iris.pack.schema;
import org.junit.Test;
import java.util.List;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class SchemaBuilderSnippetPatternTest {
@Test
public void legacyOnlyPatternKeepsItsPlainForm() {
assertEquals("^snippet/rate/", SchemaBuilder.snippetPattern("rate", List.of()));
}
@Test
public void dotInAGroupFolderMatchesOnlyADot() {
String pattern = SchemaBuilder.snippetPattern("rate", List.of("snippet/iris/my.group/rate"));
assertEquals("^(?:snippet/rate|snippet/iris/my\\.group/rate)/", pattern);
assertTrue(Pattern.compile(pattern).matcher("snippet/iris/my.group/rate/fast").find());
assertFalse(Pattern.compile(pattern).matcher("snippet/iris/myXgroup/rate/fast").find());
}
@Test
public void everyRegexSyntaxCharacterIsEscapedOnItsOwn() {
String folder = "snippet/iris/a^$\\.*+?()[]{}|b/rate";
String pattern = SchemaBuilder.snippetPattern("rate", List.of(folder));
assertEquals("^(?:snippet/rate|snippet/iris/a\\^\\$\\\\\\.\\*\\+\\?\\(\\)\\[\\]\\{\\}\\|b/rate)/", pattern);
assertTrue(Pattern.compile(pattern).matcher(folder + "/fast").find());
}
}