PackResources.idOf: the id a pack gives the resource its files name by a key (ResourceId.ofPackKey)

This commit is contained in:
piexel committed 2026-10-10 18:02:08 +02:00
1 parent d2d746734f
commit d17a017418
5 files changed
+34 -2

No files matched your search

@@ -35,6 +35,15 @@ public interface PackResources {
*/
List<ResourceId> ids(Class<?> type);
/** The id of the resource the pack's files name by {@code key} (the file path inside the kind's folder, without
* {@code .json}), such as {@code overworld:dungeon/chest} for {@code dungeon/chest}; see
* {@link ResourceId#ofPackKey}. Settings that name a resource, such as a {@link com.volmit.config.ResourceRef},
* hold such a key.
*/
default ResourceId idOf(String key) {
return ResourceId.ofPackKey(packId().namespace(), key);
}
default <T> T require(ResourceKey<T> key) {
return find(key).orElseThrow(() -> new NoSuchElementException("Missing resource: " + key.id()));
}
@@ -1,5 +1,6 @@
package com.volmit.resource;
import java.util.Locale;
import java.util.Objects;
import java.util.regex.Pattern;
@@ -7,6 +8,8 @@ import java.util.regex.Pattern;
public record ResourceId(String namespace, String path) implements Comparable<ResourceId> {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+");
private static final Pattern NOT_PATH = Pattern.compile("[^a-z0-9_./-]");
private static final String PATH_REPLACEMENT = "_";
public ResourceId {
Objects.requireNonNull(namespace, "namespace");
@@ -28,6 +31,17 @@ public record ResourceId(String namespace, String path) implements Comparable<Re
return new ResourceId(value.substring(0, separator), value.substring(separator + 1));
}
/**
* The id a pack gives the resource its files name by {@code key}, such as {@code dungeon/chest} for
* {@code loot/dungeon/chest.json}: the pack's namespace and the key as the path, lower-cased, with every
* character outside {@code [a-z0-9_./-]} replaced by {@code _}. Keys that differ only in such characters share
* an id.
*/
public static ResourceId ofPackKey(String namespace, String key) {
Objects.requireNonNull(key, "key");
return new ResourceId(namespace, NOT_PATH.matcher(key.toLowerCase(Locale.ROOT)).replaceAll(PATH_REPLACEMENT));
}
@Override
public String toString() { return namespace + ":" + path; }