-
Notifications
You must be signed in to change notification settings - Fork 136
/
Copy pathFilePatching.cs
498 lines (434 loc) · 19.7 KB
/
FilePatching.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using BepInEx;
using Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace EpicLoot.Patching
{
[Serializable]
public enum PatchAction
{
None, // Do nothing
Add, // Add the provided value to the selected object with the provided property name, if the property already exists, it's value is overwritten
Overwrite, // Replace the selected token's value with the provided value
Remove, // Remove the selected token from the array or object
Append, // Append the provided value to the end of the selected array
AppendAll, // Append the provided array to the end of the selected array.
InsertBefore, // Insert the provided value into the array containing the selected token, before the token
InsertAfter, // Insert the provided value into the array containing the selected token, after the token
RemoveAll, // Remove all elements of an array or all properties of an object
Merge, // Use property values in the provided object to add or overwrite property values on the selected object
}
[Serializable]
public class Patch
{
public int Priority = -1;
public string Author = "";
public string SourceFile = "";
public string TargetFile = "";
public string Path = "";
public PatchAction Action = PatchAction.None;
public bool Require;
public string PropertyName = "";
public JToken Value = null;
}
[Serializable]
public class PatchFile
{
public int Priority = 500;
public string TargetFile = "";
public string Author = "";
public bool RequireAll = false;
public List<Patch> Patches;
}
public static class FilePatching
{
public static string PatchesDirPath;
public static List<string> ConfigFileNames = new List<string>();
public static MultiValueDictionary<string, Patch> PatchesPerFile = new MultiValueDictionary<string, Patch>();
public static void LoadAllPatches()
{
PatchesDirPath = GetPatchesDirectoryPath();
// If the folder does not exist, there are no patches
if (string.IsNullOrEmpty(PatchesDirPath))
return;
var patchesFolder = new DirectoryInfo(PatchesDirPath);
if (!patchesFolder.Exists)
return;
var pluginFolder = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
CheckForOldPatches(pluginFolder.Parent);
GetAllConfigFileNames(pluginFolder.Parent);
ProcessPatchDirectory(patchesFolder);
}
public static void CheckForOldPatches(DirectoryInfo pluginFolder)
{
var oldPatchFolder = Path.Combine(pluginFolder.FullName, "patches");
if (Directory.Exists(oldPatchFolder))
{
if (Directory.GetFiles(oldPatchFolder, "*.json", SearchOption.AllDirectories).Length > 0)
{
EpicLoot.LogWarningForce($"***************************************************");
EpicLoot.LogWarningForce($"Epic Loot Patch Folder Has Moved To:");
EpicLoot.LogWarningForce($"{PatchesDirPath}");
EpicLoot.LogWarningForce($"Please move your patch files. Patch files found in this folder will not be loaded");
EpicLoot.LogWarningForce($"***************************************************");
}
}
}
public static void RemoveFilePatches(string fileName, string patchFile)
{
PatchesPerFile.GetValues(fileName, true).RemoveAll(y => y.SourceFile.Equals(patchFile));
}
public static void GetAllConfigFileNames(DirectoryInfo pluginFolder)
{
ConfigFileNames.Clear();
FileInfo[] files = null;
try
{
files = pluginFolder.GetFiles("*.json");
}
catch (Exception e)
{
EpicLoot.LogError($"Error parsing patch directory ({pluginFolder.Name}): {e.Message}");
}
if (files == null)
return;
foreach (var file in files)
{
ConfigFileNames.Add(file.Name);
}
}
public static void ProcessPatchDirectory(DirectoryInfo dir)
{
FileInfo[] files = null;
try
{
files = dir.GetFiles("*.json");
}
catch (Exception e)
{
EpicLoot.LogError($"Error parsing patch directory ({dir.Name}): {e.Message}");
}
if (files != null)
{
foreach (var file in files)
{
ProcessPatchFile(file);
}
}
var subDirs = dir.GetDirectories();
foreach (var subDir in subDirs)
{
ProcessPatchDirectory(subDir);
}
}
public static void ProcessPatchFile(FileInfo file)
{
var defaultTargetFile = "";
if (ConfigFileNames.Contains(file.Name))
defaultTargetFile = file.Name;
PatchFile patchFile = null;
try
{
patchFile = JsonConvert.DeserializeObject<PatchFile>(File.ReadAllText(file.FullName));
}
catch (Exception e)
{
EpicLoot.LogErrorForce($"Error parsing patch file ({file.Name})! Error: {e.Message}");
return;
}
if (patchFile == null)
{
EpicLoot.LogErrorForce($"Error parsing patch file ({file.Name})! Error: unknown!");
return;
}
if (!string.IsNullOrEmpty(patchFile.TargetFile) && !string.IsNullOrEmpty(defaultTargetFile) && patchFile.TargetFile != defaultTargetFile)
EpicLoot.LogWarningForce($"TargetFile ({patchFile.TargetFile}) specified in patch file ({file.Name}) does not match! If patch file name matches a config file name, TargetFile is unnecessary.");
if (!string.IsNullOrEmpty(patchFile.TargetFile))
defaultTargetFile = patchFile.TargetFile;
if (!string.IsNullOrEmpty(defaultTargetFile) && !ConfigFileNames.Contains(defaultTargetFile))
{
EpicLoot.LogErrorForce($"TargetFile ({defaultTargetFile}) specified in patch file ({file.Name}) does not exist! {file.Name} will not be processed.");
return;
}
var requiresSpecifiedSourceFile = string.IsNullOrEmpty(defaultTargetFile);
var author = string.IsNullOrEmpty(patchFile.Author) ? "<author>" : patchFile.Author;
var requireAll = patchFile.RequireAll;
var defaultPriority = patchFile.Priority;
for (var index = 0; index < patchFile.Patches.Count; index++)
{
var patch = patchFile.Patches[index];
EpicLoot.Log($"Patch: ({file.Name}, {index})\n > Action: {patch.Action}\n > Path: {patch.Path}\n > Value: {patch.Value}");
patch.Require = requireAll || patch.Require;
if (string.IsNullOrEmpty(patch.Author))
patch.Author = author;
if (string.IsNullOrEmpty(patch.TargetFile))
{
if (requiresSpecifiedSourceFile)
{
EpicLoot.LogErrorForce($"Patch ({index}) in file ({file.Name}) requires a specified TargetFile!");
continue;
}
patch.TargetFile = defaultTargetFile;
}
else if (!ConfigFileNames.Contains(patch.TargetFile))
{
EpicLoot.LogErrorForce($"Patch ({index}) in file ({file.Name}) has unknown specified source file ({patch.TargetFile})!");
continue;
}
if (patch.Priority < 0)
patch.Priority = defaultPriority;
patch.SourceFile = file.Name;
EpicLoot.Log($"Adding Patch from {patch.SourceFile} to file {patch.TargetFile} with {patch.Path}");
PatchesPerFile.Add(patch.TargetFile, patch);
}
}
public static string GetPatchesDirectoryPath()
{
var patchesFolderPath = Path.Combine(Paths.ConfigPath, "EpicLoot", "patches");
var dirInfo = Directory.CreateDirectory(patchesFolderPath);
return dirInfo.FullName;
}
public static string ProcessConfigFile(string fileName, string fileText)
{
var patches = PatchesPerFile.GetValues(fileName, true).OrderByDescending(x => x.Priority).ToList();
if (patches.Count == 0)
return fileText;
JObject json = null;
try
{
json = JObject.Parse(fileText);
}
catch (Exception e)
{
EpicLoot.LogErrorForce($"Error parsing config file ({fileName})! Error: {e.Message}");
return string.Empty;
}
foreach (var patch in patches)
{
ApplyPatch(json, patch);
}
var output = json.ToString(EpicLoot.OutputPatchedConfigFiles.Value ? Formatting.Indented : Formatting.None);
return output;
}
public static void ApplyPatch(JObject json, Patch patch)
{
var selectedTokens = json.SelectTokens(patch.Path).ToList();
if (patch.Require && selectedTokens.Count == 0)
{
EpicLoot.LogErrorForce($"Required Patch ({patch.SourceFile}) path ({patch.Path}) failed to select any tokens in target file ({patch.TargetFile})!");
return;
}
foreach (var token in selectedTokens)
{
switch (patch.Action)
{
case PatchAction.Add: ApplyPatch_Add(token, patch); break;
case PatchAction.Overwrite: ApplyPatch_Overwrite(token, patch); break;
case PatchAction.Remove: ApplyPatch_Remove(token, patch); break;
case PatchAction.Append: ApplyPatch_Append(token, patch); break;
case PatchAction.AppendAll: ApplyPatch_Append(token, patch, true); break;
case PatchAction.InsertBefore: ApplyPatch_Insert(token, patch, false); break;
case PatchAction.InsertAfter: ApplyPatch_Insert(token, patch, true); break;
case PatchAction.RemoveAll: ApplyPatch_RemoveAll(token, patch); break;
case PatchAction.Merge: ApplyPatch_Merge(token, patch); break;
default: break;
}
}
}
public static void ApplyPatch_Add(JToken token, Patch patch)
{
if (patch.Value == null)
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Add' but has not supplied a json Value! This patch will be ignored!");
return;
}
if (string.IsNullOrEmpty(patch.PropertyName))
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Add' but has not supplied a PropertyName for the added value! This patch will be ignored!");
return;
}
if (token.Type == JTokenType.Object)
{
var jObject = ((JObject)token);
if (jObject.ContainsKey(patch.PropertyName) && jObject.Property(patch.PropertyName) is JProperty jProperty)
{
EpicLoot.LogWarningForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Add' but a property with the name ({patch.PropertyName}) already exists! The property's value will be overwritten");
jProperty.Value = patch.Value;
}
else
{
jObject.Add(patch.PropertyName, patch.Value);
}
}
else
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Add' but has selected a token that is not a json Object! This patch will be ignored!");
}
}
public static void ApplyPatch_Overwrite(JToken token, Patch patch)
{
if (patch.Value == null)
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Overwrite' but has not supplied a json Value! This patch will be ignored!");
return;
}
if (token.Type == JTokenType.Property)
{
((JProperty)token).Value = patch.Value;
}
else if (token.Parent?.Type == JTokenType.Property)
{
((JProperty)token.Parent).Value = patch.Value;
}
else
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Overwrite' but did not select a json Object Property or Property Value! This patch will be ignored!");
}
}
public static void ApplyPatch_Remove(JToken token, Patch patch)
{
if (patch.Value != null)
{
EpicLoot.LogWarningForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Remove' but has supplied a json Value. (This patch will still be processed)");
}
token.Remove();
}
public static void ApplyPatch_Append(JToken token, Patch patch, bool appendAll = false)
{
var actionName = appendAll ? "AppendAll" : "Append";
if (patch.Value == null)
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action '{actionName}' but has not supplied a json Value! This patch will be ignored!");
return;
}
if (token.Type == JTokenType.Array)
{
if (appendAll)
{
if (patch.Value.Type == JTokenType.Array)
{
var mergeSettings = new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Concat,
MergeNullValueHandling = MergeNullValueHandling.Ignore
};
((JArray)token).Merge(patch.Value, mergeSettings);
}
else
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'AppendAll' but has provided a value in the source file that is not a json Array!");
}
}
else
{
((JArray)token).Add(patch.Value);
}
}
else
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action {actionName} but has selected a token in the target file that is not a json Array!");
}
}
public static void ApplyPatch_Insert(JToken token, Patch patch, bool after)
{
var actionName = $"Insert{(after ? "After" : "Before")}";
if (patch.Value == null)
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action '{actionName}' but has not supplied a json Value! This patch will be ignored!");
return;
}
var parent = token.Parent;
if (parent == null)
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action '{actionName}' but the parent of the selected token is not a container! This patch will be ignored!");
return;
}
if (parent.Type == JTokenType.Array)
{
if (after)
token.AddAfterSelf(patch.Value);
else
token.AddBeforeSelf(patch.Value);
}
else if (parent.Type == JTokenType.Object)
{
if (string.IsNullOrEmpty(patch.PropertyName))
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action '{actionName}' and has selected a property of a json Object, but not provided a PropertyName! This patch will be ignored!");
return;
}
if (after)
token.AddAfterSelf(new JProperty(patch.PropertyName, patch.Value));
else
token.AddBeforeSelf(new JProperty(patch.PropertyName, patch.Value));
}
}
public static void ApplyPatch_RemoveAll(JToken token, Patch patch)
{
const string actionName = "RemoveAll";
if (patch.Value != null)
{
EpicLoot.LogWarningForce($"Patch ({patch.SourceFile}, {patch.Path}) has action '{actionName}' but has supplied a json Value! (This patch will still be processed)");
}
if (token.Type == JTokenType.Array)
{
((JArray)token).RemoveAll();
}
else if (token.Type == JTokenType.Object)
{
((JObject)token).RemoveAll();
}
else
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action '{actionName}' but selected token is not an Array or Object! This patch will be ignored!");
}
}
public static void ApplyPatch_Merge(JToken token, Patch patch)
{
if (patch.Value == null)
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Merge' but has not supplied a json Value! This patch will be ignored!");
return;
}
if (patch.Value.Type != JTokenType.Object)
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Merge' but has supplied a json Value that is not an Object! This patch will be ignored!");
return;
}
if (token.Type != JTokenType.Object)
{
EpicLoot.LogErrorForce($"Patch ({patch.SourceFile}, {patch.Path}) has action 'Merge' but has selected a token that is not a json Object! This patch will be ignored!");
return;
}
var baseObject = ((JObject)token);
var partialObject = ((JObject)patch.Value);
MergeObject(baseObject, partialObject);
}
private static void MergeObject(JObject baseObject, JObject partialObject)
{
foreach (JProperty partialProperty in partialObject.Properties())
{
if (baseObject.ContainsKey(partialProperty.Name) && baseObject.Property(partialProperty.Name) is JProperty baseProperty)
{
if (baseProperty.Value.Type == JTokenType.Object && partialProperty.Value.Type == JTokenType.Object)
{
MergeObject((JObject)baseProperty.Value, (JObject)partialProperty.Value);
}
else
{
baseProperty.Value = partialProperty.Value;
}
}
else
{
baseObject.Add(partialProperty.Name, partialProperty.Value);
}
}
}
}
}