-
-
Notifications
You must be signed in to change notification settings - Fork 30
/
YamlCommand.java
873 lines (839 loc) · 39.8 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
873
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.objects.core.MapTag;
import com.denizenscript.denizencore.scripts.commands.AbstractCommand;
import com.denizenscript.denizencore.scripts.commands.Holdable;
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.TagManager;
import org.json.JSONObject;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.function.Consumer;
public class YamlCommand extends AbstractCommand implements Holdable {
public YamlCommand() {
setName("yaml");
setSyntax("yaml [create]/[load:<file>]/[loadtext:<text>]/[unload]/[savefile:<file>]/[copykey:<source_key> <target_key> (to_id:<name>)]/[set <key>([<#>])(:<action>):<value>] [id:<name>]");
setRequiredArguments(2, 4);
TagManager.registerTagHandler("yaml", this::yamlTagProcess);
isProcedural = false;
}
// <--[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
// @Maximum 4
// @Short Edits YAML data, especially for YAML files.
// @Group file
//
// @Description
// Edits YAML configuration data.
//
// This commands exists primarily for interoperability with pre-existing data files and other plugins.
// It should never be used for storing data that only Denizen needs to use. Consider instead using <@link command flag>.
//
// Use waitable syntax ("- ~yaml load:...") with load or savefile actions to avoid locking up the server during file IO.
// Refer to <@link language ~waitable>.
//
// For loading and saving, the starting path is within 'plugins/Denizen'.
// The file path follows standard system file path rules. That means '/' separators folders,
// and '..' as a folder name means go-up-one folder, for example '../WorldGuard/config.yml' would load the WorldGuard plugin config.
// Also be aware that some servers (Linux/Mac based) have case sensitive file systems while others (Windows based) don't.
// Generally, when using existing paths, make sure your casing is correct. When creating new paths, prefer all-lowercase to reduce risk of issues.
//
// 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.
//
// In-memory changes to a loaded YAML object will mark that object as having changes. Before saving,
// you can check whether the YAML object needs to be written to disk with the has_changes tag.
//
// 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>]>
// <yaml[<idname>].has_changes>
//
// @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
// -->
public Map<String, YamlConfiguration> yamlDocuments = new HashMap<>();
private YamlConfiguration getYaml(String id) {
if (id == null) {
Debug.echoError("Trying to get YAML file with NULL ID!");
return null;
}
return yamlDocuments.get(CoreUtilities.toLowerCase(id));
}
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 addCustomTabCompletions(String arg, Consumer<String> addOne) {
if (arg.startsWith("id:")) {
for (String yaml : yamlDocuments.keySet()) {
addOne.accept("id:" + yaml);
}
}
}
@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());
isCopyKey = true;
}
else if (!scriptEntry.hasObject("action") &&
arg.matches("unload")) {
scriptEntry.addObject("action", new ElementTag("UNLOAD"));
}
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")) {
Deprecations.yamlFixFormatting.warn(scriptEntry);
}
// Check for key:value/action
else if (isSet &&
!scriptEntry.hasObject("value")) {
if (!arg.canBeElement) {
scriptEntry.addObject("yaml_action", YAML_Action.SET_VALUE);
scriptEntry.addObject("key", new ElementTag(arg.prefix));
scriptEntry.addObject("value", arg.object);
}
else {
int split = arg.getRawValue().split(":", 3).length;
if (split == 2) {
String[] flagArgs = arg.getRawValue().split(":", 2);
scriptEntry.addObject("key", new ElementTag(flagArgs[0]));
switch (flagArgs[1]) {
case "++":
case "+":
scriptEntry.addObject("yaml_action", YAML_Action.INCREASE);
scriptEntry.addObject("value", new ElementTag(1));
break;
case "--":
case "-":
scriptEntry.addObject("yaml_action", YAML_Action.DECREASE);
scriptEntry.addObject("value", new ElementTag(1));
break;
case "!":
scriptEntry.addObject("yaml_action", YAML_Action.DELETE);
scriptEntry.addObject("value", new ElementTag(false));
break;
case "<-":
scriptEntry.addObject("yaml_action", YAML_Action.REMOVE);
scriptEntry.addObject("value", new ElementTag(false));
break;
default:
// No ACTION, we're just setting a value...
scriptEntry.addObject("yaml_action", YAML_Action.SET_VALUE);
scriptEntry.addObject("value", new ElementTag(flagArgs[1]));
break;
}
}
else if (split == 3) {
String[] flagArgs = arg.getRawValue().split(":", 3);
scriptEntry.addObject("key", new ElementTag(flagArgs[0]));
switch (flagArgs[1]) {
case "->":
scriptEntry.addObject("yaml_action", YAML_Action.INSERT);
break;
case "<-":
scriptEntry.addObject("yaml_action", YAML_Action.REMOVE);
break;
case "||":
case "|":
scriptEntry.addObject("yaml_action", YAML_Action.SPLIT);
break;
case "!|":
scriptEntry.addObject("yaml_action", YAML_Action.SPLIT_NEW);
break;
case "++":
case "+":
scriptEntry.addObject("yaml_action", YAML_Action.INCREASE);
break;
case "--":
case "-":
scriptEntry.addObject("yaml_action", YAML_Action.DECREASE);
break;
case "**":
case "*":
scriptEntry.addObject("yaml_action", YAML_Action.MULTIPLY);
break;
case "//":
case "/":
scriptEntry.addObject("yaml_action", YAML_Action.DIVIDE);
break;
default:
scriptEntry.addObject("yaml_action", YAML_Action.SET_VALUE);
scriptEntry.addObject("value", new ElementTag(arg.getRawValue().split(":", 2)[1]));
continue;
}
scriptEntry.addObject("value", new ElementTag(flagArgs[2]));
}
else {
arg.reportUnhandled();
}
}
}
else if (isCopyKey && !scriptEntry.hasObject("value")) {
scriptEntry.addObject("value", arg.asElement());
}
else {
arg.reportUnhandled();
}
}
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(""));
}
@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 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());
final String id = CoreUtilities.toLowerCase(idElement.asString());
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 = () -> {
yamlDocuments.remove(id);
yamlDocuments.put(id, runnableConfigs[0]);
scriptEntry.setFinished(true);
};
Runnable loadRunnable = () -> {
try {
FileInputStream fis = new FileInputStream(file);
String str = ScriptHelper.convertStreamToString(fis);
fis.close();
runnableConfigs[0] = YamlConfiguration.load(str);
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);
yamlDocuments.remove(id);
yamlDocuments.put(id, config);
scriptEntry.setFinished(true);
break;
case UNLOAD:
if (yamlDocuments.containsKey(id)) {
yamlDocuments.remove(id);
}
else {
Debug.echoError("Unknown YAML ID '" + id + "'");
}
break;
case SAVE:
if (yamlDocuments.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();
YamlConfiguration yaml = yamlDocuments.get(id);
String outp = yaml.saveToString(false);
yaml.setDirty(false);
Runnable saveRunnable = () -> {
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 (!yamlDocuments.containsKey(id)) {
break;
}
YamlConfiguration yaml = yamlDocuments.get(id);
YamlConfiguration destYaml = yaml;
if (toId != null) {
destYaml = getYaml(toId.toString());
if (destYaml == null) {
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 (yamlDocuments.containsKey(id)) {
if (yaml_action == null || key == null || value == null) {
Debug.echoError("Must specify a YAML action, key, and value!");
return;
}
YamlConfiguration yaml = yamlDocuments.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 = new ElementTag(key.asString().split("\\[")[0]);
}
String keyStr = key.asString();
String valueStr = yaml_action == YAML_Action.SET_VALUE ? null : 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, value);
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, scriptEntry.getContext())));
break;
}
case SPLIT: {
List<String> list = yaml.getStringList(keyStr);
if (list == null) {
list = new ArrayList<>();
}
list.addAll(ListTag.valueOf(valueStr, scriptEntry.getContext()));
yaml.set(keyStr, list);
break;
}
}
}
else {
Debug.echoError("Unknown YAML ID '" + id + "'");
}
break;
case CREATE:
yamlDocuments.remove(id);
yamlConfiguration = new YamlConfiguration();
yamlDocuments.put(id, yamlConfiguration);
break;
}
}
public Object deepCopyObject(Object obj) {
if (obj == null) {
return null;
}
if (obj instanceof YamlConfiguration) {
return copySection((YamlConfiguration) obj);
}
else if (obj instanceof List) {
ArrayList outList = new ArrayList(((List) obj).size());
for (Object subValue : (List) obj) {
outList.add(deepCopyObject(subValue));
}
return outList;
}
else if (obj instanceof Map) {
LinkedHashMap newMap = new LinkedHashMap();
for (Map.Entry<Object, Object> entry : ((Map<Object, Object>) obj).entrySet()) {
newMap.put(deepCopyObject(entry.getKey()), deepCopyObject(entry.getValue()));
}
return newMap;
}
return obj;
}
public YamlConfiguration copySection(YamlConfiguration section) {
YamlConfiguration newSection = new YamlConfiguration();
for (StringHolder key : section.getKeys(false)) {
Object obj = section.get(key.str);
newSection.set(key.str, deepCopyObject(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.isEmpty()) {
return "";
}
return list.get(index);
}
}
public void Set(YamlConfiguration yaml, int index, String key, Object value) {
if (index == -1) {
if (value instanceof MapTag || ((value instanceof ElementTag || value instanceof String) && value.toString().startsWith("map@"))) {
MapTag map = value instanceof MapTag ? (MapTag) value : MapTag.valueOf(value.toString(), CoreUtilities.noDebugContext);
if (map != null) {
yaml.set(key, CoreUtilities.objectTagToJavaForm(map, true));
return;
}
}
yaml.set(key, value.toString());
}
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.toString());
}
else {
list.set(index, value.toString());
}
yaml.set(key, list);
}
}
public ObjectTag yamlTagProcess(Attribute attribute) {
String id = attribute.hasContext(1) ? CoreUtilities.toLowerCase(attribute.getContext(1)) : null;
attribute.fulfill(1);
// <--[tag]
// @attribute <yaml.list>
// @returns ListTag
// @description
// Returns a list of all currently loaded YAML ID's.
// -->
if (attribute.startsWith("list")) {
ListTag list = new ListTag();
list.addAll(yamlDocuments.keySet());
return list;
}
if (id == null) {
attribute.echoError("yaml[...] tag must specify a YAML id.");
return null;
}
YamlConfiguration yaml = getYaml(id);
if (yaml == null) {
attribute.echoError("YAML tag has specified an invalid ID, or the specified id has already been closed. Tag replacement aborted. ID given: '" + id + "'.");
return null;
}
// <--[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)) {
return new ElementTag(yaml.contains(attribute.getContext(1)));
}
// <--[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)) {
return new ElementTag(yaml.isList(attribute.getContext(1)));
}
// <--[tag]
// @attribute <yaml[<id>].parsed_key[<path>]>
// @returns ElementTag
// @description
// Returns the value from a data key on the YAML document as an ElementTag, ListTag, or MapTag.
// Will automatically parse any tags contained within the value of the key, preserving key data structure
// (meaning, a tag that returns a ListTag, inside a data list, will insert a ListTag inside the returned ListTag, as you would expect).
// Generally, prefer to use <@link tag yaml.read>.
// -->
if (attribute.startsWith("parsed_key") && attribute.hasContext(1)) {
Object obj = yaml.get(attribute.getContext(1));
if (obj == null) {
return null;
}
return CoreUtilities.objectToTagForm(obj, attribute.context, false, true);
}
// <--[tag]
// @attribute <yaml[<id>].read[<path>]>
// @returns ElementTag
// @description
// Returns the value from a data key on the YAML document as an ElementTag, ListTag, or MapTag.
// -->
if (attribute.startsWith("read") && attribute.hasContext(1)) {
Object obj = yaml.get(attribute.getContext(1));
if (obj == null) {
return null;
}
return CoreUtilities.objectToTagForm(obj, attribute.context);
}
// <--[tag]
// @attribute <yaml[<id>].list_deep_keys[<path>]>
// @returns ListTag
// @description
// Returns a ListTag of all the keys at the path and all subpaths.
// Use empty path input to represent the root of the yaml document tree.
// -->
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 = yaml.getConfigurationSection(path);
if (section == null) {
return null;
}
keys = section.getKeys(true);
}
else {
keys = yaml.getKeys(true);
}
if (keys == null) {
return null;
}
else {
return new ListTag(keys);
}
}
// <--[tag]
// @attribute <yaml[<id>].list_keys[<path>]>
// @returns ListTag
// @description
// Returns a ListTag of all the keys at the path (and not sub-keys).
// Use empty path input to represent the root of the yaml document tree.
// -->
if (attribute.startsWith("list_keys") && attribute.hasContext(1)) {
Set<StringHolder> keys;
String path = attribute.getContext(1);
if (path != null && path.length() > 0) {
YamlConfiguration section = yaml.getConfigurationSection(path);
if (section == null) {
return null;
}
keys = section.getKeys(false);
}
else {
keys = yaml.getKeys(false);
}
if (keys == null) {
return null;
}
else {
return new ListTag(keys);
}
}
// <--[tag]
// @attribute <yaml[<id>].has_changes>
// @returns ElementTag(Boolean)
// @description
// Returns whether this YAML object has had changes since the last save or load.
// -->
if (attribute.startsWith("has_changes")) {
return new ElementTag(yaml.isDirty());
}
// <--[tag]
// @attribute <yaml[<id>].to_json>
// @returns ElementTag
// @description
// Converts the YAML container to a JSON array.
// -->
if (attribute.startsWith("to_json")) {
return new ElementTag(new JSONObject(yaml.getMap()).toString());
}
// <--[tag]
// @attribute <yaml[<id>].to_text>
// @returns ElementTag
// @description
// Converts the YAML container to raw YAML text.
// -->
if (attribute.startsWith("to_text")) {
return new ElementTag(yaml.saveToString(false));
}
return null;
}
}