/
MMPatchLoader.cs
1830 lines (1566 loc) · 72.6 KB
/
MMPatchLoader.cs
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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using Debug = UnityEngine.Debug;
using ModuleManager.Logging;
using ModuleManager.Extensions;
using ModuleManager.Collections;
using ModuleManager.Tags;
using ModuleManager.Threading;
using ModuleManager.Patches;
using ModuleManager.Progress;
using NodeStack = ModuleManager.Collections.ImmutableStack<ConfigNode>;
using static ModuleManager.FilePathRepository;
namespace ModuleManager
{
[SuppressMessage("ReSharper", "StringLastIndexOfIsCultureSpecific.1")]
[SuppressMessage("ReSharper", "StringIndexOfIsCultureSpecific.1")]
public class MMPatchLoader : LoadingSystem
{
public string status = "";
public string errors = "";
public static bool keepPartDB = false;
private string activity = "Module Manager";
private static readonly Dictionary<string, Regex> regexCache = new Dictionary<string, Regex>();
private UrlDir.UrlFile physicsUrlFile;
private string configSha;
private Dictionary<string, string> filesSha = new Dictionary<string, string>();
private const float yieldInterval = 1f/30f; // Patch at ~30fps
private IBasicLogger logger;
private float progressFraction = 0;
public static MMPatchLoader Instance { get; private set; }
private void Awake()
{
if (Instance != null)
{
DestroyImmediate(this);
return;
}
Instance = this;
logger = new ModLogger("ModuleManager", new UnityLogger(Debug.unityLogger));
}
private bool ready;
public override bool IsReady()
{
return ready;
}
public override float ProgressFraction() => progressFraction;
public override string ProgressTitle()
{
return activity;
}
public override void StartLoad()
{
ready = false;
// DB check used to track the now fixed TextureReplacer corruption
//checkValues();
StartCoroutine(ProcessPatch());
}
public static void AddPostPatchCallback(ModuleManagerPostPatchCallback callback)
{
PostPatchLoader.AddPostPatchCallback(callback);
}
private IEnumerator ProcessPatch()
{
Stopwatch patchSw = new Stopwatch();
patchSw.Start();
status = "Checking Cache";
logger.Info(status);
yield return null;
bool useCache = false;
try
{
useCache = IsCacheUpToDate();
}
catch (Exception ex)
{
logger.Exception("Exception in IsCacheUpToDate", ex);
}
#if DEBUG
//useCache = false;
#endif
yield return null;
IEnumerable<IProtoUrlConfig> databaseConfigs = null;
if (!useCache)
{
IPatchProgress progress = new PatchProgress(logger);
status = "Pre patch init";
logger.Info(status);
IEnumerable<string> mods = ModListGenerator.GenerateModList(progress, logger);
yield return null;
// If we don't use the cache then it is best to clean the PartDatabase.cfg
if (!keepPartDB && File.Exists(partDatabasePath))
File.Delete(partDatabasePath);
LoadPhysicsConfig();
#region Sorting Patches
status = "Extracting patches";
logger.Info(status);
yield return null;
UrlDir gameData = GameDatabase.Instance.root.children.First(dir => dir.type == UrlDir.DirectoryType.GameData && dir.name == "");
INeedsChecker needsChecker = new NeedsChecker(mods, gameData, progress, logger);
ITagListParser tagListParser = new TagListParser(progress);
IProtoPatchBuilder protoPatchBuilder = new ProtoPatchBuilder(progress);
IPatchCompiler patchCompiler = new PatchCompiler();
PatchExtractor extractor = new PatchExtractor(progress, logger, needsChecker, tagListParser, protoPatchBuilder, patchCompiler);
// Have to convert to an array because we will be removing patches
IEnumerable<IPatch> extractedPatches =
GameDatabase.Instance.root.AllConfigs.Select(urlConfig => extractor.ExtractPatch(urlConfig)).Where(patch => patch != null);
PatchList patchList = new PatchList(mods, extractedPatches, progress);
#endregion
#region Applying patches
status = "Applying patches";
logger.Info(status);
yield return null;
MessageQueue<ILogMessage> logQueue = new MessageQueue<ILogMessage>();
IBasicLogger patchLogger = new QueueLogger(logQueue);
IPatchProgress threadPatchProgress = new PatchProgress(progress, patchLogger);
PatchApplier applier = new PatchApplier(threadPatchProgress, patchLogger);
logger.Info("Starting patch thread");
ITaskStatus patchThread = BackgroundTask.Start(delegate
{
databaseConfigs = applier.ApplyPatches(patchList);
});
float nextYield = Time.realtimeSinceStartup + yieldInterval;
float updateTimeRemaining()
{
float timeRemaining = nextYield - Time.realtimeSinceStartup;
if (timeRemaining < 0)
{
nextYield = Time.realtimeSinceStartup + yieldInterval;
StatusUpdate(progress);
activity = applier.Activity;
}
return timeRemaining;
}
while (patchThread.IsRunning)
{
foreach (ILogMessage message in logQueue.TakeAll())
{
message.LogTo(logger);
if (updateTimeRemaining() < 0) yield return null;
}
float timeRemaining = updateTimeRemaining();
if (timeRemaining > 0) System.Threading.Thread.Sleep((int)(timeRemaining * 1000));
yield return null;
}
StatusUpdate(progress);
activity = "ModuleManager - finishing up";
yield return null;
// Clear any log messages that might still be in the queue
foreach (ILogMessage message in logQueue.TakeAll())
{
message.LogTo(logger);
}
if (patchThread.IsExitedWithError)
{
progress.Exception("The patch runner threw an exception", patchThread.Exception);
FatalErrorHandler.HandleFatalError("The patch runner threw an exception");
yield break;
}
if (databaseConfigs == null)
{
progress.Error("The patcher returned a null collection of configs");
FatalErrorHandler.HandleFatalError("The patcher returned a null collection of configs");
yield break;
}
logger.Info("Done patching");
yield return null;
PurgeUnused();
#endregion Applying patches
#region Saving Cache
foreach (KeyValuePair<string, int> item in progress.Counter.warningFiles)
{
logger.Warning(item.Value + " warning" + (item.Value > 1 ? "s" : "") + " related to GameData/" + item.Key);
}
if (progress.Counter.errors > 0 || progress.Counter.exceptions > 0)
{
foreach (KeyValuePair<string, int> item in progress.Counter.errorFiles)
{
errors += item.Value + " error" + (item.Value > 1 ? "s" : "") + " related to GameData/" + item.Key
+ "\n";
}
logger.Warning("Errors in patch prevents the creation of the cache");
try
{
if (File.Exists(cachePath))
File.Delete(cachePath);
if (File.Exists(shaPath))
File.Delete(shaPath);
}
catch (Exception e)
{
logger.Exception("Exception while deleting stale cache ", e);
}
}
else
{
status = "Saving Cache";
logger.Info(status);
yield return null;
CreateCache(databaseConfigs, progress.Counter.patchedNodes);
}
StatusUpdate(progress);
#endregion Saving Cache
SaveModdedTechTree();
SaveModdedPhysics();
}
else
{
status = "Loading from Cache";
logger.Info(status);
yield return null;
databaseConfigs = LoadCache();
}
foreach (UrlDir.UrlFile file in GameDatabase.Instance.root.AllConfigFiles)
{
file.configs.Clear();
}
foreach (IProtoUrlConfig protoConfig in databaseConfigs)
{
protoConfig.UrlFile.AddConfig(protoConfig.Node);
}
logger.Info(status + "\n" + errors);
patchSw.Stop();
logger.Info("Ran in " + ((float)patchSw.ElapsedMilliseconds / 1000).ToString("F3") + "s");
ready = true;
}
private void LoadPhysicsConfig()
{
logger.Info("Loading Physics.cfg");
UrlDir gameDataDir = GameDatabase.Instance.root.AllDirectories.First(d => d.path.EndsWith("GameData") && d.name == "" && d.url == "");
// need to use a file with a cfg extension to get the right fileType or you can't AddConfig on it
physicsUrlFile = new UrlDir.UrlFile(gameDataDir, new FileInfo(defaultPhysicsPath));
// Since it loaded the default config badly (sub node only) we clear it first
physicsUrlFile.configs.Clear();
// And reload it properly
ConfigNode physicsContent = ConfigNode.Load(defaultPhysicsPath);
physicsContent.name = "PHYSICSGLOBALS";
physicsUrlFile.AddConfig(physicsContent);
gameDataDir.files.Add(physicsUrlFile);
}
private void SaveModdedPhysics()
{
List<UrlDir.UrlConfig> configs = physicsUrlFile.configs;
if (configs.Count == 0)
{
logger.Info("No PHYSICSGLOBALS node found. No custom Physics config will be saved");
return;
}
if (configs.Count > 1)
{
logger.Info(configs.Count + " PHYSICSGLOBALS node found. A patch may be wrong. Using the first one");
}
configs[0].config.Save(physicsPath);
}
private bool IsCacheUpToDate()
{
Stopwatch sw = new Stopwatch();
sw.Start();
System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create();
System.Security.Cryptography.SHA256 filesha = System.Security.Cryptography.SHA256.Create();
UrlDir.UrlFile[] files = GameDatabase.Instance.root.AllConfigFiles.ToArray();
filesSha.Clear();
for (int i = 0; i < files.Length; i++)
{
// Hash the file path so the checksum change if files are moved
byte[] pathBytes = Encoding.UTF8.GetBytes(files[i].url);
sha.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
// hash the file content
byte[] contentBytes = File.ReadAllBytes(files[i].fullPath);
sha.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
filesha.ComputeHash(contentBytes);
if (!filesSha.ContainsKey(files[i].url))
{
filesSha.Add(files[i].url, BitConverter.ToString(filesha.Hash));
}
else
{
logger.Warning("Duplicate fileSha key. This should not append. The key is " + files[i].url);
}
}
// Hash the mods dll path so the checksum change if dlls are moved or removed (impact NEEDS)
foreach (AssemblyLoader.LoadedAssembly dll in AssemblyLoader.loadedAssemblies)
{
string path = dll.url + "/" + dll.name;
byte[] pathBytes = Encoding.UTF8.GetBytes(path);
sha.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
}
byte[] godsFinalMessageToHisCreation = Encoding.UTF8.GetBytes("We apologize for the inconvenience.");
sha.TransformFinalBlock(godsFinalMessageToHisCreation, 0, godsFinalMessageToHisCreation.Length);
configSha = BitConverter.ToString(sha.Hash);
sha.Clear();
filesha.Clear();
sw.Stop();
logger.Info("SHA generated in " + ((float)sw.ElapsedMilliseconds / 1000).ToString("F3") + "s");
logger.Info(" SHA = " + configSha);
bool useCache = false;
if (File.Exists(shaPath))
{
ConfigNode shaConfigNode = ConfigNode.Load(shaPath);
if (shaConfigNode != null && shaConfigNode.HasValue("SHA") && shaConfigNode.HasValue("version") && shaConfigNode.HasValue("KSPVersion"))
{
string storedSHA = shaConfigNode.GetValue("SHA");
string version = shaConfigNode.GetValue("version");
string kspVersion = shaConfigNode.GetValue("KSPVersion");
ConfigNode filesShaNode = shaConfigNode.GetNode("FilesSHA");
useCache = CheckFilesChange(files, filesShaNode);
useCache = useCache && storedSHA.Equals(configSha);
useCache = useCache && version.Equals(Assembly.GetExecutingAssembly().GetName().Version.ToString());
useCache = useCache && kspVersion.Equals(Versioning.version_major + "." + Versioning.version_minor + "." + Versioning.Revision + "." + Versioning.BuildID);
useCache = useCache && File.Exists(cachePath);
useCache = useCache && File.Exists(physicsPath);
useCache = useCache && File.Exists(techTreePath);
logger.Info("Cache SHA = " + storedSHA);
logger.Info("useCache = " + useCache);
}
}
return useCache;
}
private bool CheckFilesChange(UrlDir.UrlFile[] files, ConfigNode shaConfigNode)
{
bool noChange = true;
StringBuilder changes = new StringBuilder();
changes.Append("Changes :\n");
for (int i = 0; i < files.Length; i++)
{
ConfigNode fileNode = GetFileNode(shaConfigNode, files[i].url);
string fileSha = fileNode?.GetValue("SHA");
if (fileNode == null)
continue;
if (fileSha == null || filesSha[files[i].url] != fileSha)
{
changes.Append("Changed : " + fileNode.GetValue("filename") + ".cfg\n");
noChange = false;
}
}
for (int i = 0; i < files.Length; i++)
{
ConfigNode fileNode = GetFileNode(shaConfigNode, files[i].url);
if (fileNode == null)
{
changes.Append("Added : " + files[i].url + ".cfg\n");
noChange = false;
}
shaConfigNode.RemoveNode(fileNode);
}
foreach (ConfigNode fileNode in shaConfigNode.GetNodes())
{
changes.Append("Deleted : " + fileNode.GetValue("filename") + ".cfg\n");
noChange = false;
}
if (!noChange)
logger.Info(changes.ToString());
return noChange;
}
private ConfigNode GetFileNode(ConfigNode shaConfigNode, string filename)
{
for (int i = 0; i < shaConfigNode.nodes.Count; i++)
{
ConfigNode file = shaConfigNode.nodes[i];
if (file.name == "FILE" && file.GetValue("filename") == filename)
return file;
}
return null;
}
private void CreateCache(IEnumerable<IProtoUrlConfig> databaseConfigs, int patchedNodeCount)
{
ConfigNode shaConfigNode = new ConfigNode();
shaConfigNode.AddValue("SHA", configSha);
shaConfigNode.AddValue("version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
shaConfigNode.AddValue("KSPVersion", Versioning.version_major + "." + Versioning.version_minor + "." + Versioning.Revision + "." + Versioning.BuildID);
ConfigNode filesSHANode = shaConfigNode.AddNode("FilesSHA");
ConfigNode cache = new ConfigNode();
cache.AddValue("patchedNodeCount", patchedNodeCount.ToString());
foreach (IProtoUrlConfig urlConfig in databaseConfigs)
{
ConfigNode node = cache.AddNode("UrlConfig");
node.AddValue("parentUrl", urlConfig.UrlFile.url);
node.AddNode(urlConfig.Node);
}
foreach (var file in GameDatabase.Instance.root.AllConfigFiles)
{
// "/Physics" is the node we created manually to loads the PHYSIC config
if (file.url != "/Physics" && filesSha.ContainsKey(file.url))
{
ConfigNode shaNode = filesSHANode.AddNode("FILE");
shaNode.AddValue("filename", file.url);
shaNode.AddValue("SHA", filesSha[file.url]);
filesSha.Remove(file.url);
}
}
logger.Info("Saving cache");
try
{
shaConfigNode.Save(shaPath);
}
catch (Exception e)
{
logger.Exception("Exception while saving the sha", e);
}
try
{
cache.Save(cachePath);
return;
}
catch (NullReferenceException e)
{
logger.Exception("NullReferenceException while saving the cache", e);
}
catch (Exception e)
{
logger.Exception("Exception while saving the cache", e);
}
try
{
logger.Error("An error occured while creating the cache. Deleting the cache files to avoid keeping a bad cache");
if (File.Exists(cachePath))
File.Delete(cachePath);
if (File.Exists(shaPath))
File.Delete(shaPath);
}
catch (Exception e)
{
logger.Exception("Exception while deleting the cache", e);
}
}
private void SaveModdedTechTree()
{
UrlDir.UrlConfig[] configs = GameDatabase.Instance.GetConfigs("TechTree");
if (configs.Length == 0)
{
logger.Info("No TechTree node found. No custom TechTree will be saved");
return;
}
if (configs.Length > 1)
{
logger.Info(configs.Length + " TechTree node found. A patch may be wrong. Using the first one");
}
ConfigNode techNode = new ConfigNode("TechTree");
techNode.AddNode(configs[0].config);
techNode.Save(techTreePath);
}
private IEnumerable<IProtoUrlConfig> LoadCache()
{
ConfigNode cache = ConfigNode.Load(cachePath);
if (cache.HasValue("patchedNodeCount") && int.TryParse(cache.GetValue("patchedNodeCount"), out int patchedNodeCount))
status = "ModuleManager: " + patchedNodeCount + " patch" + (patchedNodeCount != 1 ? "es" : "") + " loaded from cache";
// Create the fake file where we load the physic config cache
UrlDir gameDataDir = GameDatabase.Instance.root.AllDirectories.First(d => d.path.EndsWith("GameData") && d.name == "" && d.url == "");
// need to use a file with a cfg extension to get the right fileType or you can't AddConfig on it
physicsUrlFile = new UrlDir.UrlFile(gameDataDir, new FileInfo(defaultPhysicsPath));
gameDataDir.files.Add(physicsUrlFile);
List<IProtoUrlConfig> databaseConfigs = new List<IProtoUrlConfig>(cache.nodes.Count);
foreach (ConfigNode node in cache.nodes)
{
string parentUrl = node.GetValue("parentUrl");
UrlDir.UrlFile parent = GameDatabase.Instance.root.AllConfigFiles.FirstOrDefault(f => f.url == parentUrl);
if (parent != null)
{
databaseConfigs.Add(new ProtoUrlConfig(parent, node.nodes[0]));
}
else
{
logger.Warning("Parent null for " + parentUrl);
}
}
progressFraction = 1;
logger.Info("Cache Loaded");
return databaseConfigs;
}
private void StatusUpdate(IPatchProgress progress)
{
progressFraction = progress.ProgressFraction;
status = "ModuleManager: " + progress.Counter.patchedNodes + " patch" + (progress.Counter.patchedNodes != 1 ? "es" : "") + " applied";
if (progress.Counter.warnings > 0)
status += ", found <color=yellow>" + progress.Counter.warnings + " warning" + (progress.Counter.warnings != 1 ? "s" : "") + "</color>";
if (progress.Counter.errors > 0)
status += ", found <color=orange>" + progress.Counter.errors + " error" + (progress.Counter.errors != 1 ? "s" : "") + "</color>";
if (progress.Counter.exceptions > 0)
status += ", encountered <color=red>" + progress.Counter.exceptions + " exception" + (progress.Counter.exceptions != 1 ? "s" : "") + "</color>";
}
private static void PurgeUnused()
{
foreach (UrlDir.UrlConfig mod in GameDatabase.Instance.root.AllConfigs.ToArray())
{
string name = mod.type.RemoveWS();
if (CommandParser.Parse(name, out name) != Command.Insert)
mod.parent.configs.Remove(mod);
}
}
#region Applying Patches
// Name is group 1, index is group 2, vector related filed is group 3, vector separator is group 4, operator is group 5
private static Regex parseValue = new Regex(@"([\w\&\-\.\?\*+/^!\(\) ]+(?:,[^*\d][\w\&\-\.\?\*\(\) ]*)*)(?:,(-?[0-9\*]+))?(?:\[((?:[0-9\*]+)+)(?:,(.))?\])?");
// 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 static ConfigNode ModifyNode(NodeStack original, ConfigNode mod, PatchContext context)
{
ConfigNode newNode = original.value.DeepCopy();
NodeStack nodeStack = original.ReplaceValue(newNode);
#region Values
#if LOGSPAM
string vals = "[ModuleManager] modding values";
#endif
foreach (ConfigNode.Value modVal in mod.values)
{
#if LOGSPAM
vals += "\n " + modVal.name + "= " + modVal.value;
#endif
Command cmd = CommandParser.Parse(modVal.name, out string valName);
Operator op;
if (valName.Length > 2 && valName[valName.Length - 2] == ',')
op = Operator.Assign;
else
op = OperatorParser.Parse(valName, out valName);
if (cmd == Command.Special)
{
ConfigNode.Value val = RecurseVariableSearch(valName, nodeStack.Push(mod), context);
if (val == null)
{
context.progress.Error(context.patchUrl, "Error - Cannot find value assigning command: " + valName);
continue;
}
if (op != Operator.Assign)
{
if (double.TryParse(modVal.value, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out double s)
&& double.TryParse(val.value, NumberStyles.Float, CultureInfo.InvariantCulture.NumberFormat, out double os))
{
switch (op)
{
case Operator.Multiply:
val.value = (os * s).ToString(CultureInfo.InvariantCulture);
break;
case Operator.Divide:
val.value = (os / s).ToString(CultureInfo.InvariantCulture);
break;
case Operator.Add:
val.value = (os + s).ToString(CultureInfo.InvariantCulture);
break;
case Operator.Subtract:
val.value = (os - s).ToString(CultureInfo.InvariantCulture);
break;
case Operator.Exponentiate:
val.value = Math.Pow(os, s).ToString(CultureInfo.InvariantCulture);
break;
}
}
}
else
{
val.value = modVal.value;
}
continue;
}
Match match = parseValue.Match(valName);
if (!match.Success)
{
context.progress.Error(context.patchUrl, "Error - Cannot parse value modifying command: " + valName);
continue;
}
// Get the bits and pieces from the regexp
valName = match.Groups[1].Value;
// Get a position for editing a vector
int position = 0;
bool isPosStar = false;
if (match.Groups[3].Success)
{
if (match.Groups[3].Value == "*")
isPosStar = true;
else if (!int.TryParse(match.Groups[3].Value, out position))
{
context.progress.Error(context.patchUrl, "Error - Unable to parse number as number. Very odd.");
continue;
}
}
char seperator = ',';
if (match.Groups[4].Success)
{
seperator = match.Groups[4].Value[0];
}
// In this case insert the value at position index (with the same node names)
int index = 0;
bool isStar = false;
if (match.Groups[2].Success)
{
if (match.Groups[2].Value == "*")
isStar = true;
// can have "node,n *" (for *= ect)
else if (!int.TryParse(match.Groups[2].Value, out index))
{
context.progress.Error(context.patchUrl, "Error - Unable to parse number as number. Very odd.");
continue;
}
}
int valCount = 0;
for (int i=0; i<newNode.CountValues; i++)
if (newNode.values[i].name == valName)
valCount++;
string varValue;
switch (cmd)
{
case Command.Insert:
if (match.Groups[5].Success)
{
context.progress.Error(context.patchUrl, "Error - Cannot use operators with insert value: " + mod.name);
}
else
{
// Insert at the end by default
varValue = ProcessVariableSearch(modVal.value, nodeStack, context);
if (varValue != null)
InsertValue(newNode, match.Groups[2].Success ? index : int.MaxValue, valName, varValue);
else
context.progress.Error(context.patchUrl, "Error - Cannot parse variable search when inserting new key " + valName + " = " +
modVal.value);
}
break;
case Command.Replace:
if (match.Groups[2].Success || match.Groups[5].Success || valName.Contains('*')
|| valName.Contains('?'))
{
if (match.Groups[2].Success)
context.progress.Error(context.patchUrl, "Error - Cannot use index with replace (%) value: " + mod.name);
if (match.Groups[5].Success)
context.progress.Error(context.patchUrl, "Error - Cannot use operators with replace (%) value: " + mod.name);
if (valName.Contains('*') || valName.Contains('?'))
context.progress.Error(context.patchUrl, "Error - Cannot use wildcards (* or ?) with replace (%) value: " + mod.name);
}
else
{
varValue = ProcessVariableSearch(modVal.value, nodeStack, context);
if (varValue != null)
{
newNode.RemoveValues(valName);
newNode.AddValue(valName, varValue);
}
else
{
context.progress.Error(context.patchUrl, "Error - Cannot parse variable search when replacing (%) key " + 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
while (index < valCount)
{
varValue = ProcessVariableSearch(modVal.value, nodeStack, context);
if (varValue != null)
{
string value = FindAndReplaceValue(
mod,
ref valName,
varValue, newNode,
op,
index,
out ConfigNode.Value origVal,
context,
match.Groups[3].Success,
position,
isPosStar,
seperator
);
if (value != null)
{
#if LOGSPAM
if (origVal.value != value)
vals += ": " + origVal.value + " -> " + value;
#endif
if (cmd != Command.Copy)
origVal.value = value;
else
newNode.AddValue(valName, value);
}
}
else
{
context.progress.Error(context.patchUrl, "Error - Cannot parse variable search when editing key " + valName + " = " + modVal.value);
}
if (isStar) index++;
else break;
}
break;
case Command.Delete:
if (match.Groups[5].Success)
{
context.progress.Error(context.patchUrl, "Error - Cannot use operators with delete (- or !) value: " + mod.name);
}
else if (match.Groups[2].Success)
{
while (index < valCount)
{
// If there is an index, use it.
ConfigNode.Value v = FindValueIn(newNode, valName, index);
if (v != null)
newNode.values.Remove(v);
if (isStar) index++;
else break;
}
}
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;
case Command.Rename:
if (nodeStack.IsRoot)
{
context.progress.Error(context.patchUrl, "Error - Renaming nodes does not work on top nodes");
break;
}
newNode.name = modVal.value;
break;
case Command.Create:
if (match.Groups[2].Success || match.Groups[5].Success || valName.Contains('*')
|| valName.Contains('?'))
{
if (match.Groups[2].Success)
context.progress.Error(context.patchUrl, "Error - Cannot use index with create (&) value: " + mod.name);
if (match.Groups[5].Success)
context.progress.Error(context.patchUrl, "Error - Cannot use operators with create (&) value: " + mod.name);
if (valName.Contains('*') || valName.Contains('?'))
context.progress.Error(context.patchUrl, "Error - Cannot use wildcards (* or ?) with create (&) value: " + mod.name);
}
else
{
varValue = ProcessVariableSearch(modVal.value, nodeStack, context);
if (varValue != null)
{
if (!newNode.HasValue(valName))
newNode.AddValue(valName, varValue);
}
else
{
context.progress.Error(context.patchUrl, "Error - Cannot parse variable search when replacing (&) key " + valName + " = " +
modVal.value);
}
}
break;
}
}
#if LOGSPAM
log(vals);
#endif
#endregion Values
#region Nodes
foreach (ConfigNode subMod in mod.nodes)
{
subMod.name = subMod.name.RemoveWS();
if (!subMod.name.IsBracketBalanced())
{
context.progress.Error(context.patchUrl,
"Error - Skipping a patch subnode with unbalanced square brackets or a space (replace them with a '?') in "
+ mod.name + " : \n" + subMod.name + "\n");
continue;
}
string subName = subMod.name;
Command command = CommandParser.Parse(subName, out string tmp);
if (command == Command.Insert)
{
ConfigNode newSubMod = new ConfigNode(subMod.name);
newSubMod = ModifyNode(nodeStack.Push(newSubMod), subMod, context);
subName = newSubMod.name;
if (subName.Contains(",") && int.TryParse(subName.Split(',')[1], out int index))
{
// In this case insert the node at position index (with the same node names)
newSubMod.name = subName.Split(',')[0];
InsertNode(newNode, newSubMod, index);
}
else
{
newNode.AddNode(newSubMod);
}
}
else if (command == Command.Paste)
{
//int start = subName.IndexOf('[');
//int end = subName.LastIndexOf(']');
//if (start == -1 || end == -1 || end - start < 1)
//{
// log("Pasting a node require a [path] to the node to paste" + mod.name + " : \n" + subMod.name + "\n");
// errorCount++;
// continue;
//}
//string newName = subName.Substring(0, start);
//string path = subName.Substring(start + 1, end - start - 1);
ConfigNode toPaste = RecurseNodeSearch(subName.Substring(1), nodeStack, context);
if (toPaste == null)
{
context.progress.Error(context.patchUrl, "Error - Can not find the node to paste in " + mod.name + " : " + subMod.name + "\n");
continue;
}
ConfigNode newSubMod = new ConfigNode(toPaste.name);
newSubMod = ModifyNode(nodeStack.Push(newSubMod), toPaste, context);
if (subName.LastIndexOf(",") > 0 && int.TryParse(subName.Substring(subName.LastIndexOf(",") + 1), out int index))
{
// In this case insert the node at position index
InsertNode(newNode, newSubMod, index);
}
else
newNode.AddNode(newSubMod);
}
else
{
string constraints = "";
string tag = "";
string nodeType, nodeName;
int index = 0;
#if LOGSPAM
string msg = "";
#endif
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