forked from sarbian/ModuleManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmoduleManager.cs
More file actions
1385 lines (1211 loc) · 55.8 KB
/
moduleManager.cs
File metadata and controls
1385 lines (1211 loc) · 55.8 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using KSP;
using UnityEngine;
namespace ModuleManager
{
// Once MUST be true for the election process to work when 2+ dll of the same version are loaded
// But I need it to be false for the reload database thingy
[KSPAddon(KSPAddon.Startup.EveryScene, false)]
public class ConfigManager : MonoBehaviour
{
#region state
private bool loaded = false;
private bool inRnDCenter = false;
private int patchCount = 0;
private int errorCount = 0;
private int needsUnsatisfiedCount = 0;
private Dictionary<String, int> errorFiles;
private List<AssemblyName> mods;
private string status = "Processing Module Manager patch\nPlease Wait...";
private string errors = "";
public bool showUI = false;
private Rect windowPos = new Rect(80f, 60f, 240f, 40f);
#endregion
#region Top Level - Update
private static bool loadedInScene = false;
internal void OnRnDCenterSpawn()
{
inRnDCenter = true;
}
internal void OnRnDCenterDespawn()
{
inRnDCenter = false;
}
internal void Awake()
{
// Ensure that only one copy of the service is run per scene change.
if (loadedInScene)
{
Assembly currentAssembly = Assembly.GetExecutingAssembly();
log("[ModuleManager] Multiple copies of current version. Using the first copy. Version: " + currentAssembly.GetName().Version);
Destroy(gameObject);
return;
}
// Subscrive to the RnD center spawn/despawn events
GameEvents.onGUIRnDComplexSpawn.Add(OnRnDCenterSpawn);
GameEvents.onGUIRnDComplexDespawn.Add(OnRnDCenterDespawn);
Update();
loadedInScene = true;
}
// Unsubscribe from events when the behavior dies
internal void OnDestroy()
{
GameEvents.onGUIRnDComplexSpawn.Remove(OnRnDCenterSpawn);
GameEvents.onGUIRnDComplexDespawn.Remove(OnRnDCenterDespawn);
}
public void Update()
{
// Unset the loadedInScene flag. All the other copies will have this sorted out during Start, so safe to do here.
loadedInScene = false;
if (GameSettings.MODIFIER_KEY.GetKey() && Input.GetKeyDown(KeyCode.F11))
{
showUI = !showUI;
}
#region Initialization
/*
* It should be a code to reload when the Reload Database debug button is used.
* But it seem to go balistic after the 2nd reload.
*
if (PartLoader.Instance.Recompile == waitingReload)
{
waitingReload = !waitingReload;
print("[ModuleManager] waitingReload change " + waitingReload + " loaded " + loaded);
if (!waitingReload)
{
loaded = false;
print("[ModuleManager] loaded = false ");
}
}
*/
if (!GameDatabase.Instance.IsReady() && ((HighLogic.LoadedScene == GameScenes.MAINMENU) || (HighLogic.LoadedScene == GameScenes.SPACECENTER)))
{
return;
}
if (loaded || PartLoader.Instance.IsReady())
return;
patchCount = 0;
errorCount = 0;
needsUnsatisfiedCount = 0;
errorFiles = new Dictionary<string, int>();
#endregion
#region Type election
// Check for old version and MMSarbianExt
var oldMM = AssemblyLoader.loadedAssemblies.Where(a => a.assembly.GetName().Name == Assembly.GetExecutingAssembly().GetName().Name).Where(a => a.assembly.GetName().Version.CompareTo(new System.Version(1, 5, 0)) == -1);
var oldAssemblies = oldMM.Concat(AssemblyLoader.loadedAssemblies.Where(a => a.assembly.GetName().Name == "MMSarbianExt"));
if (oldAssemblies.Any())
{
var badPaths = oldAssemblies.Select(a => a.path).Select(p => Uri.UnescapeDataString(new Uri(Path.GetFullPath(KSPUtil.ApplicationRootPath)).MakeRelativeUri(new Uri(p)).ToString().Replace('/', Path.DirectorySeparatorChar)));
status = "You have old versions of Module Manager (older than 1.5) or MMSarbianExt.\nYou will need to remove them for Module Manager and the mods using it to work\nExit KSP and delete those files :\n" + String.Join("\n", badPaths.ToArray());
PopupDialog.SpawnPopupDialog("Old versions of Module Manager", status, "OK", false, HighLogic.Skin);
loaded = true;
print("[ModuleManager] Old version of Module Manager present. Stopping");
return;
}
Assembly currentAssembly = Assembly.GetExecutingAssembly();
var eligible = from a in AssemblyLoader.loadedAssemblies
let ass = a.assembly
where ass.GetName().Name == currentAssembly.GetName().Name
orderby ass.GetName().Version descending, a.path ascending
select a;
// Elect the newest loaded version of MM to process all patch files.
// If there is a newer version loaded then don't do anything
// If there is a same version but earlier in the list, don't do anything either.
if (eligible.First().assembly != currentAssembly)
{
loaded = true;
print("[ModuleManager] version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location + " lost the election");
Destroy(gameObject);
return;
}
else
{
string candidates = "";
foreach (AssemblyLoader.LoadedAssembly a in eligible)
if (currentAssembly.Location != a.path)
candidates += "Version " + a.assembly.GetName().Version + " " + a.path + " " + "\n";
if (candidates.Length > 0)
print("[ModuleManager] version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location + " won the election against\n" + candidates);
}
#endregion
#region Excluding directories
// Build a list of subdirectory that won't be processed
List<String> excludePaths = new List<string>();
foreach (UrlDir.UrlConfig mod in GameDatabase.Instance.root.AllConfigs)
{
if (mod.name == "MODULEMANAGER[LOCAL]")
{
string fullpath = mod.url.Substring(0, mod.url.LastIndexOf('/'));
string excludepath = fullpath.Substring(0, fullpath.LastIndexOf('/'));
excludePaths.Add(excludepath);
print("excludepath: " + excludepath);
}
}
if (excludePaths.Any())
print("[ModuleManager] will not procces patch in these subdirectories:\n" + String.Join("\n", excludePaths.ToArray()));
#endregion
#region List of mods
List<AssemblyName> modsWithDup = AssemblyLoader.loadedAssemblies.Select(a => (a.assembly.GetName())).ToList();
mods = new List<AssemblyName>();
foreach (AssemblyName a in modsWithDup)
{
if (!mods.Any(m => m.Name == a.Name))
mods.Add(a);
}
string modlist = "compiling list of loaded mods...\nMod DLLs found:\n";
foreach (AssemblyName mod in mods)
{
modlist += " " + mod.Name + " v" + mod.Version.ToString() + "\n";
}
modlist += "Non-DLL mods added:\n";
foreach (UrlDir.UrlConfig cfgmod in GameDatabase.Instance.root.AllConfigs)
{
string name;
if (ParseCommand(cfgmod.type, out name) != Command.Insert && name.Contains(":FOR["))
{
name = RemoveWS(name);
// check for FOR[] blocks that don't match loaded DLLs and add them to the pass list
try
{
string dependency = name.Substring(name.IndexOf(":FOR[") + 5);
dependency = dependency.Substring(0, dependency.IndexOf(']'));
if (mods.Find(a => RemoveWS(a.Name.ToUpper()).Equals(RemoveWS(dependency.ToUpper()))) == null)
{ // found one, now add it to the list.
AssemblyName newMod = new AssemblyName(dependency);
newMod.Name = dependency;
mods.Add(newMod);
modlist += " " + dependency + "\n";
}
}
catch (ArgumentOutOfRangeException)
{
print("[ModuleManager] Skipping :FOR init for line " + name + ". The line most likely contain a space that should be removed");
}
}
}
modlist += "Mods by directory (subdirs of GameData):\n";
string gameData = Path.Combine(Path.GetFullPath(KSPUtil.ApplicationRootPath), "GameData");
foreach (string subdir in Directory.GetDirectories(gameData))
{
string name = Path.GetFileName(subdir);
string upperName = RemoveWS(name.ToUpper());
if (mods.Find(a => RemoveWS(a.Name.ToUpper()) == upperName) == null)
{
AssemblyName newMod = new AssemblyName(name);
newMod.Name = name;
mods.Add(newMod);
modlist += " " + name + "\n";
}
}
log(modlist);
#endregion
#region Check Needs
// Do filtering with NEEDS
print("[ModuleManager] Checking NEEDS.");
CheckNeeds(excludePaths);
#endregion
#region Applying patches
// :First node (and any node without a :pass)
ApplyPatch(excludePaths, ":FIRST");
foreach (AssemblyName mod in mods)
{
string upperModName = mod.Name.ToUpper();
ApplyPatch(excludePaths, ":BEFORE[" + upperModName + "]");
ApplyPatch(excludePaths, ":FOR[" + upperModName + "]");
ApplyPatch(excludePaths, ":AFTER[" + upperModName + "]");
}
// :Final node
ApplyPatch(excludePaths, ":FINAL");
PurgeUnused(excludePaths);
#endregion
#region Logging
if (errorCount > 0)
foreach (String file in errorFiles.Keys)
errors += errorFiles[file] + " error" + (errorFiles[file] > 1 ? "s" : "") + " in GameData/" + file + "\n";
status = "ModuleManager: "
+ patchCount + " patch" + (patchCount != 1 ? "es" : "") + " applied"
+ ", "
+ needsUnsatisfiedCount + " hidden item" + (needsUnsatisfiedCount != 1 ? "s" : "");
if (errorCount > 0)
status += ", found " + errorCount + " error" + (errorCount != 1 ? "s" : "");
print("[ModuleManager] " + status + "\n" + errors);
loaded = true;
#endregion
#if DEBUG
RunTestCases();
#endif
}
#endregion
#region Needs checking
private void CheckNeeds(List<String> excludePaths)
{
// Check the NEEDS parts first.
foreach (UrlDir.UrlConfig mod in GameDatabase.Instance.root.AllConfigs.ToArray())
{
try
{
if (IsPathInList(mod.url, excludePaths))
continue;
if (mod.type.Contains(":NEEDS["))
{
mod.parent.configs.Remove(mod);
string type = mod.type;
if (!CheckNeeds(ref type))
{
print("[ModuleManager] Deleting Node in file " + mod.parent.url + " subnode: " + mod.type + " as it can't satisfy its NEEDS");
needsUnsatisfiedCount++;
continue;
}
ConfigNode copy = new ConfigNode(type);
ShallowCopy(mod.config, copy);
mod.parent.configs.Add(new UrlDir.UrlConfig(mod.parent, copy));
}
// Recursivly check the contents
CheckNeeds(mod.config, mod.parent.url, new List<string>() { mod.type });
}
catch (Exception ex)
{
print("[ModuleManager] Exception while checking needs : " + mod.url + "\n" + ex.ToString());
}
}
}
private void CheckNeeds(ConfigNode subMod, string url, List<string> path)
{
try
{
path.Add(subMod.name + "[" + subMod.GetValue("name") + "]");
bool needsCopy = false;
ConfigNode copy = new ConfigNode();
for (int i = 0; i < subMod.values.Count; ++i)
{
ConfigNode.Value val = subMod.values[i];
string name = val.name;
if (CheckNeeds(ref name))
copy.AddValue(name, val.value);
else
{
needsCopy = true;
print("[ModuleManager] Deleting value in file: " + url + " subnode: " + string.Join("/", path.ToArray()) + " value: " + val.name + " = " + val.value + " as it can't satisfy its NEEDS");
needsUnsatisfiedCount++;
}
}
for (int i = 0; i < subMod.nodes.Count; ++i)
{
ConfigNode node = subMod.nodes[i];
string name = node.name;
if (CheckNeeds(ref name))
{
node.name = name;
CheckNeeds(node, url, path);
copy.AddNode(node);
}
else
{
needsCopy = true;
print("[ModuleManager] Deleting node in file: " + url + " subnode: " + string.Join("/", path.ToArray()) + "/" + node.name + " as it can't satisfy its NEEDS");
needsUnsatisfiedCount++;
}
}
if (needsCopy)
ShallowCopy(copy, subMod);
}
finally
{
path.RemoveAt(path.Count - 1);
}
}
/// <summary>
/// Returns true if needs are satisfied.
/// </summary>
private bool CheckNeeds(ref string name)
{
if (name == null)
return true;
int idxStart = name.IndexOf(":NEEDS[");
if (idxStart < 0)
return true;
int idxEnd = name.IndexOf(']', idxStart + 7);
string needsString = name.Substring(idxStart + 7, idxEnd - idxStart - 7).ToUpper();
name = name.Substring(0, idxStart) + name.Substring(idxEnd + 1);
// Check to see if all the needed dependencies are present.
foreach (string andDependencies in needsString.Split(',', '&'))
{
bool orMatch = false;
foreach (string orDependency in andDependencies.Split('|'))
{
if (orDependency.Length == 0)
continue;
bool not = orDependency[0] == '!';
string toFind = not ? orDependency.Substring(1) : orDependency;
bool found = mods.Find(a => a.Name.ToUpper() == toFind) != null;
if (not == !found)
{
orMatch = true;
break;
}
}
if (!orMatch)
return false;
}
return true;
}
private void PurgeUnused(List<string> excludePaths)
{
foreach (UrlDir.UrlConfig mod in GameDatabase.Instance.root.AllConfigs.ToArray())
{
if (IsPathInList(mod.url, excludePaths))
continue;
string name = RemoveWS(mod.type);
if (ParseCommand(name, out name) != Command.Insert)
mod.parent.configs.Remove(mod);
}
}
#endregion
#region Applying Patches
// Apply patch to all relevent nodes
public void ApplyPatch(List<String> excludePaths, string Stage)
{
print("[ModuleManager] " + Stage + (Stage == ":FIRST" ? " (default) pass" : " pass"));
foreach (UrlDir.UrlConfig mod in GameDatabase.Instance.root.AllConfigs.ToArray())
{
int lastErrorCount = errorCount;
try
{
string name = RemoveWS(mod.type);
string tmp;
Command cmd = ParseCommand(name, out tmp);
if (cmd != Command.Insert)
{
if (!IsBraquetBalanced(mod.type))
{
print("[ModuleManager] Skipping a patch with unbalanced square brackets or a space (replace them with a '?') :\n" + mod.name + "\n");
errorCount++;
// And remove it so it's not tried anymore
mod.parent.configs.Remove(mod);
continue;
}
// Ensure the stage is correct
string upperName = name.ToUpper();
int stageIdx = upperName.IndexOf(Stage);
if (stageIdx >= 0)
{
name = name.Substring(0, stageIdx) + name.Substring(stageIdx + Stage.Length);
}
else if (!(Stage == ":FIRST"
&& !upperName.Contains(":BEFORE[")
&& !upperName.Contains(":FOR[")
&& !upperName.Contains(":AFTER[")
&& !upperName.Contains(":FINAL")))
{
continue;
}
// TODO: do we want to ensure there's only one phase specifier?
try
{
char[] sep = new char[] { '[', ']' };
string cond = "";
if (upperName.Contains(":HAS["))
{
int start = upperName.IndexOf(":HAS[");
cond = name.Substring(start + 5, name.LastIndexOf(']') - start - 5);
name = name.Substring(0, start);
}
string[] splits = name.Split(sep, 3);
string pattern = splits.Length > 1 ? splits[1] : null;
string type = splits[0].Substring(1);
foreach (UrlDir.UrlConfig url in GameDatabase.Instance.root.AllConfigs.ToArray())
{
if (url.type == type
&& WildcardMatch(url.name, pattern)
&& CheckCondition(url.config, cond)
&& !IsPathInList(mod.url, excludePaths)
)
{
switch (cmd)
{
case Command.Edit:
print("[ModuleManager] Applying node " + mod.url + " to " + url.url);
patchCount++;
url.config = ModifyNode(url.config, mod.config);
break;
case Command.Copy:
ConfigNode clone = ModifyNode(url.config, mod.config);
if (url.config.name != mod.name)
{
print("[ModuleManager] Copying Node " + url.config.name + " into " + clone.name);
url.parent.configs.Add(new UrlDir.UrlConfig(url.parent, clone));
}
else
{
errorCount++;
print("[ModuleManager] Error while processing " + mod.config.name + " the copy needs to have a different name than the parent (use @name = xxx)");
}
break;
case Command.Delete:
print("[ModuleManager] Deleting Node " + url.config.name);
url.parent.configs.Remove(url);
break;
case Command.Replace:
// TODO: do something sensible here.
break;
}
}
}
}
finally
{
// The patch was either run or has failed, in any case let's remove it from the database
mod.parent.configs.Remove(mod);
}
}
}
catch (Exception e)
{
print("[ModuleManager] Exception while processing node : " + mod.url + "\n" + e.ToString());
mod.parent.configs.Remove(mod);
}
finally
{
if (lastErrorCount < errorCount)
addErrorFiles(mod.parent, errorCount - lastErrorCount);
}
}
}
// Name is group 1, index is group 2, operator is group 3
private static Regex parseValue = new Regex(@"([\w\?\*]*)(?:,(-?[0-9]+))?(?:\s([+\-*/^]))?");
// ModifyNode applies the ConfigNode mod as a 'patch' to ConfigNode original, then returns the patched ConfigNode.
// it uses FindConfigNodeIn(src, nodeType, nodeName, nodeTag) to recurse.
public ConfigNode ModifyNode(ConfigNode original, ConfigNode mod)
{
ConfigNode newNode = DeepCopy(original);
#region Values
string vals = "[ModuleManager] modding values";
foreach (ConfigNode.Value modVal in mod.values)
{
vals += "\n " + modVal.name + "= " + modVal.value;
string valName;
Command cmd = ParseCommand(modVal.name, out valName);
Match match = parseValue.Match(valName);
if (!match.Success)
{
print("[ModuleManager] Cannot parse value modifying command: " + valName);
continue;
}
// Get the bits and pieces from the regexp
valName = match.Groups[1].Value;
// In this case insert the value at position index (with the same node names)
int index = 0;
if (match.Groups[2].Success)
{
// can have "node,n *" (for *= ect)
if (!int.TryParse(match.Groups[2].Value, out index))
{
Debug.LogError("Unable to parse number as number. Very odd.");
continue;
}
}
char op = ' ';
if (match.Groups[3].Success)
{
op = match.Groups[3].Value[0];
}
switch (cmd)
{
case Command.Insert:
if (match.Groups[3].Success)
{
print("[ModuleManager] Cannot use operators with insert value: " + mod.name);
}
else
{
// Insert at the end by default
InsertValue(newNode, match.Groups[2].Success ? index : int.MaxValue, valName, modVal.value);
}
break;
case Command.Replace:
if (match.Groups[2].Success || match.Groups[3].Success || valName.Contains('*') || valName.Contains('?'))
{
if (match.Groups[2].Success)
print("[ModuleManager] Cannot use index with replace (%) value: " + mod.name);
if (match.Groups[3].Success)
print("[ModuleManager] Cannot use operators with replace (%) value: " + mod.name);
if (valName.Contains('*') || valName.Contains('?'))
print("[ModuleManager] Cannot use wildcards (* or ?) with replace (%) value: " + mod.name);
}
else
{
newNode.RemoveValues(valName);
newNode.AddValue(valName, modVal.value);
}
break;
case Command.Edit:
case Command.Copy:
// Format is @key = value or @key *= value or @key += value or @key -= value
// or @key,index = value or @key,index *= value or @key,index += value or @key,index -= value
ConfigNode.Value origVal;
string value = FindAndReplaceValue(mod, ref valName, modVal.value, newNode, op, index, out origVal);
if (value != null)
{
if (origVal.value != value)
vals += ": " + origVal.value + " -> " + value;
if (cmd != Command.Copy)
origVal.value = value;
else
newNode.AddValue(valName, value);
}
break;
case Command.Delete:
if (match.Groups[3].Success)
print("[ModuleManager] Cannot use operators with delete (- or !) value: " + mod.name);
else if (match.Groups[2].Success)
{
// If there is an index, use it.
ConfigNode.Value v = FindValueIn(newNode, valName, index);
if (v != null)
newNode.values.Remove(v);
}
else if (valName.Contains('*') || valName.Contains('?'))
{
// Delete all matching wildcard
ConfigNode.Value last = null;
while (true)
{
ConfigNode.Value v = FindValueIn(newNode, valName, index++);
if (v == last)
break;
last = v;
newNode.values.Remove(v);
}
}
else
{
// Default is to delete ALL values that match. (backwards compatibility)
newNode.RemoveValues(valName);
}
break;
}
}
//print(vals);
#endregion
#region Nodes
foreach (ConfigNode subMod in mod.nodes)
{
subMod.name = RemoveWS(subMod.name);
if (!IsBraquetBalanced(subMod.name))
{
print("[ModuleManager] Skipping a patch subnode with unbalanced square brackets or a space (replace them with a '?') in " + mod.name + " : \n" + subMod.name + "\n");
errorCount++;
continue;
}
string subName = subMod.name;
string tmp;
Command command = ParseCommand(subName, out tmp);
if (command == Command.Insert)
{
int index = int.MaxValue;
if (subName.Contains(",") && int.TryParse(subName.Split(',')[1], out index))
{
// In this case insert the value at position index (with the same node names)
subMod.name = subName = subName.Split(',')[0];
InsertNode(newNode, subMod, index);
}
else
{
newNode.AddNode(subMod);
}
}
else
{
string cond = "";
string tag = "";
string nodeType, nodeName;
int index = 0;
string msg = "";
List<ConfigNode> subNodes = new List<ConfigNode>();
// three ways to specify:
// NODE,n will match the nth node (NODE is the same as NODE,0)
// NODE,* will match ALL nodes
// NODE:HAS[condition] will match ALL nodes with condition
if (subName.Contains(":HAS["))
{
int start = subName.IndexOf(":HAS[");
cond = subName.Substring(start + 5, subName.LastIndexOf(']') - start - 5);
subName = subName.Substring(0, start);
}
else if (subName.Contains(","))
{
tag = subName.Split(',')[1];
subName = subName.Split(',')[0];
int.TryParse(tag, out index);
}
if (subName.Contains("["))
{
// format @NODETYPE[Name] {...}
// or @NODETYPE[Name, index] {...}
nodeType = subName.Substring(1).Split('[')[0];
nodeName = subName.Split('[')[1].Replace("]", "");
}
else
{
// format @NODETYPE {...} or ! instead of @
nodeType = subName.Substring(1);
nodeName = null;
}
if (tag == "*" || cond.Length > 0)
{ // get ALL nodes
if (command == Command.Replace)
{
msg += " cannot wildcard a % node: " + subMod.name + "\n";
}
else
{
ConfigNode n, last = null;
while (true)
{
n = FindConfigNodeIn(newNode, nodeType, nodeName, index++);
if (n == last || n == null)
break;
if (CheckCondition(n, cond))
subNodes.Add(n);
last = n;
}
}
}
else
{ // just get one node
ConfigNode n = FindConfigNodeIn(newNode, nodeType, nodeName, index);
if (n != null)
subNodes.Add(n);
}
if (command != Command.Replace)
{ // find each original subnode to modify, modify it and add the modified.
if (subNodes.Count == 0) // no nodes to modify!
msg += " Could not find node(s) to modify: " + subMod.name + "\n";
foreach (ConfigNode subNode in subNodes)
{
msg += " Applying subnode " + subMod.name + "\n";
ConfigNode newSubNode;
switch (command)
{
case Command.Edit:
// Edit in place
newSubNode = ModifyNode(subNode, subMod);
subNode.ClearData();
newSubNode.CopyTo(subNode);
break;
case Command.Delete:
// Delete the node
newNode.nodes.Remove(subNode);
break;
case Command.Copy:
// Copy the node
newSubNode = ModifyNode(subNode, subMod);
newNode.nodes.Add(newSubNode);
break;
}
}
}
else // command == Command.Replace
{
// if the original exists modify it
if (subNodes.Count > 0)
{
msg += " Applying subnode " + subMod.name + "\n";
ConfigNode newSubNode = ModifyNode(subNodes[0], subMod);
subNodes[0].ClearData();
newSubNode.CopyTo(subNodes[0]);
}
else
{ // if not add the mod node without the % in its name
msg += " Adding subnode " + subMod.name + "\n";
ConfigNode copy = new ConfigNode(nodeType);
if (nodeName != null)
copy.AddValue("name", nodeName);
ConfigNode newSubNode = ModifyNode(copy, subMod);
newNode.nodes.Add(newSubNode);
}
}
//print(msg);
}
}
#endregion
return newNode;
}
private static string FindAndReplaceValue(ConfigNode mod, ref string valName, string value, ConfigNode newNode, char op, int index, out ConfigNode.Value origVal)
{
origVal = FindValueIn(newNode, valName, index);
if (origVal == null)
return null;
string ovalue = origVal.value;
if (op != ' ')
{
double s, os;
if (op == '^')
{
try
{
string[] split = value.Split(value[0]);
value = Regex.Replace(ovalue, split[1], split[2]);
}
catch (Exception ex)
{
print("[ModuleManager] Failed to do a regexp replacement: " + mod.name + " : original value=\"" + ovalue + "\" regexp=\"" + value + "\" \nNote - to use regexp, the first char is used to subdivide the string (much like sed)\n" + ex.ToString());
return null;
}
}
else if (double.TryParse(value, out s) && double.TryParse(ovalue, out os))
{
switch (op)
{
case '*':
value = (s * os).ToString();
break;
case '/':
value = (s / os).ToString();
break;
case '+':
value = (s + os).ToString();
break;
case '-':
value = (s - os).ToString();
break;
}
}
else
{
print("[ModuleManager] Failed to do a maths replacement: " + mod.name + " : original value=\"" + ovalue + "\" operator=" + op + " mod value=\"" + value + "\"");
return null;
}
}
return value;
}
#endregion
#region Command Parsing
private enum Command
{
Insert,
Delete,
Edit,
Replace,
Copy
}
private static Command ParseCommand(string name, out string valueName)
{
if (name.Length == 0)
{
valueName = string.Empty;
return Command.Insert;
}
Command ret;
switch (name[0])
{
case '@':
ret = Command.Edit;
break;
case '%':
ret = Command.Replace;
break;
case '-':
case '!':
ret = Command.Delete;
break;
case '+':
case '$':
ret = Command.Copy;
break;
default:
valueName = name;
return Command.Insert;
}
valueName = name.Substring(1);
return ret;
}
#endregion
#region Sanity checking & Utility functions
public static bool IsBraquetBalanced(String str)
{
Stack<char> stack = new Stack<char>();
char c;
for (int i = 0; i < str.Length; i++)
{
c = str[i];
if (c == '[')
stack.Push(c);
else if (c == ']')
if (stack.Count == 0)
return false;
else if (stack.Peek() == '[')
stack.Pop();
else
return false;
}
return stack.Count == 0;
}
public static string RemoveWS(string withWhite)
{ // Removes ALL whitespace of a string.
return new string(withWhite.ToCharArray().Where(c => !Char.IsWhiteSpace(c)).ToArray());
}
public bool IsPathInList(string modPath, List<String> pathList)
{
return pathList.Any(modPath.StartsWith);
}
#endregion
#region Condition checking
// Split condiction while not getting lost in embeded brackets
public static List<string> SplitCondition(string cond)
{
cond = RemoveWS(cond) + ",";
List<string> conds = new List<string>();
int start = 0;
int level = 0;
for (int end = 0; end < cond.Length; end++)
{
if (cond[end] == ',' && level == 0)
{
conds.Add(cond.Substring(start, end - start));
start = end + 1;
}
else if (cond[end] == '[')
level++;
else if (cond[end] == ']')
level--;
}
return conds;
}