-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
YamlCommand.java
872 lines (809 loc) · 37.5 KB
/
YamlCommand.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
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
package com.denizenscript.denizencore.scripts.commands.file;
import com.denizenscript.denizencore.exceptions.InvalidArgumentsException;
import com.denizenscript.denizencore.objects.*;
import com.denizenscript.denizencore.objects.core.ElementTag;
import com.denizenscript.denizencore.objects.core.ListTag;
import com.denizenscript.denizencore.scripts.commands.AbstractCommand;
import com.denizenscript.denizencore.scripts.commands.Holdable;
import com.denizenscript.denizencore.tags.TagRunnable;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import com.denizenscript.denizencore.utilities.Deprecations;
import com.denizenscript.denizencore.utilities.YamlConfiguration;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizencore.utilities.scheduling.AsyncSchedulable;
import com.denizenscript.denizencore.utilities.scheduling.OneTimeSchedulable;
import com.denizenscript.denizencore.utilities.text.StringHolder;
import com.denizenscript.denizencore.DenizenCore;
import com.denizenscript.denizencore.scripts.ScriptEntry;
import com.denizenscript.denizencore.scripts.ScriptHelper;
import com.denizenscript.denizencore.tags.Attribute;
import com.denizenscript.denizencore.tags.ReplaceableTagEvent;
import com.denizenscript.denizencore.tags.TagManager;
import org.json.JSONObject;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.*;
public class YamlCommand extends AbstractCommand implements Holdable {
// <--[command]
// @Name Yaml
// @Syntax yaml [create]/[load:<file>]/[loadtext:<text>]/[unload]/[savefile:<file>]/[copykey:<source key> <target key> (to_id:<name>)]/[set <key>([<#>])(:<action>):<value>] [id:<name>]
// @Required 2
// @Short Edits a YAML configuration file.
// @Group file
//
// @Description
// Edits a YAML configuration file.
// This can be used for interacting with other plugins' configuration files.
// It can also be used for storing your own script's data.
//
// Use holdable syntax ("- ~yaml load:...") with load or savefile actions to avoid locking up the server during file IO.
//
// For loading and saving, the starting path is within 'plugins/Denizen'.
//
// Please note that all usages of the YAML command except for "load" and "savefile" arguments are purely in memory.
// That means, if you use "set" to make changes, those changes will not be saved to any file, until you use "savefile".
// Similarly, "create" does not create any file, instead it only creates a YAML object in RAM.
//
// Note that the '.yml' extension is not automatically appended, and you will have to include that in filenames.
//
// All usages of the YAML command must include the "id:" argument. This is any arbitrary name, as plaintext or from a tag,
// to uniquely and globally identify the YAML object in memory. This ID can only be used by one YAML object at a type.
// IDs are stored when "create" or "load" arguments are used, and only removed when "unload" is used.
// If, for example, you have a unique YAML data container per-player, you might use something like "id:myscript_<player>".
//
// For ways to use the "set" argument, refer to <@link language data actions>.
//
// @Tags
// <yaml[<idname>].contains[<path>]>
// <yaml[<idname>].read[<path>]>
// <yaml[<idname>].list_keys[<path>]>
//
// @Usage
// Use to create a new YAML file.
// - yaml create id:myfile
//
// @Usage
// Use to load a YAML file from disk.
// - ~yaml load:myfile.yml id:myfile
//
// @Usage
// Use to modify a YAML file similarly to a flag.
// - yaml id:myfile set my.key:HelloWorld
//
// @Usage
// Use to save a YAML file to disk.
// - ~yaml savefile:myfile.yml id:myfile
//
// @Usage
// Use to unload a YAML file from memory.
// - yaml unload id:myfile
//
// @Usage
// Use to modify a YAML file similarly to a flag.
// - yaml id:myfile set my.key:+:2
//
// @Usage
// Use to modify a YAML file similarly to a flag.
// - yaml id:myfile set my.key[2]:hello
//
// @Usage
// Use to modify a copy the contents of one YAML key to a new owning key.
// - yaml id:myfile copykey:my.first.key my.new.key
//
// @Usage
// Use to modify a copy the contents of one YAML key to a new owning key on a different YAML file.
// - yaml id:myfile copykey:my.first.key my.new.key to_id:myotherfile
// -->
@Override
public void onEnable() {
TagManager.registerTagHandler(new TagRunnable.RootForm() {
@Override
public void run(ReplaceableTagEvent event) {
yaml(event);
}
}, "yaml");
}
Map<String, YamlConfiguration> yamls = new HashMap<>();
private YamlConfiguration getYaml(String id) {
if (id == null) {
Debug.echoError("Trying to get YAML file with NULL ID!");
return null;
}
return yamls.get(id.toUpperCase());
}
public enum Action {LOAD, LOADTEXT, UNLOAD, CREATE, SAVE, SET, COPYKEY}
public enum YAML_Action {
SET_VALUE, INCREASE, DECREASE, MULTIPLY,
DIVIDE, INSERT, REMOVE, SPLIT, DELETE, SPLIT_NEW
}
@Override
public void parseArgs(ScriptEntry scriptEntry) throws InvalidArgumentsException {
boolean isSet = false;
boolean isCopyKey = false;
for (Argument arg : scriptEntry.getProcessedArgs()) {
if (!scriptEntry.hasObject("action") &&
arg.matchesPrefix("load")) {
scriptEntry.addObject("action", new ElementTag("LOAD"));
scriptEntry.addObject("filename", arg.asElement());
}
else if (!scriptEntry.hasObject("action") &&
arg.matchesPrefix("loadtext")) {
scriptEntry.addObject("action", new ElementTag("LOADTEXT"));
scriptEntry.addObject("raw_text", arg.asElement());
}
else if (!scriptEntry.hasObject("action") &&
arg.matchesPrefix("savefile", "filesave")) {
scriptEntry.addObject("action", new ElementTag("SAVE"));
scriptEntry.addObject("filename", arg.asElement());
}
else if (!scriptEntry.hasObject("action") &&
arg.matches("create")) {
scriptEntry.addObject("action", new ElementTag("CREATE"));
}
else if (!scriptEntry.hasObject("action") &&
arg.matches("set")) {
scriptEntry.addObject("action", new ElementTag("SET"));
isSet = true;
}
else if (!scriptEntry.hasObject("action") &&
arg.matchesPrefix("copykey")) {
scriptEntry.addObject("action", new ElementTag("COPYKEY"));
scriptEntry.addObject("key", arg.asElement());
isSet = true;
isCopyKey = true;
}
else if (!scriptEntry.hasObject("action") &&
arg.matches("unload")) {
scriptEntry.addObject("action", new ElementTag("UNLOAD"));
}
else if (!scriptEntry.hasObject("value") &&
arg.matchesPrefix("value")) {
if (arg.matchesArgumentType(ListTag.class)) {
scriptEntry.addObject("value", arg.asType(ListTag.class));
}
else {
scriptEntry.addObject("value", arg.asElement());
}
}
else if (!scriptEntry.hasObject("id") &&
arg.matchesPrefix("id")) {
scriptEntry.addObject("id", arg.asElement());
}
else if (!scriptEntry.hasObject("to_id") &&
arg.matchesPrefix("to_id")) {
scriptEntry.addObject("to_id", arg.asElement());
}
else if (!scriptEntry.hasObject("split") &&
arg.matches("split_list")) {
scriptEntry.addObject("split", new ElementTag("true"));
}
else if (!scriptEntry.hasObject("fix_formatting") &&
arg.matches("fix_formatting")) {
scriptEntry.addObject("fix_formatting", new ElementTag("true"));
}
// Check for key:value/action
else if (isSet &&
!scriptEntry.hasObject("value") &&
arg.raw_value.split(":", 3).length == 2) {
String[] flagArgs = arg.raw_value.split(":", 2);
scriptEntry.addObject("key", new ElementTag(flagArgs[0]));
if (flagArgs[1].equals("++") || flagArgs[1].equals("+")) {
scriptEntry.addObject("yaml_action", YAML_Action.INCREASE);
scriptEntry.addObject("value", new ElementTag(1));
}
else if (flagArgs[1].equals("--") || flagArgs[1].equals("-")) {
scriptEntry.addObject("yaml_action", YAML_Action.DECREASE);
scriptEntry.addObject("value", new ElementTag(1));
}
else if (flagArgs[1].equals("!")) {
scriptEntry.addObject("yaml_action", YAML_Action.DELETE);
scriptEntry.addObject("value", new ElementTag(false));
}
else if (flagArgs[1].equals("<-")) {
scriptEntry.addObject("yaml_action", YAML_Action.REMOVE);
scriptEntry.addObject("value", new ElementTag(false));
}
else {
// No ACTION, we're just setting a value...
scriptEntry.addObject("yaml_action", YAML_Action.SET_VALUE);
scriptEntry.addObject("value", new ElementTag(flagArgs[1]));
}
}
// Check for key:action:value
else if (isSet &&
!scriptEntry.hasObject("value") &&
arg.raw_value.split(":", 3).length == 3) {
String[] flagArgs = arg.raw_value.split(":", 3);
scriptEntry.addObject("key", new ElementTag(flagArgs[0]));
if (flagArgs[1].equals("->")) {
scriptEntry.addObject("yaml_action", YAML_Action.INSERT);
}
else if (flagArgs[1].equals("<-")) {
scriptEntry.addObject("yaml_action", YAML_Action.REMOVE);
}
else if (flagArgs[1].equals("||") || flagArgs[1].equals("|")) {
scriptEntry.addObject("yaml_action", YAML_Action.SPLIT);
}
else if (flagArgs[1].equals("!|")) {
scriptEntry.addObject("yaml_action", YAML_Action.SPLIT_NEW);
}
else if (flagArgs[1].equals("++") || flagArgs[1].equals("+")) {
scriptEntry.addObject("yaml_action", YAML_Action.INCREASE);
}
else if (flagArgs[1].equals("--") || flagArgs[1].equals("-")) {
scriptEntry.addObject("yaml_action", YAML_Action.DECREASE);
}
else if (flagArgs[1].equals("**") || flagArgs[1].equals("*")) {
scriptEntry.addObject("yaml_action", YAML_Action.MULTIPLY);
}
else if (flagArgs[1].equals("//") || flagArgs[1].equals("/")) {
scriptEntry.addObject("yaml_action", YAML_Action.DIVIDE);
}
else {
scriptEntry.addObject("yaml_action", YAML_Action.SET_VALUE);
scriptEntry.addObject("value", new ElementTag(arg.raw_value.split(":", 2)[1]));
continue;
}
scriptEntry.addObject("value", new ElementTag(flagArgs[2]));
}
else if (isCopyKey && !scriptEntry.hasObject("value")) {
scriptEntry.addObject("value", arg.asElement());
}
else {
arg.reportUnhandled();
}
}
// Check for required arguments
if (!scriptEntry.hasObject("id")) {
throw new InvalidArgumentsException("Must specify an id!");
}
if (!scriptEntry.hasObject("action")) {
throw new InvalidArgumentsException("Must specify an action!");
}
scriptEntry.defaultObject("value", new ElementTag(""));
scriptEntry.defaultObject("fix_formatting", new ElementTag("false"));
}
@Override
public void execute(final ScriptEntry scriptEntry) {
ElementTag filename = scriptEntry.getElement("filename");
ElementTag rawText = scriptEntry.getElement("raw_text");
ElementTag key = scriptEntry.getElement("key");
ObjectTag value = scriptEntry.getObjectTag("value");
ElementTag split = scriptEntry.getElement("split");
YAML_Action yaml_action = (YAML_Action) scriptEntry.getObject("yaml_action");
ElementTag actionElement = scriptEntry.getElement("action");
ElementTag idElement = scriptEntry.getElement("id");
ElementTag fixFormatting = scriptEntry.getElement("fix_formatting");
ElementTag toId = scriptEntry.getElement("to_id");
YamlConfiguration yamlConfiguration;
if (scriptEntry.dbCallShouldDebug()) {
Debug.report(scriptEntry, getName(),
idElement.debug()
+ actionElement.debug()
+ (filename != null ? filename.debug() : "")
+ (yaml_action != null ? ArgumentHelper.debugObj("yaml_action", yaml_action.name()) : "")
+ (key != null ? key.debug() : "")
+ (value != null ? value.debug() : "")
+ (split != null ? split.debug() : "")
+ (rawText != null ? rawText.debug() : "")
+ (toId != null ? toId.debug() : ""));
}
// Do action
Action action = Action.valueOf(actionElement.asString().toUpperCase());
String id = idElement.asString().toUpperCase();
if (action != Action.LOAD && action != Action.SAVE && scriptEntry.shouldWaitFor()) {
scriptEntry.setFinished(true);
}
switch (action) {
case LOAD:
File file = new File(DenizenCore.getImplementation().getDataFolder(), filename.asString());
if (!DenizenCore.getImplementation().canReadFile(file)) {
Debug.echoError("Server config denies reading files in that location.");
scriptEntry.setFinished(true);
return;
}
if (!file.exists()) {
Debug.echoError("File cannot be found!");
scriptEntry.setFinished(true);
return;
}
YamlConfiguration[] runnableConfigs = new YamlConfiguration[1];
Runnable onLoadCompleted = new Runnable() {
@Override
public void run() {
yamls.remove(id);
yamls.put(id, runnableConfigs[0]);
scriptEntry.setFinished(true);
}
};
Runnable loadRunnable = new Runnable() {
@Override
public void run() {
try {
FileInputStream fis = new FileInputStream(file);
String str = ScriptHelper.convertStreamToString(fis);
if (fixFormatting.asBoolean()) {
str = ScriptHelper.clearComments("", str, false);
Deprecations.yamlFixFormatting.warn(scriptEntry);
}
runnableConfigs[0] = YamlConfiguration.load(str);
fis.close();
if (runnableConfigs[0] == null) {
runnableConfigs[0] = new YamlConfiguration();
}
if (scriptEntry.shouldWaitFor()) {
DenizenCore.schedule(new OneTimeSchedulable(onLoadCompleted, 0));
}
else {
onLoadCompleted.run();
}
}
catch (Exception e) {
Debug.echoError("Failed to load yaml file: " + e);
}
}
};
if (scriptEntry.shouldWaitFor()) {
DenizenCore.schedule(new AsyncSchedulable(new OneTimeSchedulable(loadRunnable, 0)));
}
else {
loadRunnable.run();
}
break;
case LOADTEXT:
String str = rawText.asString();
YamlConfiguration config = YamlConfiguration.load(str);
yamls.remove(id);
yamls.put(id, config);
scriptEntry.setFinished(true);
break;
case UNLOAD:
if (yamls.containsKey(id)) {
yamls.remove(id);
}
else {
Debug.echoError("Unknown YAML ID '" + id + "'");
}
break;
case SAVE:
if (yamls.containsKey(id)) {
try {
if (!DenizenCore.getImplementation().allowStrangeYAMLSaves()) {
File fileObj = new File(DenizenCore.getImplementation().
getDataFolder().getAbsolutePath() + "/" + filename.asString());
String directory = URLDecoder.decode(System.getProperty("user.dir"));
if (!fileObj.getCanonicalPath().startsWith(directory)) {
Debug.echoError("Outside-the-main-folder YAML saves disabled by administrator.");
scriptEntry.setFinished(true);
return;
}
}
File fileObj = new File(DenizenCore.getImplementation().
getDataFolder().getAbsolutePath() + "/" + filename.asString());
if (!DenizenCore.getImplementation().canWriteToFile(fileObj)) {
Debug.echoError(scriptEntry.getResidingQueue(), "Cannot edit that file!");
scriptEntry.setFinished(true);
return;
}
fileObj.getParentFile().mkdirs();
String outp = yamls.get(id).saveToString(false);
Runnable saveRunnable = new Runnable() {
@Override
public void run() {
try {
Charset charset = ScriptHelper.encoding == null ? null : ScriptHelper.encoding.charset();
FileOutputStream fiout = new FileOutputStream(fileObj);
OutputStreamWriter writer;
if (charset == null) {
writer = new OutputStreamWriter(fiout);
}
else {
writer = new OutputStreamWriter(fiout, charset);
}
writer.write(outp);
writer.close();
}
catch (IOException e) {
Debug.echoError(e);
}
scriptEntry.setFinished(true);
}
};
if (scriptEntry.shouldWaitFor()) {
DenizenCore.schedule(new AsyncSchedulable(new OneTimeSchedulable(saveRunnable, 0)));
}
else {
saveRunnable.run();
}
}
catch (IOException e) {
Debug.echoError(e);
}
}
else {
Debug.echoError("Unknown YAML ID '" + id + "'");
scriptEntry.setFinished(true);
}
break;
case COPYKEY: {
if (!yamls.containsKey(id)) {
break;
}
YamlConfiguration yaml = yamls.get(id);
YamlConfiguration destYaml = yaml;
if (toId != null) {
if (yamls.containsKey(toId.toString().toUpperCase())) {
destYaml = yamls.get(toId.toString().toUpperCase());
}
else {
Debug.echoError("Unknown YAML TO-ID '" + id + "'");
break;
}
}
YamlConfiguration sourceSection = yaml.getConfigurationSection(key.asString());
if (sourceSection == null) {
Debug.echoError("Invalid YAML section key name '" + key.asString() + "'.");
break;
}
YamlConfiguration newSection = copySection(sourceSection);
destYaml.set(value.toString(), newSection);
break;
}
case SET:
if (yamls.containsKey(id)) {
if (yaml_action == null || key == null || value == null) {
Debug.echoError("Must specify a YAML action and value!");
return;
}
YamlConfiguration yaml = yamls.get(id);
int index = -1;
if (key.asString().contains("[")) {
try {
if (Debug.verbose) {
Debug.echoDebug(scriptEntry, "Try index: " + key.asString().split("\\[")[1].replace("]", ""));
}
index = Integer.valueOf(key.asString().split("\\[")[1].replace("]", "")) - 1;
}
catch (Exception e) {
if (Debug.verbose) {
Debug.echoError(scriptEntry.getResidingQueue(), e);
}
index = -1;
}
key = ElementTag.valueOf(key.asString().split("\\[")[0]);
}
String keyStr = key.asString();
String valueStr = value.identify();
switch (yaml_action) {
case INCREASE: {
String originalVal = Get(yaml, index, keyStr, "0");
if (!ArgumentHelper.matchesDouble(originalVal)) {
originalVal = "0";
}
if (!ArgumentHelper.matchesDouble(valueStr)) {
Debug.echoError("YAML action required a decimal number, was given not-a-decimal-number: " + valueStr);
return;
}
Set(yaml, index, keyStr, CoreUtilities.doubleToString(Double.parseDouble(originalVal) + Double.parseDouble(valueStr)));
break;
}
case DECREASE: {
String originalVal = Get(yaml, index, keyStr, "0");
if (!ArgumentHelper.matchesDouble(originalVal)) {
originalVal = "0";
}
if (!ArgumentHelper.matchesDouble(valueStr)) {
Debug.echoError("YAML action required a decimal number, was given not-a-decimal-number: " + valueStr);
return;
}
Set(yaml, index, keyStr, CoreUtilities.doubleToString(Double.parseDouble(originalVal) - Double.parseDouble(valueStr)));
break;
}
case MULTIPLY: {
String originalVal = Get(yaml, index, keyStr, "1");
if (!ArgumentHelper.matchesDouble(originalVal)) {
originalVal = "0";
}
if (!ArgumentHelper.matchesDouble(valueStr)) {
Debug.echoError("YAML action required a decimal number, was given not-a-decimal-number: " + valueStr);
return;
}
Set(yaml, index, keyStr, CoreUtilities.doubleToString(Double.parseDouble(originalVal) * Double.parseDouble(valueStr)));
break;
}
case DIVIDE: {
String originalVal = Get(yaml, index, keyStr, "1");
if (!ArgumentHelper.matchesDouble(originalVal)) {
originalVal = "0";
}
if (!ArgumentHelper.matchesDouble(valueStr)) {
Debug.echoError("YAML action required a decimal number, was given not-a-decimal-number: " + valueStr);
return;
}
Set(yaml, index, keyStr, CoreUtilities.doubleToString(Double.parseDouble(originalVal) / Double.parseDouble(valueStr)));
break;
}
case DELETE:
yaml.set(keyStr, null);
break;
case SET_VALUE:
Set(yaml, index, keyStr, valueStr);
break;
case INSERT: {
List<String> list = yaml.getStringList(keyStr);
if (list == null) {
list = new ArrayList<>();
}
list.add(valueStr);
yaml.set(keyStr, list);
break;
}
case REMOVE: {
List<String> list = yaml.getStringList(keyStr);
if (list == null) {
if (Debug.verbose) {
Debug.echoDebug(scriptEntry, "List null!");
}
break;
}
if (index > -1 && index < list.size()) {
if (Debug.verbose) {
Debug.echoDebug(scriptEntry, "Remove ind: " + index);
}
list.remove(index);
yaml.set(keyStr, list);
}
else {
if (Debug.verbose) {
Debug.echoDebug(scriptEntry, "Remvoe value: " + valueStr);
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equalsIgnoreCase(valueStr)) {
list.remove(i);
break;
}
}
yaml.set(keyStr, list);
break;
}
break;
}
case SPLIT_NEW: {
yaml.set(keyStr, new ArrayList<>(ListTag.valueOf(valueStr)));
break;
}
case SPLIT: {
List<String> list = yaml.getStringList(keyStr);
if (list == null) {
list = new ArrayList<>();
}
list.addAll(ListTag.valueOf(valueStr));
yaml.set(keyStr, list);
break;
}
}
}
else {
Debug.echoError("Unknown YAML ID '" + id + "'");
}
break;
case CREATE:
yamls.remove(id);
yamlConfiguration = new YamlConfiguration();
yamls.put(id.toUpperCase(), yamlConfiguration);
break;
}
}
public YamlConfiguration copySection(YamlConfiguration section) {
YamlConfiguration newSection = new YamlConfiguration();
for (StringHolder key : section.getKeys(false)) {
Object obj = section.get(key.str);
if (obj instanceof YamlConfiguration) {
obj = copySection((YamlConfiguration) obj);
}
newSection.set(key.str, obj);
}
return newSection;
}
public String Get(YamlConfiguration yaml, int index, String key, String def) {
if (index == -1) {
return yaml.getString(key, def);
}
else {
List<String> list = yaml.getStringList(key);
if (index < 0) {
index = 0;
}
if (index > list.size()) {
index = list.size() - 1;
}
if (list.size() == 0) {
return "";
}
return list.get(index);
}
}
public void Set(YamlConfiguration yaml, int index, String key, String value) {
if (index == -1) {
yaml.set(key, value);
}
else {
List<String> list = yaml.getStringList(key);
if (list == null) {
list = new ArrayList<>();
}
if (index < 0) {
index = 0;
}
if (index >= list.size()) {
list.add(value);
}
else {
list.set(index, value);
}
yaml.set(key, list);
}
}
public void yaml(ReplaceableTagEvent event) {
if (!event.matches("yaml")) {
return;
}
Attribute attribute = event.getAttributes();
// <--[tag]
// @attribute <yaml.list>
// @returns ListTag
// @description
// Returns a list of all currently loaded YAML ID's.
// -->
if (attribute.getAttribute(2).equalsIgnoreCase("list")) {
ListTag list = new ListTag();
list.addAll(yamls.keySet());
event.setReplaced(list.getAttribute(attribute.fulfill(2)));
return;
}
String id = attribute.getContext(1).toUpperCase();
// Check if there is a yaml file loaded with the specified id
if (!yamls.containsKey(id)) {
if (!attribute.hasAlternative()) {
Debug.echoError("YAML tag '" + event.raw_tag + "' has specified an invalid ID, or the specified id has already" +
" been closed. Tag replacement aborted. ID given: '" + id + "'.");
}
return;
}
// Catch up with what has already been processed.
attribute.fulfill(1);
//
// Check attributes
//
// <--[tag]
// @attribute <yaml[<id>].contains[<path>]>
// @returns ElementTag(Boolean)
// @description
// Returns true if the file has the specified path.
// Otherwise, returns false.
// -->
if (attribute.startsWith("contains") && attribute.hasContext(1)) {
event.setReplaced(new ElementTag(getYaml(id).contains(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1)));
return;
}
// <--[tag]
// @attribute <yaml[<id>].is_list[<path>]>
// @returns ElementTag(Boolean)
// @description
// Returns true if the specified path results in a list.
// -->
if (attribute.startsWith("is_list") && attribute.hasContext(1)) {
event.setReplaced(new ElementTag(getYaml(id).isList(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1)));
return;
}
// <--[tag]
// @attribute <yaml[<id>].read[<path>]>
// @returns ElementTag
// @description
// Returns the value of the key at the path.
// If the key is a list, returns a ListTag instead.
// -->
if (attribute.startsWith("read") && attribute.hasContext(1)) {
if (getYaml(id).isList(attribute.getContext(1))) {
List<String> value = getYaml(id).getStringList(attribute.getContext(1));
if (value == null) {
// If value is null, the key at the specified path didn't exist.
return;
}
else {
event.setReplaced(new ListTag(value).getAttribute(attribute.fulfill(1)));
return;
}
}
else {
String value = getYaml(id).getString(attribute.getContext(1));
if (value == null) {
// If value is null, the key at the specified path didn't exist.
return;
}
else {
event.setReplaced(new ElementTag(value).getAttribute(attribute.fulfill(1)));
return;
}
}
}
// <--[tag]
// @attribute <yaml[<id>].list_deep_keys[<path>]>
// @returns ListTag
// @description
// Returns a ListTag of all the keys at the path and all subpaths.
// -->
if (attribute.startsWith("list_deep_keys") && attribute.hasContext(1)) {
Set<StringHolder> keys;
String path = attribute.getContext(1);
if (path != null && path.length() > 0) {
YamlConfiguration section = getYaml(id).getConfigurationSection(path);
if (section == null) {
return;
}
keys = section.getKeys(true);
}
else {
keys = getYaml(id).getKeys(true);
}
if (keys == null) {
return;
}
else {
event.setReplaced(new ListTag(keys).getAttribute(attribute.fulfill(1)));
return;
}
}
// <--[tag]
// @attribute <yaml[<id>].list_keys[<path>]>
// @returns ListTag
// @description
// Returns a ListTag of all the keys at the path.
// -->
if (attribute.startsWith("list_keys") && attribute.hasContext(1)) {
Set<StringHolder> keys;
String path = attribute.getContext(1);
if (path != null && path.length() > 0) {
YamlConfiguration section = getYaml(id).getConfigurationSection(path);
if (section == null) {
return;
}
keys = section.getKeys(false);
}
else {
keys = getYaml(id).getKeys(false);
}
if (keys == null) {
return;
}
else {
event.setReplaced(new ListTag(keys).getAttribute(attribute.fulfill(1)));
return;
}
}
// <--[tag]
// @attribute <yaml[<id>].to_json>
// @returns ElementTag
// @description
// Converts the YAML container to a JSON array.
// -->
if (attribute.startsWith("to_json")) {
JSONObject jsobj = new JSONObject(getYaml(id).getMap());
event.setReplaced(new ElementTag(jsobj.toString()).getAttribute(attribute.fulfill(1)));
return;
}
// <--[tag]
// @attribute <yaml[<id>].to_text>
// @returns ElementTag
// @description
// Converts the YAML container to raw YAML text.
// -->
if (attribute.startsWith("to_text")) {
event.setReplaced(new ElementTag(getYaml(id).saveToString(false)).getAttribute(attribute.fulfill(1)));
return;
}
}
}