Respackopts/src/main/java/io/gitlab/jfronny/respackopts/filters/util/FileRpoSearchProvider.java

54 lines
2.2 KiB
Java

package io.gitlab.jfronny.respackopts.filters.util;
import io.gitlab.jfronny.libjf.ResourcePath;
import io.gitlab.jfronny.respackopts.Respackopts;
import io.gitlab.jfronny.respackopts.gson.AttachmentHolder;
import io.gitlab.jfronny.respackopts.model.FileRpo;
import io.gitlab.jfronny.respackopts.model.cache.CachedPackState;
import io.gitlab.jfronny.respackopts.util.MetaCache;
import net.minecraft.resource.InputSupplier;
import net.minecraft.resource.ResourcePack;
import java.io.*;
import java.util.Map;
public class FileRpoSearchProvider {
public static boolean isRpo(String fileName) {
return fileName.endsWith(Respackopts.FILE_EXTENSION);
}
public static <T> T modifyWithRpo(String fileName, ResourcePack pack, Action<T> action, T defaultValue) {
if (isRpo(fileName)) return defaultValue;
CachedPackState state = MetaCache.getState(MetaCache.getKeyByPack(pack));
Map<String, FileRpo> rpoCache = state.cachedFileRPOs();
String rpoPathS = fileName + Respackopts.FILE_EXTENSION;
if (rpoCache.containsKey(rpoPathS)) return action.run(rpoCache.get(rpoPathS));
ResourcePath rpoPath = null;
InputSupplier<InputStream> is;
if (fileName.contains("/")) {
try {
rpoPath = new ResourcePath(rpoPathS);
is = pack.open(rpoPath.getType(), rpoPath.getId());
} catch (Throwable e) {
Respackopts.LOGGER.error("Could not check file filter status", e);
return defaultValue;
}
} else is = pack.openRoot(rpoPathS);
if (is == null) return defaultValue;
try (Reader w = new InputStreamReader(is.get())) {
FileRpo frp = AttachmentHolder.deserialize(state.metadata().version, w, FileRpo.class);
frp.path = rpoPathS;
rpoCache.put(rpoPathS, frp);
return action.run(frp);
}
catch (Exception e) {
Respackopts.LOGGER.error("Could not get replacement for " + (rpoPath == null ? fileName : rpoPath.getName()) + " in " + pack.getName(), e);
return defaultValue;
}
}
public interface Action<T> {
T run(FileRpo rpo);
}
}