-
Notifications
You must be signed in to change notification settings - Fork 4
/
Utils.cs
452 lines (400 loc) · 17 KB
/
Utils.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
using System.Security.Cryptography;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using Spectre.Console;
namespace Kiraio.LoveL2D
{
public static class Utils
{
const string LAST_OPEN_FILE = "last_open.txt";
internal static string NormalizePath(string path)
{
string[] pathSegments = path.Split(
Path.DirectorySeparatorChar,
Path.AltDirectorySeparatorChar
);
List<string> normalizedSegments = new();
foreach (string segment in pathSegments)
{
if (segment == "..")
{
if (normalizedSegments.Count > 0)
{
normalizedSegments.RemoveAt(normalizedSegments.Count - 1);
}
}
else if (segment != "." && !string.IsNullOrEmpty(segment))
{
normalizedSegments.Add(segment);
}
}
return string.Join(Path.DirectorySeparatorChar.ToString(), normalizedSegments);
}
/// <summary>
/// Get SHA-256 hash of a file.
/// </summary>
/// <param name="filePath">Source file.</param>
/// <returns>SHA-256 hash.</returns>
internal static string GetSHA256(string filePath)
{
try
{
using FileStream fileStream = File.OpenRead(filePath);
using SHA256 hash = SHA256.Create();
fileStream.Position = 0; // Make sure position at 0
byte[] hashBytes = hash.ComputeHash(fileStream);
return BitConverter.ToString(hashBytes).Replace("-", "").ToLower(); // Normalize the return
}
catch (Exception ex)
{
AnsiConsole.WriteException(ex);
}
return string.Empty;
}
internal static string ReplaceStringInFile(
string filePath,
string oldString,
string newString,
string? outputFile = null
)
{
outputFile ??= filePath;
StringBuilder stringBuilder = new();
using (StreamReader reader = new(filePath))
{
string? line;
while ((line = reader?.ReadLine()) != null)
{
// Replace the string while reading
line = line.Replace(oldString, newString);
stringBuilder.AppendLine(line);
}
}
// Write the modified content back to the file
using StreamWriter writer = new(outputFile);
writer.Write(stringBuilder.ToString());
return outputFile;
}
/// <summary>
/// Copy data from a file to an other, replacing search term, ignoring case.
/// </summary>
/// <param name="originalFile"></param>
/// <param name="outputFile"></param>
/// <param name="searchTerm"></param>
/// <param name="replaceTerm"></param>
internal static string ReplaceStringInBinaryFile(
string originalFile,
string outputFile,
string searchTerm,
string replaceTerm
)
{
byte b;
//UpperCase bytes to search
byte[] searchBytes = Encoding.UTF8.GetBytes(searchTerm.ToUpper());
//LowerCase bytes to search
byte[] searchBytesLower = Encoding.UTF8.GetBytes(searchTerm.ToLower());
//Temporary bytes during found loop
byte[] bytesToAdd = new byte[searchBytes.Length];
//Search length
int searchBytesLength = searchBytes.Length;
//First Upper char
byte searchByte0 = searchBytes[0];
//First Lower char
byte searchByte0Lower = searchBytesLower[0];
//Replace with bytes
byte[] replaceBytes = Encoding.UTF8.GetBytes(replaceTerm);
int counter = 0;
using (FileStream inputStream = File.OpenRead(originalFile))
{
//input length
long srcLength = inputStream.Length;
using BinaryReader inputReader = new(inputStream);
using FileStream outputStream = File.OpenWrite(outputFile);
using BinaryWriter outputWriter = new(outputStream);
for (int nSrc = 0; nSrc < srcLength; ++nSrc)
//first byte
if ((b = inputReader.ReadByte()) == searchByte0 || b == searchByte0Lower)
{
bytesToAdd[0] = b;
int nSearch = 1;
//next bytes
for (; nSearch < searchBytesLength; ++nSearch)
{
//get byte, save it and test
if (
(b = bytesToAdd[nSearch] = inputReader.ReadByte())
!= searchBytes[nSearch]
&& b != searchBytesLower[nSearch]
)
{
break; //fail
}
}
//Avoid overflow. No need, in my case, because no chance to see searchTerm at the end.
//else if (nSrc + nSearch >= srcLength)
// break;
if (nSearch == searchBytesLength)
{
//success
++counter;
outputWriter.Write(replaceBytes);
nSrc += nSearch - 1;
}
else
{
//failed, add saved bytes
outputWriter.Write(bytesToAdd, 0, nSearch + 1);
nSrc += nSearch;
}
}
else
outputWriter.Write(b);
}
AnsiConsole.MarkupLineInterpolated(
$"Successfully replaced [green]string[/] in [green]{originalFile}[/]: [green]{counter}[/]"
);
return outputFile;
}
internal static string ExtractZipEntry(
string zipFilePath,
string entryName,
string? outputFilePath = null
)
{
outputFilePath ??= Path.Combine(
Path.GetDirectoryName(zipFilePath) ?? string.Empty,
entryName
);
try
{
using ZipFile zipFile = new(zipFilePath);
// Log all entry names in the ZIP file for debugging purposes
// Console.WriteLine("Entries in ZIP file:");
// foreach (ZipEntry e in zipFile)
// {
// Console.WriteLine(e.Name);
// }
entryName = ZipEntry.CleanName(entryName); // Normalize entry name path
ZipEntry entry = zipFile.GetEntry(entryName);
if (entry != null)
{
// Ensure the output directory exists
string outputDirectory = Path.GetDirectoryName(outputFilePath) ?? string.Empty;
if (!string.IsNullOrEmpty(outputDirectory))
Directory.CreateDirectory(outputDirectory);
using Stream zipStream = zipFile.GetInputStream(entry);
using FileStream outputFileStream = File.Create(outputFilePath);
zipStream.CopyTo(outputFileStream);
AnsiConsole.MarkupLineInterpolated(
$"Zip Entry [green]{entryName}[/] extracted as [green]{outputFilePath}[/]."
);
}
else
AnsiConsole.MarkupLineInterpolated(
$"Zip Entry [red]{entryName}[/] not found in the ZIP file."
);
}
catch (Exception ex)
{
AnsiConsole.WriteException(ex);
}
return outputFilePath;
}
internal static string ModifyZipContents(
string inputFile,
string outputFile,
List<(string entryName, byte[] entryData)> modifiedFiles,
List<string>? ignoredFiles = null
)
{
try
{
AnsiConsole.MarkupLineInterpolated($"Modifying Zip archive: [green]{inputFile}[/]...");
// Read the input ZIP file into memory
byte[] zipBytes = File.ReadAllBytes(inputFile);
using (MemoryStream zipStream = new(zipBytes))
{
// Unpack the ZIP file into memory
using ZipFile inputZipFile = new(zipStream);
// Create a new in-memory stream to store the modified ZIP file
using MemoryStream modifiedZipStream = new();
// Create a ZipOutputStream to write the modified contents
using (ZipOutputStream zipOutputStream = new(modifiedZipStream))
{
AnsiConsole.MarkupLineInterpolated($"Rewriting Zip archive [green]{outputFile}[/]...");
foreach (ZipEntry entry in inputZipFile)
{
// Check if the entry should be modified and is not in the ignored list
(string? entryName, byte[] entryData) = modifiedFiles.FirstOrDefault(
f => ZipEntry.CleanName(f.entryName) == entry.Name
);
bool ignored =
ignoredFiles?.Any(file => ZipEntry.CleanName(file) == entry.Name)
?? false;
if (!ignored)
{
if (entryName != null)
{
AnsiConsole.MarkupLineInterpolated(
$"Modifying Zip Entry: [green]{entryName}[/]..."
);
// Modify the entry content
byte[] modifiedContentBytes = entryData;
ZipEntry modifiedEntry = new(entry.Name);
zipOutputStream.PutNextEntry(modifiedEntry);
zipOutputStream.Write(
modifiedContentBytes,
0,
modifiedContentBytes.Length
);
zipOutputStream.CloseEntry();
}
else
{
// Copy unchanged entries to the modified ZIP
using Stream entryStream = inputZipFile.GetInputStream(entry);
// Create a new entry and copy the content
ZipEntry newEntry = new(entry.Name);
zipOutputStream.PutNextEntry(newEntry);
byte[] buffer = new byte[4096];
int bytesRead;
while (
(bytesRead = entryStream.Read(buffer, 0, buffer.Length)) > 0
)
{
zipOutputStream.Write(buffer, 0, bytesRead);
}
zipOutputStream.CloseEntry();
}
}
else
AnsiConsole.MarkupLineInterpolated($"Skipping Zip Entry: [green]{entry.Name}[/]");
}
}
// Save the modified ZIP file to disk
File.WriteAllBytes(outputFile, modifiedZipStream.ToArray());
}
AnsiConsole.MarkupLineInterpolated(
$"Zip archive modified [green]successfully[/]."
);
}
catch (Exception ex)
{
AnsiConsole.WriteException(ex);
}
return outputFile;
}
internal static string UnZip(string filePath, string? outputFolder = null)
{
outputFolder ??= Path.Combine(
Path.GetDirectoryName(filePath) ?? string.Empty,
Path.GetFileNameWithoutExtension(filePath)
);
try
{
using ZipFile zipFile = new(filePath);
Directory.CreateDirectory(outputFolder);
if (zipFile.Count > 0)
{
foreach (ZipEntry entry in zipFile)
{
string? entryPath = Path.Combine(outputFolder, entry.Name);
Directory.CreateDirectory(Path.GetDirectoryName(entryPath) ?? string.Empty);
if (!entry.IsDirectory)
{
try
{
using Stream inputStream = zipFile.GetInputStream(entry);
using FileStream outputStream = File.Create(entryPath);
inputStream.CopyTo(outputStream);
}
catch (Exception ex)
{
AnsiConsole.WriteException(ex);
}
}
}
}
}
catch (Exception ex)
{
AnsiConsole.WriteException(ex);
}
return outputFolder;
}
internal static string Zip(string sourceFolder, string? outputFile = null)
{
outputFile ??= $"{Path.GetFileName(sourceFolder)}.zip";
string[] files = GetFilesRecursive(sourceFolder);
try
{
using ZipOutputStream zipStream = new(File.Create(outputFile));
foreach (string filePath in files)
{
FileInfo file = new(filePath);
string entryName = filePath[sourceFolder.Length..].TrimStart('\\'); // Keep file structure by including the folder
ZipEntry entry = new(entryName) { DateTime = DateTime.Now, Size = file.Length };
zipStream.PutNextEntry(entry);
using FileStream fileStream = file.OpenRead();
byte[] buffer = new byte[4096]; // Optimum size
int bytesRead;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0)
zipStream.Write(buffer, 0, bytesRead);
}
}
catch (Exception ex)
{
AnsiConsole.WriteException(ex);
}
return outputFile;
}
/// <summary>
/// Get all files from a folder.
/// </summary>
/// <param name="sourceFolder"></param>
/// <returns>File paths.</returns>
internal static string[] GetFilesRecursive(string sourceFolder)
{
return Directory.GetFiles(sourceFolder, "*.*", SearchOption.AllDirectories);
}
internal static void SaveLastOpenedFile(string directoryPath)
{
try
{
// Write the last opened directory to a text file
using StreamWriter writer = new(LAST_OPEN_FILE);
writer.WriteLine($"last_opened={directoryPath}");
}
catch (Exception ex)
{
AnsiConsole.WriteException(ex);
}
}
internal static string GetLastOpenedFile()
{
if (!File.Exists(LAST_OPEN_FILE))
return string.Empty;
string lastOpenedDirectory = string.Empty;
try
{
// Read the last opened directory from the text file
using StreamReader reader = new(LAST_OPEN_FILE);
string? line;
while ((line = reader.ReadLine()) != null)
{
if (line.StartsWith("last_opened="))
{
lastOpenedDirectory = line["last_opened=".Length..];
break;
}
}
}
catch (Exception ex)
{
AnsiConsole.WriteException(ex);
}
return lastOpenedDirectory;
}
}
}