-
-
Notifications
You must be signed in to change notification settings - Fork 442
Expand file tree
/
Copy pathSkript.java
More file actions
2228 lines (1970 loc) · 82.1 KB
/
Skript.java
File metadata and controls
2228 lines (1970 loc) · 82.1 KB
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ch.njol.skript;
import ch.njol.skript.aliases.Aliases;
import ch.njol.skript.bukkitutil.BurgerHelper;
import ch.njol.skript.classes.ClassInfo;
import ch.njol.skript.classes.data.*;
import ch.njol.skript.command.Commands;
import ch.njol.skript.doc.Documentation;
import ch.njol.skript.events.EvtSkript;
import ch.njol.skript.expressions.arithmetic.ExprArithmetic;
import ch.njol.skript.hooks.Hook;
import ch.njol.skript.lang.*;
import ch.njol.skript.lang.Condition.ConditionType;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.skript.localization.Language;
import ch.njol.skript.localization.Message;
import ch.njol.skript.localization.PluralizingArgsMessage;
import ch.njol.skript.log.*;
import ch.njol.skript.registrations.Classes;
import ch.njol.skript.registrations.EventValues;
import ch.njol.skript.registrations.Feature;
import ch.njol.skript.test.runner.*;
import ch.njol.skript.timings.SkriptTimings;
import ch.njol.skript.update.ReleaseManifest;
import ch.njol.skript.update.ReleaseStatus;
import ch.njol.skript.update.UpdateManifest;
import ch.njol.skript.util.*;
import ch.njol.skript.util.Date;
import ch.njol.skript.util.chat.BungeeConverter;
import ch.njol.skript.util.chat.ChatMessages;
import ch.njol.skript.variables.Variables;
import ch.njol.util.Closeable;
import ch.njol.util.Kleenean;
import ch.njol.util.StringUtils;
import ch.njol.util.coll.iterator.CheckedIterator;
import ch.njol.util.coll.iterator.EnumerationIterable;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.bstats.bukkit.Metrics;
import org.bukkit.*;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.server.PluginDisableEvent;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.event.server.ServerLoadEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.UnknownNullability;
import org.jetbrains.annotations.Unmodifiable;
import org.junit.After;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
import org.skriptlang.skript.bukkit.SkriptMetrics;
import org.skriptlang.skript.bukkit.breeding.BreedingModule;
import org.skriptlang.skript.bukkit.brewing.BrewingModule;
import org.skriptlang.skript.bukkit.damagesource.DamageSourceModule;
import org.skriptlang.skript.bukkit.displays.DisplayModule;
import org.skriptlang.skript.bukkit.entity.EntityModule;
import org.skriptlang.skript.bukkit.fishing.FishingModule;
import org.skriptlang.skript.bukkit.furnace.FurnaceModule;
import org.skriptlang.skript.bukkit.input.InputModule;
import org.skriptlang.skript.bukkit.interactions.InteractionModule;
import org.skriptlang.skript.bukkit.itemcomponents.ItemComponentModule;
import org.skriptlang.skript.bukkit.log.runtime.BukkitRuntimeErrorConsumer;
import org.skriptlang.skript.bukkit.loottables.LootTableModule;
import org.skriptlang.skript.bukkit.misc.MiscModule;
import org.skriptlang.skript.bukkit.particles.ParticleModule;
import org.skriptlang.skript.bukkit.potion.PotionModule;
import org.skriptlang.skript.bukkit.registration.BukkitSyntaxInfos;
import org.skriptlang.skript.bukkit.tags.TagModule;
import org.skriptlang.skript.common.CommonModule;
import org.skriptlang.skript.common.colors.ColorModule;
import org.skriptlang.skript.docs.Origin;
import org.skriptlang.skript.lang.comparator.Comparator;
import org.skriptlang.skript.lang.comparator.Comparators;
import org.skriptlang.skript.lang.converter.Converter;
import org.skriptlang.skript.lang.converter.Converters;
import org.skriptlang.skript.lang.entry.EntryValidator;
import org.skriptlang.skript.lang.experiment.ExperimentRegistry;
import org.skriptlang.skript.lang.properties.Property;
import org.skriptlang.skript.lang.properties.PropertyRegistry;
import org.skriptlang.skript.lang.script.Script;
import org.skriptlang.skript.lang.structure.Structure;
import org.skriptlang.skript.lang.structure.StructureInfo;
import org.skriptlang.skript.log.runtime.RuntimeErrorManager;
import org.skriptlang.skript.registration.DefaultSyntaxInfos;
import org.skriptlang.skript.registration.SyntaxInfo;
import org.skriptlang.skript.registration.SyntaxRegistry;
import org.skriptlang.skript.registration.SyntaxRegistry.Key;
import org.skriptlang.skript.util.ClassLoader;
import org.skriptlang.skript.util.Priority;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.atomic.AtomicLong;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
// TODO meaningful error if someone uses an %expression with percent signs% outside of text or a variable
/**
* <b>Skript</b> - A Bukkit plugin to modify how Minecraft behaves without having to write a single line of code (You'll likely be writing some code though if you're reading this
* =P)
* <p>
* Use this class to extend this plugin's functionality by adding more {@link Condition conditions}, {@link Effect effects}, {@link SimpleExpression expressions}, etc.
* <p>
* If your plugin.yml contains <tt>'depend: [Skript]'</tt> then your plugin will not start at all if Skript is not present. Add <tt>'softdepend: [Skript]'</tt> to your plugin.yml
* if you want your plugin to work even if Skript isn't present, but want to make sure that Skript gets loaded before your plugin.
* <p>
* If you use 'softdepend' you can test whether Skript is loaded with <tt>'Bukkit.getPluginManager().getPlugin("Skript") != null'</tt>
* <p>
* Once you made sure that Skript is loaded you can use <code>Skript.getInstance()</code> whenever you need a reference to the plugin, but you likely won't need it since all API
* methods are static.
*
* @author Peter Güttinger
* @see #registerAddon(JavaPlugin)
* @see #registerCondition(Class, String...)
* @see #registerEffect(Class, String...)
* @see #registerExpression(Class, Class, ExpressionType, String...)
* @see #registerEvent(String, Class, Class, String...)
* @see EventValues#registerEventValue(Class, Class, Converter, int)
* @see Classes#registerClass(ClassInfo)
* @see Comparators#registerComparator(Class, Class, Comparator)
* @see Converters#registerConverter(Class, Class, Converter)
*/
public final class Skript extends JavaPlugin implements Listener {
// ================ PLUGIN ================
@Nullable
private static Skript instance = null;
private static org.skriptlang.skript.@UnknownNullability Skript skript = null;
private static org.skriptlang.skript.@UnknownNullability Skript unmodifiableSkript = null;
private static boolean disabled = false;
private static boolean partDisabled = false;
public static Skript getInstance() {
if (instance == null)
throw new IllegalStateException();
return instance;
}
/**
* @return The modern Skript instance to be used for addon registration.
*/
public static org.skriptlang.skript.Skript instance() {
if (unmodifiableSkript == null) {
throw new SkriptAPIException("Skript is still initializing");
}
return unmodifiableSkript;
}
/**
* Current updater instance used by Skript.
*/
@Nullable
private SkriptUpdater updater;
public Skript() throws IllegalStateException {
if (instance != null)
throw new IllegalStateException("Cannot create multiple instances of Skript!");
instance = this;
}
private static Version minecraftVersion = new Version(666), UNKNOWN_VERSION = new Version(666);
private static ServerPlatform serverPlatform = ServerPlatform.BUKKIT_UNKNOWN; // Start with unknown... onLoad changes this
/**
* Check minecraft version and assign it to minecraftVersion field
* This method is created to update MC version before onEnable method
*/
public static void updateMinecraftVersion() {
String bukkitV = Bukkit.getBukkitVersion();
Matcher m = Pattern.compile("\\d+\\.\\d+(\\.\\d+)?").matcher(bukkitV);
if (!m.find()) {
minecraftVersion = new Version(666, 0, 0);
} else {
minecraftVersion = new Version("" + m.group());
}
}
@Nullable
private static Version version = null;
@Deprecated(since = "2.9.0", forRemoval = true) // TODO this field will be replaced by a proper registry later
private static @UnknownNullability ExperimentRegistry experimentRegistry;
public static Version getVersion() {
final Version v = version;
if (v == null)
throw new IllegalStateException();
return v;
}
public static final Message
m_invalid_reload = new Message("skript.invalid reload"),
m_finished_loading = new Message("skript.finished loading"),
m_no_errors = new Message("skript.no errors"),
m_no_scripts = new Message("skript.no scripts");
private static final PluralizingArgsMessage m_scripts_loaded = new PluralizingArgsMessage("skript.scripts loaded");
private static final Message WARNING_MESSAGE = new Message("skript.warning message");
private static final Message RESTART_MESSAGE = new Message("skript.restart message");
public static String getWarningMessage() {
return WARNING_MESSAGE.getValueOrDefault("It appears that /reload or another plugin reloaded Skript. This is not supported behaviour and may cause issues.");
}
public static String getRestartMessage() {
return RESTART_MESSAGE.getValueOrDefault("Please consider restarting the server instead.");
}
public static ServerPlatform getServerPlatform() {
if (classExists("net.glowstone.GlowServer")) {
return ServerPlatform.BUKKIT_GLOWSTONE; // Glowstone has timings too, so must check for it first
} else if (classExists("co.aikar.timings.Timings")) {
return ServerPlatform.BUKKIT_PAPER; // Could be Sponge, but it doesn't work at all at the moment
} else if (classExists("org.spigotmc.SpigotConfig")) {
return ServerPlatform.BUKKIT_SPIGOT;
} else if (classExists("org.bukkit.craftbukkit.CraftServer") || classExists("org.bukkit.craftbukkit.Main")) {
// At some point, CraftServer got removed or moved
return ServerPlatform.BUKKIT_CRAFTBUKKIT;
} else { // Probably some ancient Bukkit implementation
return ServerPlatform.BUKKIT_UNKNOWN;
}
}
/**
* Checks if server software and Minecraft version are supported.
* Prints errors or warnings to console if something is wrong.
* @return Whether Skript can continue loading at all.
*/
private static boolean checkServerPlatform() {
String bukkitV = Bukkit.getBukkitVersion();
Matcher m = Pattern.compile("\\d+\\.\\d+(\\.\\d+)?").matcher(bukkitV);
if (!m.find()) {
Skript.error("The Bukkit version '" + bukkitV + "' does not contain a version number which is required for Skript to enable or disable certain features. " +
"Skript will still work, but you might get random errors if you use features that are not available in your version of Bukkit.");
minecraftVersion = new Version(666, 0, 0);
} else {
minecraftVersion = new Version("" + m.group());
}
Skript.debug("Loading for Minecraft " + minecraftVersion);
// Check that MC version is supported
if (!isRunningMinecraft(1, 9)) {
// Prevent loading when not running at least Minecraft 1.9
Skript.error("This version of Skript does not work with Minecraft " + minecraftVersion + " and requires Minecraft 1.9.4+");
Skript.error("You probably want Skript 2.2 or 2.1 (Google to find where to get them)");
Skript.error("Note that those versions are, of course, completely unsupported!");
return false;
}
// Check that current server platform is somewhat supported
serverPlatform = getServerPlatform();
Skript.debug("Server platform: " + serverPlatform);
if (!serverPlatform.works) {
Skript.error("It seems that this server platform (" + serverPlatform.name + ") does not work with Skript.");
if (SkriptConfig.allowUnsafePlatforms.value()) {
Skript.error("However, you have chosen to ignore this. Skript will probably still not work.");
} else {
Skript.error("To prevent potentially unsafe behaviour, Skript has been disabled.");
Skript.error("You may re-enable it by adding a configuration option 'allow unsafe platforms: true'");
Skript.error("Note that it is unlikely that Skript works correctly even if you do so.");
Skript.error("A better idea would be to install Paper or Spigot in place of your current server.");
return false;
}
} else if (!serverPlatform.supported) {
Skript.warning("This server platform (" + serverPlatform.name + ") is not supported by Skript.");
Skript.warning("It will still probably work, but if it does not, you are on your own.");
Skript.warning("Skript officially supports Paper and Spigot.");
}
// If nothing got triggered, everything is probably ok
return true;
}
private static final Set<Class<? extends Hook<?>>> disabledHookRegistrations = new HashSet<>();
private static boolean finishedLoadingHooks = false;
/**
* Checks whether a hook has been enabled.
* @param hook The hook to check.
* @return Whether the hook is enabled.
* @see #disableHookRegistration(Class[])
*/
public static boolean isHookEnabled(Class<? extends Hook<?>> hook) {
return !disabledHookRegistrations.contains(hook);
}
/**
* @return whether hooks have been loaded,
* and if {@link #disableHookRegistration(Class[])} won't error because of this.
*/
public static boolean isFinishedLoadingHooks() {
return finishedLoadingHooks;
}
/**
* Disables the registration for the given hook classes. If Skript has been enabled, this method
* will throw an API exception. It should be used in something like {@link JavaPlugin#onLoad()}.
* @param hooks The hooks to disable the registration of.
* @see #isHookEnabled(Class)
*/
@SafeVarargs
public static void disableHookRegistration(Class<? extends Hook<?>>... hooks) {
if (finishedLoadingHooks) { // Hooks have been registered if Skript is enabled
throw new SkriptAPIException("Disabling hooks is not possible after Skript has been enabled!");
}
Collections.addAll(disabledHookRegistrations, hooks);
}
/**
* The folder containing all Scripts.
* Never reference this field directly. Use {@link #getScriptsFolder()}.
*/
private File scriptsFolder;
/**
* @return The manager for experimental, optional features.
*/
public static ExperimentRegistry experiments() {
return experimentRegistry;
}
/**
* @return The folder containing all Scripts.
*/
public File getScriptsFolder() {
if (!scriptsFolder.isDirectory())
//noinspection ResultOfMethodCallIgnored
scriptsFolder.mkdirs();
return scriptsFolder;
}
// ================ RUNTIME ERRORS ================
public static RuntimeErrorManager getRuntimeErrorManager() {
return RuntimeErrorManager.getInstance();
}
// =================================================
@Override
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
if (disabled) {
Skript.error(m_invalid_reload.toString());
setEnabled(false);
return;
}
handleJvmArguments(); // JVM arguments
version = new Version("" + getDescription().getVersion()); // Skript version
// Start the updater
// Note: if config prohibits update checks, it will NOT do network connections
try {
this.updater = new SkriptUpdater();
} catch (Exception e) {
Skript.exception(e, "Update checker could not be initialized.");
}
if (!getDataFolder().isDirectory())
getDataFolder().mkdirs();
scriptsFolder = new File(getDataFolder(), SCRIPTSFOLDER);
File config = new File(getDataFolder(), "config.sk");
File features = new File(getDataFolder(), "features.sk");
File lang = new File(getDataFolder(), "lang");
File aliasesFolder = new File(getDataFolder(), "aliases");
if (!scriptsFolder.isDirectory() || !config.exists() || !features.exists() || !lang.exists() || !aliasesFolder.exists()) {
ZipFile f = null;
try {
boolean populateExamples = false;
if (!scriptsFolder.isDirectory()) {
if (!scriptsFolder.mkdirs())
throw new IOException("Could not create the directory " + scriptsFolder);
populateExamples = true;
}
boolean populateLanguageFiles = false;
if (!lang.isDirectory()) {
if (!lang.mkdirs())
throw new IOException("Could not create the directory " + lang);
populateLanguageFiles = true;
}
if (!aliasesFolder.isDirectory()) {
if (!aliasesFolder.mkdirs())
throw new IOException("Could not create the directory " + aliasesFolder);
}
f = new ZipFile(getFile());
for (ZipEntry e : new EnumerationIterable<ZipEntry>(f.entries())) {
if (e.isDirectory())
continue;
File saveTo = null;
if (populateExamples && e.getName().startsWith(SCRIPTSFOLDER + "/")) {
String fileName = e.getName().substring(e.getName().indexOf("/") + 1);
// All example scripts must be disabled for jar security.
if (!fileName.startsWith(ScriptLoader.DISABLED_SCRIPT_PREFIX))
fileName = ScriptLoader.DISABLED_SCRIPT_PREFIX + fileName;
saveTo = new File(scriptsFolder, fileName);
} else if (populateLanguageFiles
&& e.getName().startsWith("lang/")
&& !e.getName().endsWith("default.lang")) {
String fileName = e.getName().substring(e.getName().lastIndexOf("/") + 1);
saveTo = new File(lang, fileName);
} else if (e.getName().equals("config.sk")) {
if (!config.exists())
saveTo = config;
// } else if (e.getName().startsWith("aliases-") && e.getName().endsWith(".sk") && !e.getName().contains("/")) {
// File af = new File(getDataFolder(), e.getName());
// if (!af.exists())
// saveTo = af;
} else if (e.getName().startsWith("features.sk")) {
if (!features.exists())
saveTo = features;
}
if (saveTo != null) {
InputStream in = f.getInputStream(e);
try {
assert in != null;
FileUtils.save(in, saveTo);
} finally {
in.close();
}
}
}
info("Successfully generated the config and the example scripts.");
} catch (ZipException ignored) {} catch (IOException e) {
error("Error generating the default files: " + ExceptionUtils.toString(e));
} finally {
if (f != null) {
try {
f.close();
} catch (IOException ignored) {}
}
}
}
// initialize the modern Skript instance
skript = org.skriptlang.skript.Skript.of(getClass(), getName());
unmodifiableSkript = new ModernSkriptBridge.SpecialUnmodifiableSkript(skript);
skript.localizer().setSourceDirectories("lang",
getDataFolder().getAbsolutePath() + File.separatorChar + "lang");
// initialize the old Skript SkriptAddon instance
getAddonInstance();
experimentRegistry = new ExperimentRegistry(this);
Feature.registerAll(getAddonInstance(), experimentRegistry);
skript.storeRegistry(PropertyRegistry.class, new PropertyRegistry(this));
Property.registerDefaultProperties();
// Load classes which are always safe to use
new JavaClasses(); // These may be needed in configuration
// Check server software, Minecraft version, etc.
if (!checkServerPlatform()) {
disabled = true; // Nothing was loaded, nothing needs to be unloaded
setEnabled(false); // Cannot continue; user got errors in console to tell what happened
return;
}
// And then not-so-safe classes
Throwable classLoadError = null;
try {
new SkriptClasses();
new BukkitClasses();
} catch (Throwable e) {
classLoadError = e;
}
// Warn about pausing
if (Skript.methodExists(Server.class, "getPauseWhenEmptyTime")) {
int pauseThreshold = getServer().getPauseWhenEmptyTime();
if (pauseThreshold > -1) {
Skript.warning("Minecraft server pausing is enabled!");
Skript.warning("Scripts that interact with the world or entities may not work as intended when the server is paused and may crash your server.");
Skript.warning("Consider setting 'pause-when-empty-seconds' to -1 in server.properties to make sure you don't encounter any issues.");
}
}
// Config must be loaded after Java and Skript classes are parseable
// ... but also before platform check, because there is a config option to ignore some errors
SkriptConfig.load();
// Register the runtime error refresh after loading, so we can do the first instantiation manually.
SkriptConfig.eventRegistry().register(SkriptConfig.ReloadEvent.class, RuntimeErrorManager::refresh);
// init runtime error manager and add bukkit consumer.
RuntimeErrorManager.refresh();
getRuntimeErrorManager().addConsumer(new BukkitRuntimeErrorConsumer());
// Now override the verbosity if test mode is enabled
if (TestMode.VERBOSITY != null)
SkriptLogger.setVerbosity(Verbosity.valueOf(TestMode.VERBOSITY));
// Use the updater, now that it has been configured to (not) do stuff
if (updater != null) {
CommandSender console = Bukkit.getConsoleSender();
assert console != null;
assert updater != null;
updater.updateCheck(console);
}
// If loading can continue (platform ok), check for potentially thrown error
if (classLoadError != null) {
exception(classLoadError);
setEnabled(false);
return;
}
PluginCommand skriptCommand = getCommand("skript");
assert skriptCommand != null; // It is defined, unless build is corrupted or something like that
skriptCommand.setExecutor(new SkriptCommand());
skriptCommand.setTabCompleter(new SkriptCommandTabCompleter());
// Load Bukkit stuff. It is done after platform check, because something might be missing!
new BukkitEventValues();
new DefaultComparators();
new DefaultConverters();
new DefaultFunctions();
new DefaultOperations();
ChatMessages.registerListeners();
try {
getAddonInstance().loadClasses("ch.njol.skript",
"conditions", "effects", "events", "expressions", "entity", "literals", "sections", "structures");
getAddonInstance().loadClasses("org.skriptlang.skript.bukkit", "misc");
// todo: become proper module once registry api is merged
FishingModule.load();
BreedingModule.load();
DisplayModule.load();
InputModule.load();
TagModule.load();
FurnaceModule.load();
LootTableModule.load();
skript.loadModules(
new CommonModule(),
new BrewingModule(),
new ColorModule(),
new EntityModule(),
new DamageSourceModule(),
new InteractionModule(),
new ItemComponentModule(),
new PotionModule(),
new MiscModule(),
new ParticleModule());
} catch (final Exception e) {
exception(e, "Could not load required .class files: " + e.getLocalizedMessage());
setEnabled(false);
return;
}
// todo: remove completely 2.11 or 2.12
CompletableFuture<Boolean> aliases = Aliases.loadAsync();
Commands.registerListeners();
if (logNormal())
info(" " + Language.get("skript.copyright"));
final long tick = testing() ? Bukkit.getWorlds().get(0).getFullTime() : 0;
Bukkit.getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
@SuppressWarnings("synthetic-access")
@Override
public void run() {
assert Bukkit.getWorlds().get(0).getFullTime() == tick;
// Load hooks from Skript jar
try {
try (JarFile jar = new JarFile(getFile())) {
for (JarEntry e : new EnumerationIterable<>(jar.entries())) {
if (e.getName().startsWith("ch/njol/skript/hooks/") && e.getName().endsWith("Hook.class") && StringUtils.count("" + e.getName(), '/') <= 5) {
final String c = e.getName().replace('/', '.').substring(0, e.getName().length() - ".class".length());
try {
Class<?> hook = Class.forName(c, true, getClassLoader());
if (Hook.class.isAssignableFrom(hook) && !Modifier.isAbstract(hook.getModifiers()) && isHookEnabled((Class<? extends Hook<?>>) hook)) {
hook.getDeclaredConstructor().setAccessible(true);
hook.getDeclaredConstructor().newInstance();
}
} catch (ClassNotFoundException ex) {
Skript.exception(ex, "Cannot load class " + c);
} catch (ExceptionInInitializerError err) {
Skript.exception(err.getCause(), "Class " + c + " generated an exception while loading");
} catch (Exception ex) {
Skript.exception(ex, "Exception initializing hook: " + c);
}
}
}
}
} catch (IOException e) {
error("Error while loading plugin hooks" + (e.getLocalizedMessage() == null ? "" : ": " + e.getLocalizedMessage()));
Skript.exception(e);
}
finishedLoadingHooks = true;
try {
aliases.get(); // wait for aliases to load
} catch (InterruptedException | ExecutionException e) {
exception(e, "Could not load aliases concurrently");
}
if (TestMode.ENABLED) {
info("Preparing Skript for testing...");
tainted = true;
try {
getAddonInstance().loadClasses("ch.njol.skript.test.runner");
if (TestMode.JUNIT)
getAddonInstance().loadClasses("org.skriptlang.skript.test.junit.registration");
} catch (IOException e) {
Skript.exception("Failed to load testing environment.");
Bukkit.getServer().shutdown();
}
}
stopAcceptingRegistrations();
Documentation.generate(); // TODO move to test classes?
// Variable loading
if (logNormal())
info("Loading variables...");
long vls = System.currentTimeMillis();
LogHandler h = SkriptLogger.startLogHandler(new ErrorDescLogHandler() {
@Override
public LogResult log(final LogEntry entry) {
super.log(entry);
if (entry.level.intValue() >= Level.SEVERE.intValue()) {
logEx(entry.message); // no [Skript] prefix
return LogResult.DO_NOT_LOG;
} else {
return LogResult.LOG;
}
}
@Override
protected void beforeErrors() {
logEx();
logEx("===!!!=== Skript variable load error ===!!!===");
logEx("Unable to load (all) variables:");
}
@Override
protected void afterErrors() {
logEx();
logEx("Skript will work properly, but old variables might not be available at all and new ones may or may not be saved until Skript is able to create a backup of the old file and/or is able to connect to the database (which requires a restart of Skript)!");
logEx();
}
});
try (CountingLogHandler c = new CountingLogHandler(SkriptLogger.SEVERE).start()) {
if (!Variables.load())
if (c.getCount() == 0)
error("(no information available)");
} finally {
h.stop();
}
long vld = System.currentTimeMillis() - vls;
if (logNormal())
info("Loaded " + Variables.numVariables() + " variables in " + ((vld / 100) / 10.) + " seconds");
// Skript initialization done
debug("Early init done");
if (TestMode.ENABLED) {
if (TestMode.DEV_MODE) {
runTests(); // Dev mode doesn't need a delay
} else {
// delay + chunk loading necessary to allow world to fully generate and start ticking before tests run.
World world = Bukkit.getWorlds().get(0);
world.setSpawnLocation(0, 0, 0);
Bukkit.getScheduler().scheduleSyncDelayedTask(Skript.getInstance(), () -> {
world.addPluginChunkTicket(0, 0, Skript.getInstance());
world.addPluginChunkTicket(100, 100, Skript.getInstance());
Bukkit.getScheduler().scheduleSyncDelayedTask(Skript.getInstance(), () -> runTests(), 100);
}, 5);
}
}
Skript.metrics = new Metrics(Skript.getInstance(), 722); // 722 is our bStats plugin ID
SkriptMetrics.setupMetrics(Skript.metrics);
/*
* Start loading scripts
*/
Date start = new Date();
CountingLogHandler logHandler = new CountingLogHandler(Level.SEVERE);
File scriptsFolder = getScriptsFolder();
ScriptLoader.updateDisabledScripts(scriptsFolder.toPath());
ScriptLoader.loadScripts(scriptsFolder, logHandler)
.thenAccept(scriptInfo -> {
try {
if (logHandler.getCount() == 0)
Skript.info(m_no_errors.toString());
if (scriptInfo.files == 0)
Skript.warning(m_no_scripts.toString());
if (Skript.logNormal() && scriptInfo.files > 0)
Skript.info(m_scripts_loaded.toString(
scriptInfo.files,
scriptInfo.structures,
start.difference(new Date())
));
Skript.info(m_finished_loading.toString());
// EvtSkript.onSkriptStart should be called on main server thread
if (!ScriptLoader.isAsync()) {
EvtSkript.onSkriptStart();
// Suppresses the "can't keep up" warning after loading all scripts
// Only for non-asynchronous loading
Filter filter = record -> {
if (record == null)
return false;
return record.getMessage() == null
|| !record.getMessage().toLowerCase(Locale.ENGLISH).startsWith("can't keep up!");
};
BukkitLoggerFilter.addFilter(filter);
Bukkit.getScheduler().scheduleSyncDelayedTask(
Skript.this,
() -> BukkitLoggerFilter.removeFilter(filter),
1);
} else {
Bukkit.getScheduler().scheduleSyncDelayedTask(Skript.this,
EvtSkript::onSkriptStart);
}
} catch (Exception e) {
// Something went wrong, we need to make sure the exception is printed
throw Skript.exception(e);
}
});
}
});
if (!TestMode.ENABLED) {
Bukkit.getPluginManager().registerEvents(new JoinUpdateNotificationListener(), this);
}
// Send a warning to console when the plugin is reloaded
Bukkit.getPluginManager().registerEvents(new ServerReloadListener(), this);
// Tell Timings that we are here!
SkriptTimings.setSkript(this);
}
private static class ServerReloadListener implements Listener {
@EventHandler
public void onServerReload(ServerLoadEvent event) {
if ((event.getType() != ServerLoadEvent.LoadType.RELOAD))
return;
for (OfflinePlayer player : Bukkit.getOperators()) {
if (player.isOnline()) {
player.getPlayer().sendMessage(ChatColor.YELLOW + getWarningMessage());
player.getPlayer().sendMessage(ChatColor.YELLOW + getRestartMessage());
}
}
Skript.warning(getWarningMessage());
Skript.warning(getRestartMessage());
}
}
private class JoinUpdateNotificationListener implements Listener {
@EventHandler
public void onJoin(PlayerJoinEvent event) {
if (!event.getPlayer().hasPermission("skript.admin"))
return;
new Task(Skript.this, 0) {
@Override
public void run() {
Player player = event.getPlayer();
SkriptUpdater updater = getUpdater();
// Don't actually check for updates to avoid breaking GitHub rate limit
if (updater == null || updater.getReleaseStatus() != ReleaseStatus.OUTDATED)
return;
// Last check indicated that an update is available
UpdateManifest update = updater.getUpdateManifest();
if (update == null)
return;
Skript.info(player, SkriptUpdater.m_update_available.toString(update.id, Skript.getVersion()));
player.spigot().sendMessage(BungeeConverter.convert(ChatMessages.parseToArray(
"Download it at: <aqua><u><link:" + update.downloadUrl + ">" + update.downloadUrl)));
}
};
}
}
private void runTests() {
info("Skript testing environment enabled, starting...");
// Delay is in Minecraft ticks.
AtomicLong shutdownDelay = new AtomicLong(0);
List<Class<?>> asyncTests = new ArrayList<>();
CompletableFuture<Void> onAsyncComplete = CompletableFuture.completedFuture(null);
if (TestMode.GEN_DOCS) {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "skript gen-docs");
} else if (TestMode.DEV_MODE) { // Developer controlled environment.
info("Test development mode enabled. Test scripts are at " + TestMode.TEST_DIR);
return;
} else {
info("Loading all tests from " + TestMode.TEST_DIR);
// Treat parse errors as fatal testing failure
TestingLogHandler errorCounter = new TestingLogHandler(Level.SEVERE);
try {
errorCounter.start();
// load example scripts (cleanup after)
ScriptLoader.loadScripts(new File(getScriptsFolder(), "-examples" + File.separator), errorCounter);
// unload these as to not interfere with the tests
ScriptLoader.unloadScripts(ScriptLoader.getLoadedScripts());
// load test directory scripts
ScriptLoader.loadScripts(TestMode.TEST_DIR.toFile(), errorCounter);
} finally {
errorCounter.stop();
}
Bukkit.getPluginManager().callEvent(new SkriptTestEvent());
if (errorCounter.getCount() > 0) {
TestTracker.testStarted("parse scripts");
TestTracker.testFailed(errorCounter.getCount() + " error(s) found");
}
if (errored) { // Check for exceptions thrown while script was executing
TestTracker.testStarted("run scripts");
TestTracker.testFailed("exception was thrown during execution");
}
if (TestMode.JUNIT) {
AtomicLong milliseconds = new AtomicLong(0),
tests = new AtomicLong(0), fails = new AtomicLong(0),
ignored = new AtomicLong(0), size = new AtomicLong(0);
info("Running sync JUnit tests...");
try {
// Search for all test classes
Set<Class<?>> classes = new HashSet<>();
ClassLoader.builder()
.addSubPackages("org.skriptlang.skript", "ch.njol.skript")
.filter(fqn -> fqn.endsWith("Test"))
.initialize(true)
.deep(true)
.forEachClass(clazz -> {
if (clazz.isAnonymousClass() || clazz.isLocalClass())
return;
classes.add(clazz);
})
.build()
.loadClasses(Skript.class, getFile());
// remove some known non-tests that get picked up
classes.remove(SkriptJUnitTest.class);
classes.remove(SkriptAsyncJUnitTest.class);
size.set(classes.size());
for (Class<?> clazz : classes) {
if (SkriptAsyncJUnitTest.class.isAssignableFrom(clazz)) {
asyncTests.add(clazz); // do these later, all together
continue;
}
runTest(clazz, shutdownDelay, tests, milliseconds, ignored, fails);
}
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
InvocationTargetException | NoSuchMethodException | SecurityException e) {
Skript.exception(e, "Failed to initalize test JUnit classes.");
}
if (ignored.get() > 0)
Skript.warning("There were " + ignored + " ignored test cases! This can mean they are not properly setup in order in that class!");
onAsyncComplete = CompletableFuture.runAsync(() -> {
info("Running async JUnit tests...");
try {
for (Class<?> clazz : asyncTests) {
runTest(clazz, shutdownDelay, tests, milliseconds, ignored, fails);
}
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException |
InvocationTargetException | NoSuchMethodException | SecurityException e) {
Skript.exception(e, "Failed to initalize test JUnit classes.");
}
if (ignored.get() > 0)
Skript.warning("There were " + ignored + " ignored test cases! " +
"This can mean they are not properly setup in order in that class!");
info("Completed " + tests + " JUnit tests in " + size + " classes with " + fails +
" failures in " + milliseconds + " milliseconds.");
});
}
}
onAsyncComplete.thenRun(() -> {
double display = shutdownDelay.get() / 20.0;
info("Testing done, shutting down the server in " + display + " second" + (display == 1 ? "" : "s") + "...");
// Delay server shutdown to stop the server from crashing because the current tick takes a long time due to all the tests
Bukkit.getScheduler().runTaskLater(Skript.this, () -> {
info("Shutting down server.");
if (TestMode.JUNIT && !EffObjectives.isJUnitComplete())
EffObjectives.fail();
info("Collecting results to " + TestMode.RESULTS_FILE);
String results = new GsonBuilder()
.setPrettyPrinting() // Easier to read lines
.disableHtmlEscaping() // Fixes issue with "'" character in test strings going unicode
.create().toJson(TestTracker.collectResults());
try {
Files.write(TestMode.RESULTS_FILE, results.getBytes(StandardCharsets.UTF_8));
} catch (IOException e) {
Skript.exception(e, "Failed to write test results.");
}
// delay by 1 tick to avoid the watchdog from thinking the shutdown tick took too long.
Bukkit.getScheduler().runTaskLater(Skript.this, () -> Bukkit.getServer().shutdown(), 1);
}, shutdownDelay.get());
});
}
private void runTest(Class<?> clazz, AtomicLong shutdownDelay, AtomicLong tests,
AtomicLong milliseconds, AtomicLong ignored, AtomicLong fails)
throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
String test = clazz.getName();
SkriptJUnitTest.setCurrentJUnitTest(test);
SkriptJUnitTest.setShutdownDelay(0);
info("Running JUnit test '" + test + "'");
Result result = JUnitCore.runClasses(clazz);
TestTracker.testStarted("JUnit: '" + test + "'");
/*
* Usage of @After is pointless if the JUnit class requires delay. As the @After will happen instantly.
* The JUnit must override the 'cleanup' method to avoid Skript automatically cleaning up the test data.
*/
boolean overrides = false;
for (Method method : clazz.getDeclaredMethods()) {
if (!method.isAnnotationPresent(After.class))
continue;
if (SkriptJUnitTest.getShutdownDelay() > 1)
warning("Methods annotated with @After in happen instantaneously, and '" + test + "' requires a delay. Do test cleanup in the junit script file or 'cleanup' method.");
if (method.getName().equals("cleanup"))
overrides = true;
}
if (SkriptJUnitTest.getShutdownDelay() > 1 && !overrides)
error("The JUnit class '" + test + "' does not override the method 'cleanup', thus the test data will instantly be cleaned up " +
"despite requiring a longer shutdown time: " + SkriptJUnitTest.getShutdownDelay());
shutdownDelay.set(Math.max(shutdownDelay.get(), SkriptJUnitTest.getShutdownDelay()));
tests.getAndAdd(result.getRunCount());
milliseconds.getAndAdd(result.getRunTime());
ignored.getAndAdd(result.getIgnoreCount());