Skip to content

Commit

Permalink
Add a way to apply actions
Browse files Browse the repository at this point in the history
Signed-off-by: TheSilkMiner <thesilkminer@outlook.com>
  • Loading branch information
TheSilkMiner authored and jaredlll08 committed Feb 27, 2022
1 parent 3a8a715 commit 7f393fc
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
@@ -1,5 +1,6 @@
package com.blamejared.crafttweaker.api.zencode.scriptrun;

import com.blamejared.crafttweaker.api.action.base.IAction;
import org.openzen.zencode.shared.SourceFile;

import java.util.List;
Expand All @@ -12,4 +13,6 @@ public interface IScriptRunManager {

IScriptRunInfo currentRunInfo();

void applyAction(final IAction action);

}
@@ -1,6 +1,8 @@
package com.blamejared.crafttweaker.impl.script.scriptrun;

import com.blamejared.crafttweaker.api.CraftTweakerAPI;
import com.blamejared.crafttweaker.api.action.base.IAction;
import com.blamejared.crafttweaker.api.action.base.IRuntimeAction;
import com.blamejared.crafttweaker.api.zencode.IPreprocessor;
import com.blamejared.crafttweaker.api.zencode.IScriptLoader;
import com.blamejared.crafttweaker.api.zencode.scriptrun.IScriptFile;
Expand Down Expand Up @@ -78,6 +80,21 @@ public IScriptRunInfo currentRunInfo() {
return Objects.requireNonNull(this.currentRunInfo, "Unable to get current run info outside a script run");
}

@Override
public void applyAction(final IAction action) {

if(this.currentRunInfo == null) {
this.applyActionOutsideRun(action);
return;
}

if(!(action instanceof IRuntimeAction) && !this.currentRunInfo.isFirstRun()) {
return;
}

this.applyActionInRun(action);
}

private List<Path> lookupScriptFiles() {

try {
Expand Down Expand Up @@ -122,4 +139,44 @@ private void attemptRunStop() {
this.currentRunInfo = null;
}

private void applyActionOutsideRun(@SuppressWarnings("unused") final IAction action) {

// TODO("Should this be supported? Custom IAction impl if so?")
throw new UnsupportedOperationException("Unable to apply an action outside of a script run");
}

private void applyActionInRun(final IAction action) {

final RunInfo info = Objects.requireNonNull(this.currentRunInfo);

try {

if(!action.shouldApplyOn(info.loadSource())) {
return;
}

if(!action.validate(CraftTweakerAPI.LOGGER)) {
info.enqueueAction(action, false);
return;
}

CraftTweakerAPI.LOGGER.info(this.makeDescription(action));
action.apply();
info.enqueueAction(action, true);

} catch(final Exception e) {
CraftTweakerAPI.LOGGER.error("Unable to run action due to an error", e);
}
}

private String makeDescription(final IAction action) {

final String description = action.describe();
if(description == null || description.isEmpty()) {
return "Applying unknown action '" + action + "': tell the mod author to properly implement describe";
}

return description;
}

}

0 comments on commit 7f393fc

Please sign in to comment.