-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
ScriptHelper.java
245 lines (224 loc) · 10.6 KB
/
ScriptHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package com.denizenscript.denizencore.scripts;
import com.denizenscript.denizencore.utilities.CoreConfiguration;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.YamlConfiguration;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizencore.DenizenCore;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Consumer;
/**
* Reloads and retrieves information from the scripts folder.
*/
public class ScriptHelper {
public static volatile ArrayList<YamlConfiguration> _yamlScripts;
@Deprecated
public static ArrayList<YamlConfiguration> additionalScripts = new ArrayList<>();
/**
* Add additional script file references here as wanted/needed. Use like:
*
* (scripts) -> scripts.add(YamlConfiguration.load(ScriptHelper.clearComments(MY_FILENAME, MY_FILE_TEXT, true)));
*/
public static List<Consumer<List<YamlConfiguration>>> buildAdditionalScripts = new ArrayList<>();
private static void reloadFailed(Throwable ex) {
hadError = true;
Debug.echoError("Could not load scripts!");
Debug.echoError(ex);
_yamlScripts = new ArrayList<>();
}
public static void reloadScripts(boolean delayable, Consumer<Long> onFinished) {
Runnable afterLoad = () -> {
postLoad();
long midPoint = CoreUtilities.monotonicMillis();
_yamlScripts.addAll(additionalScripts);
ScriptRegistry.buildCoreYamlScriptContainers(_yamlScripts);
onFinished.accept(midPoint);
};
if (delayable) {
DenizenCore.runAsync(() -> {
try {
_yamlScripts = buildScriptList();
DenizenCore.runOnMainThread(afterLoad);
}
catch (Throwable ex) {
reloadFailed(ex);
}
});
}
else {
try {
_yamlScripts = buildScriptList();
afterLoad.run();
}
catch (Throwable ex) {
reloadFailed(ex);
}
}
}
private static volatile boolean hadError = false; // Note: can be called async
public static boolean hadError() {
return hadError;
}
public static void resetError() {
hadError = false;
}
public static void setHadError() {
hadError = true;
}
private static volatile HashMap<String, String> scriptSources = new HashMap<>();
private static volatile HashMap<String, String> scriptOriginalNames = new HashMap<>();
private static volatile HashMap<String, String> scriptSourcesInprogress;
private static volatile HashMap<String, String> scriptOriginalNamesInprogress;
public static String getSource(String script) {
return scriptSources.get(CoreUtilities.toLowerCase(script));
}
public static String getOriginalName(String script) {
return scriptOriginalNames.get(CoreUtilities.toLowerCase(script));
}
public static String clearComments(String filename, String input, boolean trackSources) {
StringBuilder result = new StringBuilder(input.length());
String[] lines = input.replace("\t", " ").replace("\r", "").split("\n");
boolean hasAnyScript = false;
for (int lineNum = 0; lineNum < lines.length; lineNum++) {
String trimmedLine = lines[lineNum].trim();
String trimStart = lines[lineNum].replaceAll("^[\\s]+", "");
if (trackSources && !trimmedLine.startsWith("#") && trimStart.length() == lines[lineNum].length() && trimmedLine.endsWith(":") && trimmedLine.length() > 1) {
String name = trimmedLine.substring(0, trimmedLine.length() - 1).replace('\"', '\'').replace("'", "");
scriptSourcesInprogress.put(CoreUtilities.toLowerCase(name), filename);
scriptOriginalNamesInprogress.put(CoreUtilities.toLowerCase(name), name);
result.append(CoreUtilities.toUpperCase(name)).append(":\n");
hasAnyScript = true;
}
else if (!trimmedLine.startsWith("#")) {
if (trackSources && !hasAnyScript && trimmedLine.endsWith(":")) {
Debug.echoError("Script '<Y>" + filename + "<W>' is broken: script container title has spaces in front.");
hasAnyScript = true;
}
String curLine = lines[lineNum].replace('\0', ' ');
boolean endsColon = trimmedLine.endsWith(":");
boolean startsDash = trimmedLine.startsWith("-");
if (!endsColon && startsDash) {
curLine = curLine.replace(": ", "<&co> ");
curLine = curLine.replace("#", "<&ns>");
}
else if (endsColon && !startsDash) {
if (curLine.contains(".")) {
curLine = CoreUtilities.replace(curLine, "&", "&");
curLine = CoreUtilities.replace(curLine, ".", "&dot");
}
}
else if (!startsDash && (trimmedLine.contains(": &") || trimmedLine.contains(": *") || trimmedLine.contains(": !"))) {
int colon = curLine.indexOf(':');
curLine = curLine.substring(0, colon) + ": \"" + curLine.substring(colon + 2).replace("\"", "<&dq>") + "\"";
}
else if (!endsColon) {
int colon = curLine.indexOf(':');
curLine = curLine.substring(0, colon + 1) + CoreUtilities.replace(curLine.substring(colon + 1), ":", "<&co>");
}
if (trimmedLine.startsWith("- ") && !trimmedLine.startsWith("- \"") && !trimmedLine.startsWith("- '")) {
int dashIndex = curLine.indexOf('-');
curLine = curLine.substring(0, dashIndex + 1) + " " + ScriptBuilder.LINE_PREFIX_CHAR + (lineNum + 1) + ScriptBuilder.LINE_PREFIX_CHAR + curLine.substring(dashIndex + 1);
}
result.append(curLine).append("\n");
}
else {
result.append("\n");
}
}
result.append("\n");
return result.toString();
}
public static String convertStreamToString(InputStream is) {
return convertStreamToString(is, false);
}
public static String convertStreamToString(InputStream is, boolean defaultUTF8) {
Scanner s;
if (CoreConfiguration.scriptEncoding == null && !defaultUTF8) {
s = new Scanner(is);
}
else {
s = new Scanner(new InputStreamReader(is, CoreConfiguration.scriptEncoding == null ? StandardCharsets.UTF_8.newDecoder() : CoreConfiguration.scriptEncoding));
}
s.useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
public static YamlConfiguration loadConfig(String filename, InputStream resource) throws IOException { // Note: can be called async
try {
String script = clearComments(filename, convertStreamToString(resource, filename.endsWith(".dsc")), true);
return YamlConfiguration.load(script);
}
finally {
resource.close();
}
}
private static ArrayList<YamlConfiguration> buildScriptList() { // Note: can be called async
scriptSourcesInprogress = new HashMap<>();
scriptOriginalNamesInprogress = new HashMap<>();
try {
File file = DenizenCore.implementation.getScriptFolder();
// Check if the directory exists
if (!file.exists()) {
Debug.echoError("No script folder found, please create one.");
hadError = true;
return new ArrayList<>();
}
// Get files using script directory
List<File> files = CoreUtilities.listDScriptFiles(file);
if (files.size() > 0) {
ArrayList<YamlConfiguration> outList = new ArrayList<>();
YamlConfiguration yaml;
for (File f : files) {
String fileName = f.getAbsolutePath().substring(file.getAbsolutePath().length());
if (CoreConfiguration.debugLoadingInfo) {
Debug.log("Processing '" + fileName + "'... ");
}
try {
yaml = loadConfig(f.getAbsolutePath(), new FileInputStream(f));
String saved = yaml != null ? yaml.saveToString(false) : null;
if (saved != null && saved.length() > 0) {
outList.add(yaml);
}
else {
Debug.echoError("Error parsing '<Y>" + fileName + "<W>'! This script has been skipped. No internal error - is the file empty?");
hadError = true;
}
}
catch (Exception e) {
Debug.echoError("Error parsing '<Y>" + fileName + "<W>'!");
hadError = true;
Debug.echoError(e);
}
}
for (Consumer<List<YamlConfiguration>> additional : buildAdditionalScripts) {
try {
additional.accept(outList);
}
catch (Exception ex) {
Debug.echoError("Error parsing additional script!");
hadError = true;
Debug.echoError(ex);
}
}
if (CoreConfiguration.debugLoadingInfo) {
Debug.echoApproval("All scripts loaded!");
}
return outList;
}
else {
Debug.log("No scripts in /plugins/Denizen/scripts/ to load!");
hadError = true;
}
}
catch (Exception e) {
Debug.echoError("No script folder found in " + DenizenCore.implementation.getScriptFolder());
hadError = true;
Debug.echoError(e);
}
return new ArrayList<>();
}
public static void postLoad() {
scriptSources = scriptSourcesInprogress;
scriptOriginalNames = scriptOriginalNamesInprogress;
}
}