Merge branch 'master' into 1.16

# Conflicts:
#	src/main/java/carpet/CarpetSettings.java
#	src/main/java/carpet/script/CarpetScriptServer.java
#	src/main/java/carpet/script/bundled/Module.java
This commit is contained in:
gnembon committed 2020-06-07 01:59:15 -03:00
commit f29153c3d2
21 files changed
+601 -74

No files matched your search

@@ -13,6 +13,7 @@ import carpet.script.value.Value;
import carpet.utils.Messenger;
import net.minecraft.block.BlockState;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.command.ServerCommandSource;
import net.minecraft.entity.Entity;
import net.minecraft.server.network.ServerPlayerEntity;
@@ -53,6 +54,7 @@ import java.util.stream.Collectors;
public class CarpetEventServer
{
public final List<ScheduledCall> scheduledCalls = new LinkedList<>();
public final MinecraftServer server;
public static class Callback
{
@@ -658,8 +660,9 @@ public class CarpetEventServer
}
public CarpetEventServer()
public CarpetEventServer(MinecraftServer server)
{
this.server = server;
for (Event e: Event.values())
e.handler.callList.clear();
}
+105 -23
View File
@@ -2489,6 +2489,18 @@ public class CarpetExpression
}
public static String recognizeResource(Value value)
{
String origfile = value.getString();
String file = origfile.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9/]", "");
file = Arrays.stream(file.split("/+")).filter(s -> !s.isEmpty()).collect(Collectors.joining("/"));
if (file.isEmpty())
{
throw new InternalExpressionException("Cannot use "+origfile+" as resource name - must have some letters and numbers");
}
return file;
}
private void API_AuxiliaryAspects()
{
this.expr.addLazyFunction("sound", -1, (c, t, lv) -> {
@@ -2877,13 +2889,6 @@ public class CarpetExpression
// implmenetation should dock the task on the main thread.
});
this.expr.addLazyFunction("logger", 1, (c, t, lv) ->
{
Value res = lv.get(0).evalValue(c);
CarpetSettings.LOG.error(res.getString());
return (_c, _t) -> res; // pass through for variables
});
this.expr.addLazyFunction("run", 1, (c, t, lv) -> {
BlockPos target = ((CarpetContext)c).origin;
Vec3d posf = new Vec3d((double)target.getX()+0.5D,(double)target.getY(),(double)target.getZ()+0.5D);
@@ -3070,25 +3075,108 @@ public class CarpetExpression
return (c_, t_) -> Value.TRUE;
});
this.expr.addLazyFunction("logger", 1, (c, t, lv) ->
{
Value res = lv.get(0).evalValue(c);
CarpetSettings.LOG.error(res.getString());
return (_c, _t) -> res; // pass through for variables
});
this.expr.addLazyFunction("read_file", 2, (c, t, lv) -> {
String resource = recognizeResource(lv.get(0).evalValue(c));
String origtype = lv.get(1).evalValue(c).getString().toLowerCase(Locale.ROOT);
boolean shared = origtype.startsWith("shared_");
String type = shared ? origtype.substring(7) : origtype; //len(shared_)
if (!type.equals("raw") && !type.equals("text") && !type.equals("nbt"))
throw new InternalExpressionException("Unsupported file type: "+origtype);
Value retVal;
if (type.equals("nbt"))
{
Tag state = ((CarpetScriptHost)((CarpetContext)c).host).readFileTag(resource, shared);
if (state == null) return LazyValue.NULL;
retVal = new NBTSerializableValue(state);
}
else
{
List<String> content = ((CarpetScriptHost) ((CarpetContext) c).host).readTextResource(resource, shared);
if (content == null) return LazyValue.NULL;
retVal = ListValue.wrap(content.stream().map(StringValue::new).collect(Collectors.toList()));
}
return (cc, tt) -> retVal;
});
this.expr.addLazyFunction("delete_file", 2, (c, t, lv) -> {
String resource = recognizeResource(lv.get(0).evalValue(c));
String origtype = lv.get(1).evalValue(c).getString().toLowerCase(Locale.ROOT);
boolean shared = origtype.startsWith("shared_");
String type = shared ? origtype.substring(7) : origtype; //len(shared_)
if (!type.equals("raw") && !type.equals("text") && !type.equals("nbt"))
throw new InternalExpressionException("Unsupported file type: "+origtype);
boolean success = ((CarpetScriptHost)((CarpetContext)c).host).removeResourceFile(resource, shared, type);
return success?LazyValue.TRUE:LazyValue.FALSE;
});
this.expr.addLazyFunction("write_file", -1, (c, t, lv) -> {
if (lv.size() < 3) throw new InternalExpressionException("'write_file' requires three or more arguments");
String resource = recognizeResource(lv.get(0).evalValue(c));
String origtype = lv.get(1).evalValue(c).getString().toLowerCase(Locale.ROOT);
boolean shared = origtype.startsWith("shared_");
String type = shared ? origtype.substring(7) : origtype; //len(shared_)
if (!type.equals("raw") && !type.equals("text") && !type.equals("nbt"))
throw new InternalExpressionException("Unsupported file type: "+origtype);
boolean success;
if (type.equals("nbt"))
{
Value val = lv.get(2).evalValue(c);
NBTSerializableValue tagValue = (val instanceof NBTSerializableValue)
? (NBTSerializableValue) val
: new NBTSerializableValue(val.getString());
Tag tag = tagValue.getTag();
success = ((CarpetScriptHost)((CarpetContext)c).host).writeTagFile(tag, resource, shared);
}
else
{
List<String> data = new ArrayList<>();
if (lv.size()==3)
{
Value val = lv.get(2).evalValue(c);
if (val instanceof ListValue)
{
List<Value> lval = ((ListValue) val).getItems();
lval.forEach(v -> data.add(v.getString()));
}
else
{
data.add(val.getString());
}
}
else
{
for(int i = 2; i < lv.size(); i++)
{
data.add(lv.get(i).evalValue(c).getString());
}
}
success = ((CarpetScriptHost) ((CarpetContext) c).host).appendLogFile(resource, shared, type, data);
}
return success?LazyValue.TRUE:LazyValue.FALSE;
});
//write_file
this.expr.addLazyFunction("load_app_data", -1, (c, t, lv) ->
{
String file = null;
boolean shared = false;
if (lv.size()>0)
{
String origfile = lv.get(0).evalValue(c).getString();
file = origfile.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9/]", "");
file = Arrays.stream(file.split("/+")).filter(s -> !s.isEmpty()).collect(Collectors.joining("/"));
if (file.isEmpty())
{
throw new InternalExpressionException("Cannot use "+origfile+" as resource name - must have at least some letters and numbers");
}
file = recognizeResource(lv.get(0).evalValue(c));
if (lv.size() > 1)
{
shared = lv.get(1).evalValue(c).getBoolean();
}
}
Tag state = ((CarpetScriptHost)((CarpetContext)c).host).getGlobalState(file, shared);
Tag state = ((CarpetScriptHost)((CarpetContext)c).host).readFileTag(file, shared);
if (state == null)
return (cc, tt) -> Value.NULL;
Value retVal = new NBTSerializableValue(state);
@@ -3104,13 +3192,7 @@ public class CarpetExpression
boolean shared = false;
if (lv.size()>1)
{
String origfile = lv.get(1).evalValue(c).getString();
file = origfile.toLowerCase(Locale.ROOT).replaceAll("[^A-Za-z0-9/]", "");
file = Arrays.stream(file.split("/+")).filter(s -> !s.isEmpty()).collect(Collectors.joining("/"));
if (file.isEmpty())
{
throw new InternalExpressionException("Cannot use "+origfile+" as resource name - must have some letters and numbers");
}
file = recognizeResource(lv.get(1).evalValue(c));
if (lv.size() > 2)
{
shared = lv.get(2).evalValue(c).getBoolean();
@@ -3120,7 +3202,7 @@ public class CarpetExpression
? (NBTSerializableValue) val
: new NBTSerializableValue(val.getString());
Tag tag = tagValue.getTag();
boolean success = ((CarpetScriptHost)((CarpetContext)c).host).setGlobalState(tag, file, shared);
boolean success = ((CarpetScriptHost)((CarpetContext)c).host).writeTagFile(tag, file, shared);
return success?LazyValue.TRUE:LazyValue.FALSE;
});
@@ -323,7 +323,7 @@ public class CarpetScriptHost extends ScriptHost
{
try
{
callUDF(BlockPos.ORIGIN, CarpetServer.minecraft_server.getCommandSource(), closing, Collections.emptyList());
callUDF(BlockPos.ORIGIN, scriptServer.server.getCommandSource(), closing, Collections.emptyList());
}
catch (InvalidCallbackException ignored)
{
@@ -334,8 +334,8 @@ public class CarpetScriptHost extends ScriptHost
FunctionValue userClosing = value.getFunction("__on_close");
if (userClosing != null)
{
ServerPlayerEntity player = CarpetServer.minecraft_server.getPlayerManager().getPlayer(key);
ServerCommandSource source = (player != null)?player.getCommandSource():CarpetServer.minecraft_server.getCommandSource();
ServerPlayerEntity player = scriptServer.server.getPlayerManager().getPlayer(key);
ServerCommandSource source = (player != null)?player.getCommandSource():scriptServer.server.getCommandSource();
try
{
((CarpetScriptHost) value).callUDF(BlockPos.ORIGIN, source, userClosing, Collections.emptyList());
@@ -347,7 +347,7 @@ public class CarpetScriptHost extends ScriptHost
});
String markerName = CarpetExpression.MARKER_STRING+"_"+((getName()==null)?"":getName());
for (ServerWorld world : CarpetServer.minecraft_server.getWorlds())
for (ServerWorld world : scriptServer.server.getWorlds())
{
for (Entity e : world.getEntities(EntityType.ARMOR_STAND, (as) -> as.getScoreboardTags().contains(markerName)))
{
@@ -369,7 +369,7 @@ public class CarpetScriptHost extends ScriptHost
return Module.getData(main, null, false);
}
public Tag getGlobalState(String file, boolean isShared)
public Tag readFileTag(String file, boolean isShared)
{
if (getName() == null && !isShared) return null;
if (file != null)
@@ -379,7 +379,7 @@ public class CarpetScriptHost extends ScriptHost
return ((CarpetScriptHost)parent).globalState;
}
public boolean setGlobalState(Tag tag, String file, boolean isShared)
public boolean writeTagFile(Tag tag, String file, boolean isShared)
{
if (getName() == null && !isShared) return false; // if belongs to an app, cannot be default host.
@@ -398,6 +398,25 @@ public class CarpetScriptHost extends ScriptHost
return true;
}
public boolean removeResourceFile(String resource, boolean isShared, String type)
{
if (getName() == null && !isShared) return false; //
return Module.dropExistingFile(main, resource, type.equals("nbt")?"nbt":"txt", isShared);
}
public boolean appendLogFile(String resource, boolean isShared, String type, List<String> data)
{
if (getName() == null && !isShared) return false; // if belongs to an app, cannot be default host.
return Module.appendToTextFile(main, resource, type, isShared, data);
}
public List<String> readTextResource(String resource, boolean isShared)
{
if (getName() == null && !isShared) return null; //
return Module.listFile(main, resource, "txt", isShared);
}
public void tick()
{
if (this.saveTimeout > 0)
@@ -36,6 +36,7 @@ import static net.minecraft.server.command.CommandManager.literal;
public class CarpetScriptServer
{
//make static for now, but will change that later:
public final MinecraftServer server;
public CarpetScriptHost globalHost;
public Map<String, CarpetScriptHost> modules;
public long tickStart;
@@ -51,19 +52,20 @@ public class CarpetScriptServer
add(new BundledModule("math", true));
}};
public CarpetScriptServer()
public CarpetScriptServer(MinecraftServer server)
{
init();
}
private void init()
{
this.server = server;
ScriptHost.systemGlobals.clear();
events = new CarpetEventServer();
events = new CarpetEventServer(server);
modules = new HashMap<>();
tickStart = 0L;
stopAll = false;
holyMoly = CarpetServer.minecraft_server.getCommandManager().getDispatcher().getRoot().getChildren().stream().map(CommandNode::getName).collect(Collectors.toSet());
holyMoly = server.getCommandManager().getDispatcher().getRoot().getChildren().stream().map(CommandNode::getName).collect(Collectors.toSet());
globalHost = CarpetScriptHost.create(this, null, false, null);
}
@@ -71,10 +73,10 @@ public class CarpetScriptServer
{
if (CarpetSettings.scriptsAutoload)
{
Messenger.m(CarpetServer.minecraft_server.getCommandSource(), "Auto-loading world scarpet apps");
Messenger.m(server.getCommandSource(), "Auto-loading world scarpet apps");
for (String moduleName: listAvailableModules(false))
{
addScriptHost(CarpetServer.minecraft_server.getCommandSource(), moduleName, true, true);
addScriptHost(server.getCommandSource(), moduleName, true, true);
}
}
@@ -83,6 +85,8 @@ public class CarpetScriptServer
public Module getModule(String name, boolean allowLibraries)
{
File folder = CarpetServer.minecraft_server.getSavePath(WorldSavePath.ROOT).resolve("scripts").toFile();
File folder = server.getLevelStorage().resolveFile(
server.getLevelName(), "scripts");
File[] listOfFiles = folder.listFiles();
if (listOfFiles != null)
for (File script : listOfFiles)
@@ -117,6 +121,8 @@ public class CarpetScriptServer
}
}
File folder = CarpetServer.minecraft_server.getSavePath(WorldSavePath.ROOT).resolve("scripts").toFile();
File folder = server.getLevelStorage().resolveFile(
server.getLevelName(), "scripts");
File[] listOfFiles = folder.listFiles();
if (listOfFiles == null)
return moduleNames;
@@ -228,7 +234,7 @@ public class CarpetScriptServer
})));
}
Messenger.m(source, "gi "+hostName+" app loaded with /"+hostName+" command");
CarpetServer.minecraft_server.getCommandManager().getDispatcher().register(command);
server.getCommandManager().getDispatcher().register(command);
CarpetServer.settingsManager.notifyPlayersCommandsChanged();
}
+3 -3
View File
@@ -173,9 +173,9 @@ public class Tokenizer implements Iterator<Tokenizer.Token>
}
else if (nextChar == 't')
{
throw new ExpressionException(context, this.expression, token,
"Tab character is not supported");
//token.append('\t');
//throw new ExpressionException(context, this.expression, token,
// "Tab character is not supported");
token.append('\t');
}
else if (nextChar == 'r')
{
@@ -1,17 +1,24 @@
package carpet.script.bundled;
import carpet.CarpetServer;
import net.minecraft.nbt.PositionTracker;
import net.minecraft.nbt.Tag;
import net.minecraft.nbt.TagReaders;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FileModule extends Module
@@ -96,4 +103,44 @@ public class FileModule extends Module
if (!file.exists()) file_2.renameTo(file);
return true;
}
public static boolean appendText(File filePath, boolean addNewLines, List<String> data)
{
try
{
OutputStream out = Files.newOutputStream(filePath.toPath(), StandardOpenOption.APPEND, StandardOpenOption.CREATE);
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8)))
{
for (String line: data)
{
writer.append(line);
if (addNewLines) writer.newLine();
}
}
}
catch (IOException e)
{
return false;
}
return true;
}
public static List<String> listFileContent(File filePath)
{
try (BufferedReader reader = Files.newBufferedReader(filePath.toPath(), StandardCharsets.UTF_8)) {
List<String> result = new ArrayList<>();
for (;;) {
String line = reader.readLine();
if (line == null)
break;
result.add(line.replaceAll("[\n\r]+",""));
}
return result;
}
catch (IOException e)
{
return null;
}
}
}
@@ -6,15 +6,14 @@ import net.minecraft.util.WorldSavePath;
import java.io.File;
import java.nio.file.Files;
import static carpet.script.bundled.FileModule.read;
import static carpet.script.bundled.FileModule.write;
import java.util.List;
public abstract class Module
{
public abstract String getName();
public abstract String getCode();
public abstract boolean isLibrary();
public final static Object writeIOSync = new Object();
private static String getDescriptor(Module module, String file, boolean isShared)
{
@@ -34,18 +33,52 @@ public abstract class Module
public static Tag getData(Module module, String file, boolean isShared)
{
File dataFile = resolveResource(module, file, "nbt", isShared);
if (dataFile == null) return null;
if (!isShared && (module == null || module.getName() == null)) return null;
File dataFile = CarpetServer.minecraft_server.getSavePath(WorldSavePath.ROOT).resolve("scripts/"+getDescriptor(module, file, isShared)+".nbt").toFile();
if (!Files.exists(dataFile.toPath()) || !(dataFile.isFile())) return null;
return read(dataFile);
synchronized (writeIOSync) { return FileModule.read(dataFile); }
}
public static boolean saveData(Module module, String file, Tag globalState, boolean isShared)
{
File dataFile = resolveResource(module, file, "nbt", isShared);
if (dataFile == null) return false;
if (!isShared && (module == null || module.getName() == null)) return false;
File dataFile =CarpetServer.minecraft_server.getSavePath(WorldSavePath.ROOT).resolve("scripts/"+getDescriptor(module, file, isShared)+".nbt").toFile();
if (!Files.exists(dataFile.toPath().getParent()) && !dataFile.getParentFile().mkdirs()) return false;
return write(globalState, dataFile);
synchronized (writeIOSync) { return FileModule.write(globalState, dataFile); }
}
public static boolean appendToTextFile(Module module, String resourceName, String type, boolean isShared, List<String> message)
{
File dataFile = resolveResource(module, resourceName, "txt", isShared);
if (dataFile == null) return false;
if (!Files.exists(dataFile.toPath().getParent()) && !dataFile.getParentFile().mkdirs()) return false;
synchronized (writeIOSync) { return FileModule.appendText(dataFile, type.equals("text"), message); }
}
public static boolean dropExistingFile(Module module, String resourceName, String ext, boolean isShared)
{
File dataFile = resolveResource(module, resourceName, ext, isShared);
if (dataFile == null) return false;
synchronized (writeIOSync) { return dataFile.delete(); }
}
public static List<String> listFile(Module module, String resourceName, String ext, boolean isShared)
{
File dataFile = resolveResource(module, resourceName, ext, isShared);
if (dataFile == null) return null;
if (!dataFile.exists()) return null;
synchronized (writeIOSync) { return FileModule.listFileContent(dataFile); }
}
private static File resolveResource(Module module, String resourceName, String ext, boolean isShared)
{
if (!isShared && (module == null || module.getName() == null)) return null;
return CarpetServer.minecraft_server.getLevelStorage().resolveFile(
CarpetServer.minecraft_server.getLevelName(), "scripts/"+getDescriptor(module, resourceName, isShared)+"."+ext);
}
@Override