This repository has been archived on 2023-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
ScriptCraft/scriptcraft/src/main/java/com/thebrokenrail/scriptcraft/core/quickjs/QuickJSModules.java

93 lines
3.4 KiB
Java

package com.thebrokenrail.scriptcraft.core.quickjs;
import com.thebrokenrail.scriptcraft.core.ScriptCraftCore;
import com.thebrokenrail.scriptcraft.core.util.ScriptCraftEntryPoint;
import net.fabricmc.loader.api.FabricLoader;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
@SuppressWarnings("unused")
public class QuickJSModules {
private static boolean isDirectory(String data, String path, Class<?> clazz) {
String[] lines = data.split("\n");
for (String line : lines) {
InputStream stream = clazz.getResourceAsStream(path + File.separator + line);
return stream != null;
}
return false;
}
public static String loadModule(String name) {
List<ScriptCraftEntryPoint> mods = FabricLoader.getInstance().getEntrypoints(ScriptCraftCore.NAMESPACE, ScriptCraftEntryPoint.class);
for (ScriptCraftEntryPoint mod : mods) {
//noinspection CatchMayIgnoreException
try {
String path = File.separator + ScriptCraftCore.NAMESPACE + File.separator + name;
InputStream stream = mod.getClass().getResourceAsStream(path);
if (stream != null) {
StringBuilder textBuilder = new StringBuilder();
try (Reader reader = new BufferedReader(new InputStreamReader(stream))) {
int c;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
stream.close();
String data = textBuilder.toString();
return isDirectory(data, path, mod.getClass()) ? null : data;
}
} catch (IOException e) {
}
}
return null;
}
private static final String[] SUPPORTED_EXTENSIONS;
static {
final String[] supportedExtensions = new String[]{"", ".js", ".json", ".mjs"};
SUPPORTED_EXTENSIONS = new String[supportedExtensions.length * 2];
for (int i = 0; i < supportedExtensions.length; i++) {
SUPPORTED_EXTENSIONS[i + supportedExtensions.length] = File.separator + "index" + supportedExtensions[i];
SUPPORTED_EXTENSIONS[i] = supportedExtensions[i];
}
}
public static String normalizeModule(String baseName, String name) {
String normalizedPath;
baseName = baseName.replaceAll("/", File.separator);
name = name.replaceAll("/", File.separator);
if (name.startsWith(".")) {
Path parentPath = Paths.get(baseName).getParent();
if (parentPath == null) {
parentPath = Paths.get(File.separator);
}
normalizedPath = Paths.get(parentPath.toString(), name).normalize().toString();
if (normalizedPath.charAt(0) == File.separatorChar) {
normalizedPath = normalizedPath.substring(1);
}
} else {
normalizedPath = name;
}
for (String extension : SUPPORTED_EXTENSIONS) {
if (loadModule(normalizedPath + extension) != null) {
return normalizedPath + extension;
}
}
return normalizedPath;
}
}