semi-auto cleanup

This commit is contained in:
gnembon committed 2023-02-04 13:26:21 +01:00
1 parent cad80f82c6
commit 8f61271606
99 files changed
+11463 -8007

No files matched your search

@@ -59,35 +59,38 @@ public class CarpetScriptServer extends ScriptServer
//make static for now, but will change that later:
public static final Logger LOG = LoggerFactory.getLogger("Scarpet");
public final MinecraftServer server;
public CarpetScriptHost globalHost;
public Map<String, CarpetScriptHost> modules;
public Set<String> unloadableModules;
public CarpetScriptHost globalHost;
public Map<String, CarpetScriptHost> modules;
public Set<String> unloadableModules;
public long tickStart;
public boolean stopAll;
public int tickDepth;
private Set<String> holyMoly;
public CarpetEventServer events;
private Set<String> holyMoly;
public CarpetEventServer events;
private static final List<Module> bundledModuleData = new ArrayList<>();
private static final List<Module> ruleModuleData = new ArrayList<>();
/**
* Registers a Scarpet App to be always available under the {@code /script load} list.
* @see Module#fromJarPath(String, String, boolean)
*
*
* @param app The {@link Module} of the app
* @see Module#fromJarPath(String, String, boolean)
*/
public static void registerBuiltInApp(Module app) {
public static void registerBuiltInApp(final Module app)
{
bundledModuleData.add(app);
}
/**
* Registers a Scarpet App to be used as a Rule App (to be controlled with the value of a Carpet rule).
* Libraries should be registered with {@link #registerBuiltInScript(BundledModule)} instead
* @see Module#fromJarPath(String, String, boolean)
*
*
* @param app The {@link Module} of the app.
* @see Module#fromJarPath(String, String, boolean)
*/
public static void registerSettingsApp(Module app) {
public static void registerSettingsApp(final Module app)
{
ruleModuleData.add(app);
}
@@ -105,7 +108,7 @@ public class CarpetScriptServer extends ScriptServer
registerBuiltInApp(Module.carpetNative("distance_beta", false));
}
public CarpetScriptServer(MinecraftServer server)
public CarpetScriptServer(final MinecraftServer server)
{
this.server = server;
init();
@@ -126,13 +129,14 @@ public class CarpetScriptServer extends ScriptServer
{
CarpetServer.settingsManager.initializeScarpetRules();
CarpetServer.extensions.forEach(e -> {
if (e.extensionSettingsManager() != null) {
if (e.extensionSettingsManager() != null)
{
e.extensionSettingsManager().initializeScarpetRules();
}
});
if (CarpetSettings.scriptsAutoload)
{
for (String moduleName: listAvailableModules(false))
for (final String moduleName : listAvailableModules(false))
{
addScriptHost(server.createCommandSourceStack(), moduleName, null, true, true, false, null);
}
@@ -140,40 +144,53 @@ public class CarpetScriptServer extends ScriptServer
CarpetEventServer.Event.START.onTick();
}
public Module getModule(String name, boolean allowLibraries)
public Module getModule(final String name, final boolean allowLibraries)
{
try {
Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
if (!Files.exists(folder))
try
{
final Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
if (!Files.exists(folder))
{
Files.createDirectories(folder);
try (Stream<Path> folderLister = Files.list(folder)) {
Optional<Path> scriptPath = folderLister
.filter(script ->
script.getFileName().toString().equalsIgnoreCase(name + ".sc") ||
(allowLibraries && script.getFileName().toString().equalsIgnoreCase(name+".scl"))
).findFirst();
}
try (final Stream<Path> folderLister = Files.list(folder))
{
final Optional<Path> scriptPath = folderLister
.filter(script ->
script.getFileName().toString().equalsIgnoreCase(name + ".sc") ||
(allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl"))
).findFirst();
if (scriptPath.isPresent())
{
return Module.fromPath(scriptPath.get());
}
}
if (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT)
{
Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts");
if (!Files.exists(globalFolder))
final Path globalFolder = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts");
if (!Files.exists(globalFolder))
{
Files.createDirectories(globalFolder);
try (Stream<Path> folderWalker = Files.walk(globalFolder)) {
Optional<Path> scriptPath = folderWalker
}
try (final Stream<Path> folderWalker = Files.walk(globalFolder))
{
final Optional<Path> scriptPath = folderWalker
.filter(script -> script.getFileName().toString().equalsIgnoreCase(name + ".sc") ||
(allowLibraries && script.getFileName().toString().equalsIgnoreCase(name + ".scl")))
.findFirst();
if (scriptPath.isPresent())
{
return Module.fromPath(scriptPath.get());
}
}
}
} catch (IOException e) {
}
catch (final IOException e)
{
CarpetSettings.LOG.error("Exception while loading the app: ", e);
}
for (Module moduleData : bundledModuleData)
for (final Module moduleData : bundledModuleData)
{
if (moduleData.name().equalsIgnoreCase(name) && (allowLibraries || !moduleData.library()))
{
@@ -182,10 +199,10 @@ public class CarpetScriptServer extends ScriptServer
}
return null;
}
public Module getRuleModule(String name)
public Module getRuleModule(final String name)
{
for (Module moduleData : ruleModuleData)
for (final Module moduleData : ruleModuleData)
{
if (moduleData.name().equalsIgnoreCase(name))
{
@@ -195,101 +212,116 @@ public class CarpetScriptServer extends ScriptServer
return null;
}
public List<String> listAvailableModules(boolean includeBuiltIns)
public List<String> listAvailableModules(final boolean includeBuiltIns)
{
List<String> moduleNames = new ArrayList<>();
final List<String> moduleNames = new ArrayList<>();
if (includeBuiltIns)
{
for (Module mi : bundledModuleData)
for (final Module mi : bundledModuleData)
{
if (!mi.library() && !mi.name().endsWith("_beta")) moduleNames.add(mi.name());
if (!mi.library() && !mi.name().endsWith("_beta"))
{
moduleNames.add(mi.name());
}
}
}
try {
Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
if (!Files.exists(worldScripts))
try
{
final Path worldScripts = server.getWorldPath(LevelResource.ROOT).resolve("scripts");
if (!Files.exists(worldScripts))
{
Files.createDirectories(worldScripts);
try (Stream<Path> folderLister = Files.list(worldScripts)) {
}
try (final Stream<Path> folderLister = Files.list(worldScripts))
{
folderLister
.filter(f -> f.toString().endsWith(".sc"))
.forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$","").toLowerCase(Locale.ROOT)));
.filter(f -> f.toString().endsWith(".sc"))
.forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$", "").toLowerCase(Locale.ROOT)));
}
if (includeBuiltIns && (FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT))
{
Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts");
final Path globalScripts = FabricLoader.getInstance().getConfigDir().resolve("carpet/scripts");
if (!Files.exists(globalScripts))
{
Files.createDirectories(globalScripts);
try (Stream<Path> folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS)) {
}
try (final Stream<Path> folderWalker = Files.walk(globalScripts, FileVisitOption.FOLLOW_LINKS))
{
folderWalker
.filter(f -> f.toString().endsWith(".sc"))
.forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$","").toLowerCase(Locale.ROOT)));
.filter(f -> f.toString().endsWith(".sc"))
.forEach(f -> moduleNames.add(f.getFileName().toString().replaceFirst("\\.sc$", "").toLowerCase(Locale.ROOT)));
}
}
} catch (IOException e) {
}
catch (final IOException e)
{
CarpetSettings.LOG.error("Exception while searching for apps: ", e);
}
return moduleNames;
}
public CarpetScriptHost getAppHostByName(String name)
public CarpetScriptHost getAppHostByName(final String name)
{
if (name == null)
return globalHost;
return modules.get(name);
return name == null ? globalHost : modules.get(name);
}
public boolean addScriptHost(CommandSourceStack source, String name, Predicate<CommandSourceStack> commandValidator,
boolean perPlayer, boolean autoload, boolean isRuleApp, AppStoreManager.StoreNode installer)
public boolean addScriptHost(final CommandSourceStack source, String name, Predicate<CommandSourceStack> commandValidator,
final boolean perPlayer, final boolean autoload, final boolean isRuleApp, final AppStoreManager.StoreNode installer)
{
CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet load", CarpetProfiler.TYPE.GENERAL);
if (commandValidator == null) commandValidator = p -> true;
long start = System.nanoTime();
final CarpetProfiler.ProfilerToken currentSection = CarpetProfiler.start_section(null, "Scarpet load", CarpetProfiler.TYPE.GENERAL);
if (commandValidator == null)
{
commandValidator = p -> true;
}
final long start = System.nanoTime();
name = name.toLowerCase(Locale.ROOT);
boolean reload = false;
if (modules.containsKey(name))
{
if (isRuleApp) return false;
if (isRuleApp)
{
return false;
}
removeScriptHost(source, name, false, isRuleApp);
reload = true;
}
Module module = isRuleApp ? getRuleModule(name) : getModule(name, false);
final Module module = isRuleApp ? getRuleModule(name) : getModule(name, false);
if (module == null)
{
Messenger.m(source, "r Failed to add "+name+" app: App not found");
Messenger.m(source, "r Failed to add " + name + " app: App not found");
return false;
}
CarpetScriptHost newHost;
final CarpetScriptHost newHost;
try
{
newHost = CarpetScriptHost.create(this, module, perPlayer, source, commandValidator, isRuleApp, installer);
}
catch (LoadException e)
catch (final LoadException e)
{
Messenger.m(source, "r Failed to add " + name + " app" + (e.getMessage() == null ? "" : ": " + e.getMessage()));
return false;
}
// config needs to be read as we load the app since some events use that info
//if (!newHost.readConfig())
//{
// Messenger.m(source, "r Failed to add "+name+" app: invalid app config (via '__config()' function)");
// return false;
//}
modules.put(name, newHost);
if (!isRuleApp) unloadableModules.add(name);
if (!isRuleApp)
{
unloadableModules.add(name);
}
if (autoload && !newHost.persistenceRequired)
{
removeScriptHost(source, name, false, false);
return false;
}
//addEvents(source, name);
String action = (installer!=null)?(reload?"reinstalled":"installed"):(reload?"reloaded":"loaded");
final String action = (installer != null) ? (reload ? "reinstalled" : "installed") : (reload ? "reloaded" : "loaded");
String finalName = name;
Boolean isCommandAdded = newHost.addAppCommands(s -> {
if (!isRuleApp) Messenger.m(source, Messenger.c("r Failed to add app '" + finalName + "': ", s));
final String finalName = name;
final Boolean isCommandAdded = newHost.addAppCommands(s -> {
if (!isRuleApp)
{
Messenger.m(source, Messenger.c("r Failed to add app '" + finalName + "': ", s));
}
});
if (isCommandAdded == null) // error should be dispatched
{
@@ -299,17 +331,23 @@ public class CarpetScriptServer extends ScriptServer
else if (isCommandAdded)
{
CommandHelper.notifyPlayersCommandsChanged(server);
if (!isRuleApp) Messenger.m(source, "gi "+name+" app "+action+" with /"+name+" command");
if (!isRuleApp)
{
Messenger.m(source, "gi " + name + " app " + action + " with /" + name + " command");
}
}
else
{
if (!isRuleApp) Messenger.m(source, "gi "+name+" app "+action);
if (!isRuleApp)
{
Messenger.m(source, "gi " + name + " app " + action);
}
}
if (newHost.isPerUser())
{
// that will provide player hosts right at the startup
for (ServerPlayer player : source.getServer().getPlayerList().getPlayers())
for (final ServerPlayer player : source.getServer().getPlayerList().getPlayers())
{
newHost.retrieveForExecution(player.createCommandSourceStack(), player);
}
@@ -317,59 +355,76 @@ public class CarpetScriptServer extends ScriptServer
else
{
// global app - calling start now.
FunctionValue onStart = newHost.getFunction("__on_start");
if (onStart != null) newHost.callNow(onStart, Collections.emptyList());
final FunctionValue onStart = newHost.getFunction("__on_start");
if (onStart != null)
{
newHost.callNow(onStart, Collections.emptyList());
}
}
CarpetProfiler.end_current_section(currentSection);
long end = System.nanoTime();
CarpetSettings.LOG.info("App "+name+" loaded in "+(end-start)/1000000+" ms");
final long end = System.nanoTime();
CarpetSettings.LOG.info("App " + name + " loaded in " + (end - start) / 1000000 + " ms");
return true;
}
public boolean isInvalidCommandRoot(String appName)
public boolean isInvalidCommandRoot(final String appName)
{
return holyMoly.contains(appName);
}
public boolean removeScriptHost(CommandSourceStack source, String name, boolean notifySource, boolean isRuleApp)
public boolean removeScriptHost(final CommandSourceStack source, String name, final boolean notifySource, final boolean isRuleApp)
{
name = name.toLowerCase(Locale.ROOT);
if (!modules.containsKey(name) || (!isRuleApp && !unloadableModules.contains(name)))
{
if (notifySource) Messenger.m(source, "r No such app found: ", "wb " + name);
if (notifySource)
{
Messenger.m(source, "r No such app found: ", "wb " + name);
}
return false;
}
// stop all events associated with name
CarpetScriptHost host = modules.remove(name);
final CarpetScriptHost host = modules.remove(name);
events.removeAllHostEvents(host);
host.onClose();
if (host.hasCommand)
((CommandDispatcherInterface)server.getCommands().getDispatcher()).carpet$unregister(name);
if (!isRuleApp) unloadableModules.remove(name);
{
((CommandDispatcherInterface) server.getCommands().getDispatcher()).carpet$unregister(name);
}
if (!isRuleApp)
{
unloadableModules.remove(name);
}
CommandHelper.notifyPlayersCommandsChanged(server);
if (notifySource) Messenger.m(source, "gi Removed "+name+" app");
if (notifySource)
{
Messenger.m(source, "gi Removed " + name + " app");
}
return true;
}
public boolean uninstallApp(CommandSourceStack source, String name)
public boolean uninstallApp(final CommandSourceStack source, String name)
{
try
{
name = name.toLowerCase(Locale.ROOT);
Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts/trash");
if (!Files.exists(folder)) Files.createDirectories(folder);
if (!Files.exists(folder.getParent().resolve(name+".sc")))
final Path folder = server.getWorldPath(LevelResource.ROOT).resolve("scripts/trash");
if (!Files.exists(folder))
{
Files.createDirectories(folder);
}
if (!Files.exists(folder.getParent().resolve(name + ".sc")))
{
Messenger.m(source, "App doesn't exist in the world scripts folder, so can only be unloaded");
return false;
}
removeScriptHost(source, name, false, false);
Files.move(folder.getParent().resolve(name+".sc"), folder.resolve(name+".sc"), StandardCopyOption.REPLACE_EXISTING);
Messenger.m(source, "gi Removed "+name+" app");
Files.move(folder.getParent().resolve(name + ".sc"), folder.resolve(name + ".sc"), StandardCopyOption.REPLACE_EXISTING);
Messenger.m(source, "gi Removed " + name + " app");
return true;
}
catch (IOException exc)
catch (final IOException exc)
{
Messenger.m(source, "rb Failed to uninstall the app");
}
@@ -380,10 +435,13 @@ public class CarpetScriptServer extends ScriptServer
{
CarpetProfiler.ProfilerToken token;
token = CarpetProfiler.start_section(null, "Scarpet schedule", CarpetProfiler.TYPE.GENERAL);
events.handleEvents.getWhileDisabled( () -> {events.tick(); return null;});
events.handleEvents.getWhileDisabled(() -> {
events.tick();
return null;
});
CarpetProfiler.end_current_section(token);
token = CarpetProfiler.start_section(null, "Scarpet app data", CarpetProfiler.TYPE.GENERAL);
for (CarpetScriptHost host : modules.values())
for (final CarpetScriptHost host : modules.values())
{
host.tick();
}
@@ -393,14 +451,14 @@ public class CarpetScriptServer extends ScriptServer
public void onClose()
{
CarpetEventServer.Event.SHUTDOWN.onTick();
for (CarpetScriptHost host : modules.values())
for (final CarpetScriptHost host : modules.values())
{
host.onClose();
events.removeAllHostEvents(host);
}
}
public void onPlayerJoin(ServerPlayer player)
public void onPlayerJoin(final ServerPlayer player)
{
modules.values().forEach(h ->
{
@@ -410,36 +468,38 @@ public class CarpetScriptServer extends ScriptServer
{
h.retrieveOwnForExecution(player.createCommandSourceStack());
}
catch (CommandSyntaxException ignored)
catch (final CommandSyntaxException ignored)
{
}
}
});
}
private static record TransferData(boolean perUser, Predicate<CommandSourceStack> commandValidator, boolean isRuleApp)
private record TransferData(boolean perUser, Predicate<CommandSourceStack> commandValidator,
boolean isRuleApp)
{
private TransferData(CarpetScriptHost host)
private TransferData(final CarpetScriptHost host)
{
this(host.perUser, host.commandValidator, host.isRuleApp);
}
}
public void reload(MinecraftServer server)
public void reload(final MinecraftServer server)
{
Map<String, TransferData> apps = new HashMap<>();
final Map<String, TransferData> apps = new HashMap<>();
modules.forEach((s, h) -> apps.put(s, new TransferData(h)));
apps.keySet().forEach(s -> removeScriptHost(server.createCommandSourceStack(), s, false, false));
CarpetEventServer.Event.clearAllBuiltinEvents();
init();
apps.forEach((s, data) -> addScriptHost(server.createCommandSourceStack(), s,data.commandValidator, data.perUser,false, data.isRuleApp, null));
apps.forEach((s, data) -> addScriptHost(server.createCommandSourceStack(), s, data.commandValidator, data.perUser, false, data.isRuleApp, null));
}
public void reAddCommands()
{
modules.values().forEach(host -> host.addAppCommands(s -> {}));
modules.values().forEach(host -> host.addAppCommands(s -> {
}));
}
public static void parseFunctionClasses()
{
ExpressionException.prepareForDoom(); // see fc-#1172
@@ -451,7 +511,7 @@ public class CarpetScriptServer extends ScriptServer
AnnotationParser.parseFunctionClass(Loops.class);
AnnotationParser.parseFunctionClass(Sys.class);
AnnotationParser.parseFunctionClass(Threading.class);
// API
AnnotationParser.parseFunctionClass(Auxiliary.class);
AnnotationParser.parseFunctionClass(BlockIterators.class);