-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathProgram.cs
More file actions
608 lines (500 loc) · 26 KB
/
Copy pathProgram.cs
File metadata and controls
608 lines (500 loc) · 26 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
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using DataTool.ConvertLogic.WEM;
using DataTool.Flag;
using DataTool.Helper;
using DataTool.SaveLogic;
using DataTool.ToolLogic.Extract;
using Microsoft.Win32;
using TankLib;
using TankLib.TACT;
using TACTLib.Client;
using TACTLib.Client.HandlerArgs;
using TACTLib.Core.Product.Tank;
using TACTLib.Exceptions;
using TankLib.Helpers;
using ValveKeyValue;
namespace DataTool;
public static class Program {
public static ClientHandler Client;
public static ProductHandler_Tank TankHandler;
public static Dictionary<ushort, HashSet<ulong>> TrackedFiles;
public static ToolFlags Flags;
public static uint BuildVersion;
public static bool IsPTR => Client?.ProductCode == "prot";
public static readonly string[] ValidLanguages = { "deDE", "enUS", "esES", "esMX", "frFR", "itIT", "jaJP", "koKR", "plPL", "ptBR", "ruRU", "thTH", "trTR", "zhCN", "zhTW" };
private static readonly Dictionary<string, string> SteamLocaleMapping = new() {
{ "german", "deDE" },
{ "english", "enUS" },
{ "spanish", "esES" },
{ "latam", "esMX" },
{ "french", "frFR" },
{ "italian", "itIT" },
{ "japanese", "jaJP" },
{ "koreana", "koKR" },
{ "polish", "plPL" },
{ "brazilian", "ptBR" },
{ "russian", "ruRU" },
{ "thai", "thTH" },
{ "turkish", "trTR" },
{ "schinese", "zhCN" },
{ "tchinese", "zhTW" },
};
public static void Main() {
HookConsole();
// Verify that tool is being run from the console
LaunchHelpers.VerifyConsoleLaunch();
Logger.Info("Core", $"{Assembly.GetExecutingAssembly().GetName().Name} v{Util.GetVersion(typeof(Program).Assembly)}");
Logger.Info("Core", $"CommandLine: [{string.Join(", ", FlagParser.AppArgs.Select(x => $"\"{x}\""))}]");
// the text `"junkrat|spray="Venomous" by Leon"`
// is interpreted by cmd as `junkrat|spray=Venomous by Leon`
// (sequential quoted elements are concatenated)
// therefore, any " in the cli args must be because of an imbalance
// todo: trying to match unlock names that contain " characters has never worked.
// should probably remove the character from any name...
var invalidCliChars = SearchValues.Create(['"', '”']);
if (Environment.GetCommandLineArgs().Any(x => x.AsSpan().IndexOfAny(invalidCliChars) != -1)) {
Logger.Error("Core", "The tool cannot interpret your command!");
Logger.Warn("Core", "- Ensure there are spaces between each part.");
Logger.Warn("Core", "- Ensure there are no \\ characters before a \".");
return;
}
var tools = GetTools();
InitFlags(tools);
// If the flags failed to parse or something, just return. Flag parsing will have printed an error.
if (Flags == null)
return;
if (Flags.OverwatchDirectory == "{overwatch_directory}") {
Logger.Error("Core", "You need to replace {overwatch_directory} with the location you have Overwatch installed to. It can be found in Battle.net. Remember to surround it with quotes");
return;
}
if (Flags.OverwatchDirectory.StartsWith("{") || Flags.OverwatchDirectory.EndsWith("}")) {
Logger.Error("Core", "Do not include { or } in the Overwatch directory you pass to the tool. The path should be surrounded with quotation marks only");
return;
}
// Overrides the Overwatch Directory with the path set in the Environment variable.
// Useful for debugging as you can use saved configurations without having to edit the directory saved in the arguments
var overwatchDirectoryOverride = Environment.GetEnvironmentVariable("DATATOOL_OVERWATCH_DIR");
if (!string.IsNullOrEmpty(overwatchDirectoryOverride)) {
Flags.OverwatchDirectory = overwatchDirectoryOverride;
}
Logger.Debug("Core", $"CommandLineFile: {FlagParser.ArgFilePath}");
if (Flags.SaveArgs) {
FlagParser.AppArgs = FlagParser.AppArgs.Where(x => !x.StartsWith("--arg")).ToArray();
FlagParser.SaveArgs(Flags.OverwatchDirectory);
} else if (Flags.ResetArgs || Flags.DeleteArgs) {
FlagParser.ResetArgs();
if (Flags.DeleteArgs)
FlagParser.DeleteArgs();
Logger.Info("Core", $"CommandLineNew: [{string.Join(", ", FlagParser.AppArgs.Select(x => $"\"{x}\""))}]");
Flags = FlagParser.Parse<ToolFlags>(full => PrintHelp(full, tools));
if (Flags == null)
return;
}
if (string.IsNullOrWhiteSpace(Flags.OverwatchDirectory) || string.IsNullOrWhiteSpace(Flags.Mode) || Flags.Help) {
PrintHelp(true, tools);
return;
}
// find the current tool/mode to run
var (targetTool, targetToolFlags, targetToolAttributes) = GetToolActivation(tools);
if (targetTool == null) {
return;
}
if (targetToolFlags is ExtractFlags extractFlags) {
if (extractFlags.OutputPath.Contains("\"")) {
Logger.Error("Core", "The output directory you passed will confuse the tool! Please remove the last \\ character");
return;
}
if (extractFlags.OutputPath == "{output_directory}") {
Logger.Error("Core", "You need to replace {output_directory} with where you want the output files to go. Can just be something like \"out\" and a folder will be created next to the tool");
return;
}
if (extractFlags.OutputPath.StartsWith("{") || extractFlags.OutputPath.EndsWith("}")) {
Logger.Error("Core", "Do not include { or } in the output directory you pass to the tool. The path should be surrounded with quotation marks only");
return;
}
}
if (!targetToolAttributes.UtilNoArchiveNeeded) {
try {
InitStorage(Flags.Online);
} catch (Exception ex) when (ex.InnerException is UnsupportedBuildVersionException) {
Logger.Log24Bit(ConsoleSwatch.XTermColor.OrangeRed, true, Console.Error, "CASC", "This version of DataTool does not support this version of Overwatch.");
Logger.Log24Bit(ConsoleSwatch.XTermColor.OrangeRed, true, Console.Error, "CASC", "DataTool must be updated to support every new build of the game. This tool update may not be available straight away.");
throw;
} catch (IOException ex) when ((uint) ex.HResult == 0x80070020) {
Logger.Log24Bit(ConsoleSwatch.XTermColor.OrangeRed, true, Console.Error, "Core", "Error reading game files! Is Overwatch is running? Close Overwatch and Battle.net before running the tool.");
throw;
}
catch (FileNotFoundException) {
// file not found exceptions thrown by TACTLib should already include good exception info, we don't need to log anything here
throw;
} catch {
Logger.Log24Bit(ConsoleSwatch.XTermColor.OrangeRed, true, Console.Error, "CASC",
"=================\nError initializing CASC!\n" +
"Please Scan & Repair your game, launch it for a minute, and try the tools again before reporting a bug!\n" +
"========================");
throw;
}
InitKeys();
InitMisc();
}
var stopwatch = new Stopwatch();
Logger.Info("Core", "Tooling...");
stopwatch.Start();
targetTool.Parse(targetToolFlags);
stopwatch.Stop();
Logger.Success("Core", $"Execution finished in {stopwatch.Elapsed}");
ShutdownMisc();
}
private static void HookConsole() {
AppDomain.CurrentDomain.UnhandledException += ExceptionHandler;
Process.GetCurrentProcess()
.EnableRaisingEvents = true;
AppDomain.CurrentDomain.ProcessExit += (sender, @event) => Console.ForegroundColor = ConsoleColor.Gray;
Console.CancelKeyPress += (sender, @event) => Console.ForegroundColor = ConsoleColor.Gray;
Console.OutputEncoding = Encoding.UTF8;
}
private static void InitFlags(HashSet<Type> tools) {
FlagParser.LoadArgs();
Flags = FlagParser.Parse<ToolFlags>(full => PrintHelp(full, tools));
if (Flags == null)
return;
if (Flags.Debug) {
Logger.ShowDebug = true;
}
#if DEBUG
FlagParser.CheckCollisions(typeof(ToolFlags), (flag, duplicate) => {
Logger.Error("Flag", $"The flag \"{flag}\" from {duplicate} is a duplicate!");
});
#endif
}
public static void InitMisc() {
var dbPath = Flags.ScratchDBPath;
if (Flags.Deduplicate) {
Logger.Warn("ScratchDB", "Will attempt to deduplicate files if extracting...");
if (!string.IsNullOrWhiteSpace(Flags.ScratchDBPath)) {
Logger.Warn("ScratchDB", "Loading Scratch database...");
if (!File.Exists(dbPath) || new DirectoryInfo(dbPath).Exists)
dbPath = Path.Combine(Path.GetFullPath(Flags.ScratchDBPath), "Scratch.db");
Combo.ScratchDBInstance.Load(dbPath);
}
}
if (!Flags.NoGuidNames)
IO.LoadGUIDTable(Flags.OnlyCanonical);
IO.LoadLocalizedNamesMapping();
WwiseBank.GetReady();
}
public static void ShutdownMisc() {
SaveScratchDatabase();
}
public static void SaveScratchDatabase() {
if (!string.IsNullOrWhiteSpace(Flags.ScratchDBPath)) {
var dbPath = Flags.ScratchDBPath;
if (!File.Exists(dbPath) || new DirectoryInfo(dbPath).Exists)
dbPath = Path.Combine(Path.GetFullPath(Flags.ScratchDBPath), "Scratch.db");
if (Flags.Deduplicate && !string.IsNullOrWhiteSpace(dbPath)) {
Logger.Warn("ScratchDB", "Saving Scratch database...");
Combo.ScratchDBInstance.Save(dbPath);
}
}
}
public static void InitStorage(bool online = false) { // turnin offline off again, can cause perf issues with bundle hack
// Attempt to load language via registry or from Steam, if they were already provided via flags then this won't do anything
if (!Flags.NoLanguageRegistry) {
TryFetchLocaleFromSteamInstall(); // fetch from steam first
TryFetchLocaleFromRegistry();
}
Logger.Info("CASC", $"Text Language: {Flags.Language} | Speech Language: {Flags.SpeechLanguage}");
// todo: workaround for "detecting" RCN-only installs (bnet china)
// initially they were chinese-locale only, but now it supports all.
// it still only features only RCN manifests, no RDEV
if (File.Exists(Path.Combine(Flags.OverwatchDirectory, "NeacLoader.exe")) ||
File.Exists(Path.Combine(Flags.OverwatchDirectory, "_retail_", "NeacLoader.exe"))) {
Flags.RCN = true;
}
var args = new ClientCreateArgs {
SpeechLanguage = Flags.SpeechLanguage,
TextLanguage = Flags.Language,
HandlerArgs = new ClientCreateArgs_Tank { ManifestRegion = Flags.RCN ? ClientCreateArgs_Tank.REGION_CN : ClientCreateArgs_Tank.REGION_DEV },
Online = online,
RemoteKeyringUrl = "https://raw.githubusercontent.com/overtools/OWLib/master/TankLib/Overwatch.keyring"
};
LoadHelper.PreLoad();
Client = new ClientHandler(Flags.OverwatchDirectory, args);
LoadHelper.PostLoad(Client);
if (Client.ProductCode != "pro")
Logger.Warn("Core", $"The branch \"{Client.ProductCode}\" is not supported!. This might result in failure to load. Proceed with caution.");
if (!args.Online && Client.AgentProduct != null) {
var clientLanguages = Client.AgentProduct.Settings.Languages.Select(x => x.Language).ToArray();
var clientLanguagesStr = string.Join(", ", clientLanguages);
if (!clientLanguages.Contains(args.TextLanguage))
Logger.Warn("Core", "Battle.Net Agent reports that text language {0} is not installed. Tool likely will not work correctly. Installed languages: {1}", args.TextLanguage, clientLanguagesStr);
else if (!clientLanguages.Contains(args.SpeechLanguage))
Logger.Warn("Core", "Battle.Net Agent reports that speech language {0} is not installed. Installed languages: {1}", args.TextLanguage, clientLanguagesStr);
}
TankHandler = Client.ProductHandler as ProductHandler_Tank;
if (TankHandler == null) {
Logger.Error("Core", $"Not a valid Overwatch installation (detected product: {Client.Product})");
return;
}
// todo: these version checks don't really need to even exist anymore but whatever, maybe useful just for history - js
Client.InstallationInfo.Values.TryGetValue("Version", out var clientVersion);
var buildVersion = TryParseBuildVersion(clientVersion);
if (!uint.TryParse(buildVersion, out BuildVersion))
Logger.Warn("Core", "Could not parse build version from {0}", clientVersion ?? "null");
else if (BuildVersion < 39028)
Logger.Error("Core", "DataTool doesn't support Overwatch versions below 1.14. Please use OverTool.");
else if (BuildVersion < ProductHandler_Tank.VERSION_152_PTR)
Logger.Error("Core", "This version of DataTool doesn't support versions of Overwatch below 1.52. Please use older version of tool.");
else if (BuildVersion < 139475)
Logger.Error("Core", "This version of DataTool doesn't properly support versions of Overwatch below 2.17. Older version of tool is recommended.");
else if (BuildVersion < 146669)
Logger.Error("Core", "This version of DataTool doesn't properly support versions of Overwatch below 2.21. Older version of tool is recommended.");
InitTrackedFiles();
}
public static string TryParseBuildVersion(string clientVersion) {
string buildVersion;
if (clientVersion != null && clientVersion.Contains('.')) {
buildVersion = clientVersion.Split('.').LastOrDefault();
} else {
buildVersion = clientVersion?.Split('-').LastOrDefault();
}
// Handle cases where build version contains letters e.g. 1.71.1.0.97745a
return Regex.Replace(buildVersion ?? "", "[A-Za-z ]", "");
}
public static void InitTrackedFiles() {
TrackedFiles = new Dictionary<ushort, HashSet<ulong>>();
foreach (var asset in TankHandler.m_assets) {
var type = teResourceGUID.Type(asset.Key);
if (!TrackedFiles.TryGetValue(type, out var typeMap)) {
typeMap = new HashSet<ulong>();
TrackedFiles[type] = typeMap;
}
typeMap.Add(asset.Key);
}
}
public static void InitKeys() {
// todo: broken for now..
// surely fix
/*Logger.Info("Core", "Checking ResourceKeys");
foreach (var key in TrackedFiles[0x90]) {
if (!ValidKey(key)) continue;
var resourceKey = GetInstance<STUResourceKey>(key);
if (resourceKey == null || resourceKey.GetKeyID() == 0 || Client.ConfigHandler.Keyring.Keys.ContainsKey(resourceKey.GetReverseKeyID())) continue;
Client.ConfigHandler.Keyring.AddKey(resourceKey.GetReverseKeyID(), resourceKey.m_key);
Logger.Info("Core", $"Added ResourceKey {resourceKey.GetKeyIDString()}, Value: {resourceKey.GetKeyValueString()}");
}*/
}
private static void TryFetchLocaleFromRegistry() {
try {
if (!OperatingSystem.IsWindows()) {
return;
}
if (Flags.Language == null) {
var textLanguage = (string) Registry.GetValue(@"HKEY_CURRENT_USER\Software\Blizzard Entertainment\Battle.net\Launch Options\Pro", "LOCALE", null);
if (!string.IsNullOrWhiteSpace(textLanguage)) {
if (ValidLanguages.Contains(textLanguage)) {
Flags.Language = textLanguage;
Logger.Debug("Core", $"Found text language via registry: {textLanguage}");
} else {
Logger.Error("Core", $"Invalid text language found via registry: {textLanguage}. Ignoring.");
}
}
}
if (Flags.SpeechLanguage == null) {
var speechLanguage = (string) Registry.GetValue(@"HKEY_CURRENT_USER\Software\Blizzard Entertainment\Battle.net\Launch Options\Pro", "LOCALE_AUDIO", null);
if (!string.IsNullOrWhiteSpace(speechLanguage)) {
if (ValidLanguages.Contains(speechLanguage)) {
Flags.SpeechLanguage = speechLanguage;
Logger.Debug("Core", $"Found speech language via registry: {speechLanguage}");
} else {
Logger.Error("Core", $"Invalid speech language found via registry: {speechLanguage}. Ignoring.");
}
}
}
} catch (Exception ex) {
Logger.Debug("Core", $"Failed to fetch locale from registry: {ex.Message}");
// Ignored
}
}
private static void TryFetchLocaleFromSteamInstall() {
try {
// already have langugae so no need to lookup
if (Flags.SpeechLanguage != null && Flags.Language != null) {
return;
}
// see if the directory is a windows symlink and try to get the real path
// note: doesn't work on linux/wsl
var directoryInfo = new DirectoryInfo(Flags.OverwatchDirectory);
var realOverwatchDirectory = directoryInfo.LinkTarget ?? directoryInfo.FullName; // if it's not a symlink, LinkTarget will be null
Logger.Debug("Core", $"LinkTarget: {directoryInfo.LinkTarget} | FullName: {directoryInfo.FullName}");
var appManifestPath = Path.Combine(realOverwatchDirectory, "..", "..", "appmanifest_2357570.acf");
if (!File.Exists(appManifestPath)) {
Logger.Debug("Core", $"Failed to find appmanifest at {appManifestPath}");
return;
}
// read the appmanifest and get the language
var stream = File.OpenRead(appManifestPath);
var appManifest = KVSerializer.Create(KVSerializationFormat.KeyValues1Text).Deserialize(stream);
var language = appManifest["UserConfig"]?["language"]?.ToString(CultureInfo.InvariantCulture);
if (language == null) {
return;
}
// try to map the steam language to a valid language code.
if (SteamLocaleMapping.TryGetValue(language.ToLower(), out var locale)) {
// steam doesn't support seperate text and speech languages, so we just use the same language for both if they aren't already set
if (Flags.Language == null) {
Flags.Language = locale;
Logger.Debug("Core", $"Found text language via Steam install: {locale}");
}
if (Flags.SpeechLanguage == null) {
Flags.SpeechLanguage = locale;
Logger.Debug("Core", $"Found speech via Steam install: {locale}");
}
} else {
Logger.Error("Core", $"Invalid language found via Steam install: {language}. Ignoring.");
}
} catch (Exception ex) {
Logger.Debug("Core", $"Failed to fetch locale from Steam install: {ex.Message}");
// Ignored
}
}
private static void HandleSingleException(Exception ex) {
if (ex is TargetInvocationException fex) {
ex = fex.InnerException ?? ex;
}
Logger.Log24Bit(ConsoleSwatch.XTermColor.HotPink3, true, Console.Error, null, ex.Message);
Logger.Log24Bit(ConsoleSwatch.XTermColor.MediumPurple, true, Console.Error, null, ex.StackTrace);
if (ex is BLTEDecoderException decoder) {
File.WriteAllBytes(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"BLTEDump-{AppDomain.CurrentDomain.FriendlyName}_{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}.blte"), decoder.GetBLTEData());
}
if (ex.InnerException != null) {
HandleSingleException(ex.InnerException);
}
}
[DebuggerStepThrough]
private static void ExceptionHandler(object sender, UnhandledExceptionEventArgs e) {
if (e.ExceptionObject is Exception ex) {
HandleSingleException(ex);
if (Debugger.IsAttached) throw ex;
}
unchecked {
Environment.Exit(-1);
}
}
#region Tool Initialization
// returns all the tools/modes that are available
public static HashSet<Type> GetTools() {
var tools = new HashSet<Type>();
{
var t = typeof(ITool);
var asm = t.Assembly;
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => p.IsClass && t.IsAssignableFrom(p));
foreach (var tt in types) {
var attribute = tt.GetCustomAttribute<ToolAttribute>();
if (tt.IsInterface || attribute == null) continue;
tools.Add(tt);
}
}
return tools;
}
// returns the tool/mode that should be run based on the flags
private static (ITool targetTool, ICLIFlags targetToolFlags, ToolAttribute targetToolAttributes) GetToolActivation(HashSet<Type> tools) {
ITool targetTool = null;
ICLIFlags targetToolFlags = null;
ToolAttribute targetToolAttributes = null;
foreach (var type in tools) {
var attribute = type.GetCustomAttribute<ToolAttribute>();
var keywordMatch = string.Equals(attribute.Keyword, Flags.Mode, StringComparison.InvariantCultureIgnoreCase);
var aliasMatch = attribute.Aliases?.Any(x => string.Equals(x, Flags.Mode, StringComparison.InvariantCultureIgnoreCase)) ?? false;
if (!keywordMatch && !aliasMatch) {
continue;
}
targetTool = Activator.CreateInstance(type) as ITool;
targetToolAttributes = attribute;
if (attribute.CustomFlags != null) {
var flags = attribute.CustomFlags;
if (typeof(ICLIFlags).IsAssignableFrom(flags))
targetToolFlags = typeof(FlagParser).GetMethod(nameof(FlagParser.Parse), new Type[] { })
?.MakeGenericMethod(flags)
.Invoke(null, null) as ICLIFlags;
}
break;
}
if (targetToolFlags == null && targetTool != null) {
return (null, null, null);
}
if (targetTool == null) {
FlagParser.Help<ToolFlags>(false, new Dictionary<string, string>());
PrintHelp(false, tools);
return (null, null, null);
}
return (targetTool, targetToolFlags, targetToolAttributes);
}
// prints the help message for available tools/modes and flags
private static void PrintHelp(bool full, IEnumerable<Type> eTools) {
var tools = new List<Type>(eTools);
tools.Sort(new ToolComparer());
Logger.Log();
Logger.Log("Modes:");
Logger.Log(null, " {0, -26} | {1, -40}", "mode", "description");
Logger.Log("".PadLeft(94, '-'));
foreach (var t in tools) {
var attribute = t.GetCustomAttribute<ToolAttribute>();
if (attribute.IsSensitive) continue;
var desc = attribute.Description;
if (attribute.Description == null) desc = "";
Logger.Log(null, " {0, -26} | {1}", attribute.Keyword, desc);
}
var flagTypes = new List<Type>();
foreach (var t in tools) {
var attribute = t.GetCustomAttribute<ToolAttribute>();
if (attribute.IsSensitive) continue;
if (attribute?.CustomFlags == null) continue;
var flags = attribute.CustomFlags;
if (!typeof(ICLIFlags).IsAssignableFrom(attribute.CustomFlags)) continue;
if (flagTypes.Contains(flags)) continue;
flagTypes.Add(flags);
}
foreach (var flagType in flagTypes) {
var flagInfo = flagType.GetCustomAttribute<FlagInfo>();
Logger.Log();
Logger.Log($"{flagInfo?.Name ?? flagType.Name} Flags - {flagInfo?.Description ?? ""}");
typeof(FlagParser).GetMethod(nameof(FlagParser.FullHelp))
?.MakeGenericMethod(flagType)
.Invoke(null, new object[] { null, true });
}
ToolNameSpellCheck();
}
internal class ToolComparer : IComparer<Type> {
public int Compare(Type x, Type y) {
var xT = (x ?? throw new ArgumentNullException(nameof(x))).GetCustomAttribute<ToolAttribute>();
var yT = (y ?? throw new ArgumentNullException(nameof(y))).GetCustomAttribute<ToolAttribute>();
return string.Compare(xT.Keyword, yT.Keyword, StringComparison.InvariantCultureIgnoreCase);
}
}
private static void ToolNameSpellCheck() {
// this will happen if mode is not found
if (string.IsNullOrWhiteSpace(Flags?.Mode?.ToLower())) {
return;
}
var spellCheck = new ScopedSpellCheck();
foreach (var type in GetTools()) {
var attribute = type.GetCustomAttribute<ToolAttribute>();
if (attribute == null || attribute.IsSensitive) continue;
spellCheck.Add(attribute.Keyword.ToLowerInvariant());
}
spellCheck.LogSpellCheck(Flags.Mode.ToLowerInvariant());
}
#endregion
}