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

47 lines
2.0 KiB
Java

package io.gitlab.jfronny.respackopts.filters.util;
import io.gitlab.jfronny.libjf.LibJf;
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.GC_FileRpo;
import io.gitlab.jfronny.respackopts.model.cache.CacheKey;
import io.gitlab.jfronny.respackopts.model.cache.CachedPackState;
import io.gitlab.jfronny.respackopts.muscript.RespackoptsFS;
import io.gitlab.jfronny.respackopts.util.MetaCache;
import net.minecraft.resource.InputSupplier;
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, CacheKey key, RespackoptsFS fs, Action<T> action, T defaultValue) {
if (isRpo(fileName)) return defaultValue;
CachedPackState state = MetaCache.getState(key);
Map<String, FileRpo> rpoCache = state.cachedFileRPOs();
String rpoPathS = fileName + Respackopts.FILE_EXTENSION;
if (rpoCache.containsKey(rpoPathS)) return action.run(rpoCache.get(rpoPathS));
InputSupplier<InputStream> is = fs.open(rpoPathS);
if (is == null) return defaultValue;
if (state.tracker() != null) state.tracker().addDependency(fileName, rpoPathS);
try (Reader w = new InputStreamReader(is.get())) {
FileRpo frp = AttachmentHolder.attach(state.metadata().version, () -> GC_FileRpo.deserialize(w, LibJf.LENIENT_TRANSPORT));
frp.hydrate(rpoPathS);
rpoCache.put(rpoPathS, frp);
return action.run(frp);
}
catch (Exception e) {
Respackopts.LOGGER.error("Could not get replacement for " + fileName + " in " + state.displayName(), e);
return defaultValue;
}
}
public interface Action<T> {
T run(FileRpo rpo);
}
}