-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCfgScanCommand.cs
More file actions
346 lines (307 loc) · 13 KB
/
CfgScanCommand.cs
File metadata and controls
346 lines (307 loc) · 13 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
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace CFRezManager;
internal static partial class CfgScanCommand
{
private const int MaxConfigBytes = 8 * 1024 * 1024;
private static readonly Regex TextureReferenceRegex = CreateTextureReferenceRegex();
private sealed record Options(string RootPath, string ReportPath);
private sealed record CfgScanResult(
string Path,
string RelativePath,
long SourceByteCount,
int ReadByteCount,
int DecodedByteCount,
string Status,
string EncodingName,
bool LzmaHeader,
bool Sampled,
int TextureReferenceCount,
string TextureReferencePreview,
string ErrorMessage);
public static bool IsInvocation(string[] args)
{
return args.Any(arg =>
string.Equals(arg, "--scan-cfg", StringComparison.OrdinalIgnoreCase) ||
string.Equals(arg, "scan-cfg", StringComparison.OrdinalIgnoreCase));
}
public static int Run(string[] args)
{
try
{
Options options = ParseOptions(args);
List<CfgScanResult> results = Directory
.EnumerateFiles(options.RootPath, "*.cfg", SearchOption.AllDirectories)
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase)
.Select(path => ScanFile(options.RootPath, path))
.ToList();
string csvPath = Path.ChangeExtension(options.ReportPath, ".csv");
WriteSummary(options.ReportPath, options, csvPath, results);
WriteCsv(csvPath, results);
Console.WriteLine($"CFG files: {results.Count.ToString(CultureInfo.InvariantCulture)}");
Console.WriteLine($"Decoded text: {results.Count(result => result.Status == "decoded-text").ToString(CultureInfo.InvariantCulture)}");
Console.WriteLine($"Decoded LZMA: {results.Count(result => result.Status == "decoded-lzma").ToString(CultureInfo.InvariantCulture)}");
Console.WriteLine($"Decode failed: {results.Count(result => result.Status == "decode-failed").ToString(CultureInfo.InvariantCulture)}");
Console.WriteLine($"LZMA failed: {results.Count(result => result.Status == "lzma-decode-failed").ToString(CultureInfo.InvariantCulture)}");
Console.WriteLine($"Read errors: {results.Count(result => result.Status == "read-error").ToString(CultureInfo.InvariantCulture)}");
Console.WriteLine($"Report: {options.ReportPath}");
Console.WriteLine($"Details: {csvPath}");
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
}
private static Options ParseOptions(string[] args)
{
string? rootPath = null;
string? reportPath = null;
for (int index = 0; index < args.Length; index++)
{
string arg = args[index];
if (string.Equals(arg, "--scan-cfg", StringComparison.OrdinalIgnoreCase) ||
string.Equals(arg, "scan-cfg", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (TryReadOptionValue(args, ref index, "--root", out string? rootValue) ||
TryReadOptionValue(args, ref index, "--source-root", out rootValue) ||
TryReadOptionValue(args, ref index, "--input", out rootValue))
{
rootPath = rootValue;
continue;
}
if (TryReadOptionValue(args, ref index, "--output", out string? outputValue) ||
TryReadOptionValue(args, ref index, "-o", out outputValue))
{
reportPath = outputValue;
continue;
}
rootPath ??= arg;
}
if (string.IsNullOrWhiteSpace(rootPath))
{
throw new InvalidOperationException("Missing --root <directory>.");
}
rootPath = Path.GetFullPath(rootPath);
if (!Directory.Exists(rootPath))
{
throw new DirectoryNotFoundException($"CFG scan root does not exist: {rootPath}");
}
reportPath = string.IsNullOrWhiteSpace(reportPath)
? Path.Combine(rootPath, "_cfg_scan_report.txt")
: Path.GetFullPath(reportPath);
string? directory = Path.GetDirectoryName(reportPath);
if (!string.IsNullOrWhiteSpace(directory))
{
Directory.CreateDirectory(directory);
}
return new Options(rootPath, reportPath);
}
private static bool TryReadOptionValue(string[] args, ref int index, string optionName, out string? value)
{
value = null;
string arg = args[index];
if (!string.Equals(arg, optionName, StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (index + 1 >= args.Length)
{
throw new InvalidOperationException($"Missing value for {optionName}.");
}
index++;
value = args[index];
return true;
}
private static CfgScanResult ScanFile(string rootPath, string path)
{
string relativePath = Path.GetRelativePath(rootPath, path);
try
{
var info = new FileInfo(path);
byte[] data = ReadPrefix(path, MaxConfigBytes);
bool sampled = info.Length > data.Length;
bool lzmaHeader = LzmaAloneDecoder.IsCompressed(data);
byte[]? prepared = LzmaAloneDecoder.TryPrepareData(data, MaxConfigBytes);
bool decodedLzma = prepared is not null && !ReferenceEquals(prepared, data);
byte[] textBytes = prepared ?? data;
if (lzmaHeader && prepared is null)
{
return new CfgScanResult(
path,
relativePath,
info.Length,
data.Length,
0,
"lzma-decode-failed",
string.Empty,
lzmaHeader,
sampled,
0,
string.Empty,
"LZMA header was present, but decompression failed.");
}
if (!TextPreviewDecoder.TryDecode(textBytes, preferKorean: false, out string text, out string encodingName))
{
return new CfgScanResult(
path,
relativePath,
info.Length,
data.Length,
textBytes.Length,
"decode-failed",
string.Empty,
lzmaHeader,
sampled,
0,
string.Empty,
"Text decoder rejected this CFG as binary, encrypted, or unsupported text.");
}
List<string> textureReferences = ExtractTextureReferences(text);
return new CfgScanResult(
path,
relativePath,
info.Length,
data.Length,
textBytes.Length,
decodedLzma ? "decoded-lzma" : "decoded-text",
encodingName,
lzmaHeader,
sampled,
textureReferences.Count,
string.Join("; ", textureReferences.Take(12)),
string.Empty);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException)
{
return new CfgScanResult(
path,
relativePath,
0,
0,
0,
"read-error",
string.Empty,
false,
false,
0,
string.Empty,
ex.Message);
}
}
private static byte[] ReadPrefix(string path, int maxBytes)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
int length = (int)Math.Min(stream.Length, maxBytes);
byte[] data = new byte[length];
int offset = 0;
while (offset < data.Length)
{
int read = stream.Read(data, offset, data.Length - offset);
if (read == 0)
{
break;
}
offset += read;
}
if (offset == data.Length)
{
return data;
}
Array.Resize(ref data, offset);
return data;
}
private static List<string> ExtractTextureReferences(string text)
{
return TextureReferenceRegex
.Matches(text)
.Select(match => match.Value.Trim().Replace('\\', '/'))
.Where(value => value.Length > 0)
.Distinct(StringComparer.OrdinalIgnoreCase)
.OrderBy(value => value, StringComparer.OrdinalIgnoreCase)
.ToList();
}
private static void WriteSummary(
string reportPath,
Options options,
string csvPath,
IReadOnlyList<CfgScanResult> results)
{
using var writer = new StreamWriter(reportPath, false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
writer.WriteLine("CF Rez Manager CFG scan");
writer.WriteLine();
writer.WriteLine($"Root: {options.RootPath}");
writer.WriteLine($"CFG files: {results.Count.ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Details CSV: {csvPath}");
writer.WriteLine();
writer.WriteLine("Status counts:");
foreach (IGrouping<string, CfgScanResult> group in results
.GroupBy(result => result.Status)
.OrderBy(group => group.Key, StringComparer.OrdinalIgnoreCase))
{
writer.WriteLine($" {group.Key}: {group.Count().ToString(CultureInfo.InvariantCulture)}");
}
writer.WriteLine();
writer.WriteLine($"Files with texture references: {results.Count(result => result.TextureReferenceCount > 0).ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine($"Texture references total: {results.Sum(result => result.TextureReferenceCount).ToString(CultureInfo.InvariantCulture)}");
writer.WriteLine();
writer.WriteLine("Preview behavior:");
writer.WriteLine(" decoded-text and decoded-lzma CFG files render text thumbnails with a CFG badge.");
writer.WriteLine(" decode-failed and lzma-decode-failed CFG files now open a diagnostic fallback preview with a CFG? badge.");
writer.WriteLine();
WriteTopList(writer, "Decode failures", results.Where(result => result.Status == "decode-failed" || result.Status == "lzma-decode-failed"));
WriteTopList(writer, "CFG files with texture references", results.Where(result => result.TextureReferenceCount > 0)
.OrderByDescending(result => result.TextureReferenceCount)
.ThenBy(result => result.RelativePath, StringComparer.OrdinalIgnoreCase));
}
private static void WriteTopList(TextWriter writer, string title, IEnumerable<CfgScanResult> values)
{
writer.WriteLine($"{title}:");
int count = 0;
foreach (CfgScanResult result in values.Take(80))
{
string detail = result.TextureReferenceCount > 0
? $" ({result.TextureReferenceCount.ToString(CultureInfo.InvariantCulture)} refs)"
: string.Empty;
writer.WriteLine($" {result.RelativePath}{detail}");
count++;
}
if (count == 0)
{
writer.WriteLine(" (none)");
}
writer.WriteLine();
}
private static void WriteCsv(string csvPath, IReadOnlyList<CfgScanResult> results)
{
using var writer = new StreamWriter(csvPath, false, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
writer.WriteLine("relative_path,status,encoding,source_bytes,read_bytes,decoded_bytes,lzma_header,sampled,texture_refs,texture_ref_preview,error");
foreach (CfgScanResult result in results)
{
writer.WriteLine(string.Join(
",",
Csv(result.RelativePath),
Csv(result.Status),
Csv(result.EncodingName),
result.SourceByteCount.ToString(CultureInfo.InvariantCulture),
result.ReadByteCount.ToString(CultureInfo.InvariantCulture),
result.DecodedByteCount.ToString(CultureInfo.InvariantCulture),
Csv(result.LzmaHeader ? "yes" : "no"),
Csv(result.Sampled ? "yes" : "no"),
result.TextureReferenceCount.ToString(CultureInfo.InvariantCulture),
Csv(result.TextureReferencePreview),
Csv(result.ErrorMessage)));
}
}
private static string Csv(string value)
{
return $"\"{value.Replace("\"", "\"\"", StringComparison.Ordinal)}\"";
}
[GeneratedRegex(@"(?i)(?:[A-Za-z]:)?[A-Za-z0-9_ ./\\\-\[\]\(\)]+?\.(?:dtx|dds|tga|png|jpg|jpeg|bmp)")]
private static partial Regex CreateTextureReferenceRegex();
}