Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
574 lines (476 loc) · 17.2 KB
/
Copy pathProgram.cs
File metadata and controls
574 lines (476 loc) · 17.2 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
using LTRData.Extensions.Buffers;
using LTRData.Extensions.CommandLine;
using LTRData.Extensions.Formatting;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
#pragma warning disable IDE0079 // Remove unnecessary suppression
#pragma warning disable IDE0057 // Use range operator
namespace ZipIO;
public static class Program
{
public static int Main(params string[] args)
{
if (args is null || args.Length < 2)
{
Console.Error.WriteLine(@"Syntax:
zipio add|list|cat|del|fromdir|todir|freshen|time [switches] zipfile [args ...]
More syntax help is available using 'zipio command --help', for example:
zipio add --help
");
return -1;
}
try
{
var sub_args = args.Skip(1).ToList();
switch (args[0].ToLowerInvariant())
{
case "add":
return ZipAdd(sub_args);
case "list":
return ZipList(sub_args);
case "del":
return ZipDel(sub_args);
case "fromdir":
return ZipFromDir(sub_args);
case "todir":
return ZipToDir(sub_args);
case "replace":
return ZipFreshen.FreshenOrReplace(ZipFreshen.FreshenOrReplaceOperation.Replace, sub_args);
case "freshen":
return ZipFreshen.FreshenOrReplace(ZipFreshen.FreshenOrReplaceOperation.Freshen, sub_args);
case "time":
return ZipTime.Time(sub_args);
case "cat":
return ZipCat(sub_args);
}
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine($"Unknown command: {args[0]}");
Console.ResetColor();
return -1;
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine(ex.JoinMessages());
Console.ResetColor();
return ex.HResult;
}
}
public static int ZipCat(params string[] args)
=> ZipCat((IEnumerable<string>)args);
public static int ZipCat(IEnumerable<string> cmdLine)
{
var cmd = CommandLineParser.ParseCommandLine(cmdLine, StringComparer.OrdinalIgnoreCase);
var isRegEx = false;
foreach (var arg in cmd)
{
if (arg.Key == "e")
{
isRegEx = true;
}
else if (arg.Key != "")
{
Console.WriteLine(@"Syntax:
zipio cat [-e] zipfile [file1 file2...]
Show contents of files within zip archive.
-e Use regular expressions to match file names
");
return -1;
}
}
if (!cmd.TryGetValue("", out var args) || args.Length == 0)
{
Console.WriteLine("Missing zip file path or file names.");
return 0;
}
var stdOut = Console.OpenStandardOutput();
using var archive = args[0] == "-"
? new ZipArchive(Console.OpenStandardInput(), ZipArchiveMode.Read)
: Uri.IsWellFormedUriString(args[0], UriKind.Absolute)
? new ZipArchive(new HttpClient().GetStreamAsync(args[0]).GetAwaiter().GetResult(), ZipArchiveMode.Read)
: ZipFile.OpenRead(args[0]);
foreach (var arg in args.Length < 2 ? SingleValueEnumerable.Get("") : args.Skip(1))
{
Func<ZipArchiveEntry, bool> matchFunc;
if (arg == "")
{
matchFunc = _ => true;
}
else if (!isRegEx)
{
var pattern = arg.Replace('\\', '/');
if (pattern.Contains('/'))
{
matchFunc = entry => entry.FullName == arg;
}
else
{
matchFunc = entry => entry.Name == arg;
}
}
else
{
var regex = new Regex(arg);
matchFunc = entry => regex.IsMatch(entry.FullName);
}
foreach (var entry in archive.Entries.Where(matchFunc))
{
using var stream = entry.Open();
stream.CopyTo(stdOut);
}
}
return 0;
}
public static int ZipList(params string[] args)
=> ZipList((IEnumerable<string>)args);
public static int ZipList(IEnumerable<string> cmdLine)
{
var cmd = CommandLineParser.ParseCommandLine(cmdLine, StringComparer.OrdinalIgnoreCase);
var longlisting = false;
foreach (var arg in cmd)
{
if (arg.Key.Equals("l", StringComparison.OrdinalIgnoreCase)
|| arg.Key.Equals("long", StringComparison.OrdinalIgnoreCase))
{
longlisting = true;
}
else if (arg.Key == "")
{
}
else
{
Console.WriteLine(@"Syntax:
zipio list [--long] zipfile1 [zipfile2 ...]
Show contents of zip archive.
-l
--long Detailed file information
");
return -1;
}
}
if (!cmd.TryGetValue("", out var args) || args.Length == 0)
{
Console.WriteLine("Missing zip file paths.");
return 0;
}
foreach (var arg in args.SelectMany(path =>
{
if (path == "-")
{
return SingleValueEnumerable.Get("-");
}
if (Uri.IsWellFormedUriString(path, UriKind.Absolute))
{
return SingleValueEnumerable.Get(path);
}
var dir = Path.GetDirectoryName(path);
if (string.IsNullOrWhiteSpace(dir))
{
dir = ".";
}
try
{
return Directory.EnumerateFiles(dir, Path.GetFileName(path));
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine($"{path}: {ex.GetBaseException().Message}");
Console.ResetColor();
return [];
}
}))
{
try
{
using var archive = arg == "-"
? new ZipArchive(Console.OpenStandardInput(), ZipArchiveMode.Read)
: Uri.IsWellFormedUriString(arg, UriKind.Absolute)
? new ZipArchive(new HttpClient().GetStreamAsync(arg).GetAwaiter().GetResult(), ZipArchiveMode.Read)
: ZipFile.OpenRead(arg);
foreach (var entry in archive.Entries)
{
if (longlisting)
{
Console.WriteLine($"{entry.LastWriteTime.LocalDateTime,19:g} {entry.Length,15:#,##0} ({entry.CompressedLength,15:#,##0}) {entry.FullName}");
}
else
{
Console.WriteLine(entry.FullName);
}
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Error.WriteLine($"{arg}: {ex.GetBaseException().Message}");
Console.ResetColor();
}
}
return 0;
}
internal static IEnumerable<string> ResolveWildcards(string path, SearchOption searchOption)
{
var dir = Path.GetDirectoryName(path) ?? "";
var searchdir = dir;
if (string.IsNullOrWhiteSpace(searchdir))
{
searchdir = ".";
}
var file = Path.GetFileName(path);
path = Path.Combine(searchdir, file);
var prefix_length = path.Length - file.Length;
return Directory
.EnumerateFiles(searchdir, file, searchOption)
.Select(entry => Path.Combine(dir, entry.Substring(prefix_length)));
}
public static int ZipAdd(params string[] args)
=> ZipAdd((IEnumerable<string>)args);
public static int ZipAdd(IEnumerable<string> cmdLine)
{
var cmd = CommandLineParser.ParseCommandLine(cmdLine, StringComparer.OrdinalIgnoreCase);
string? zip_path = null;
IEnumerable<string>? files_to_add = null;
var searchOption = SearchOption.TopDirectoryOnly;
var purge = false;
var newer = false;
var cont = false;
foreach (var arg in cmd)
{
if (arg.Key.Equals("s", StringComparison.OrdinalIgnoreCase)
|| arg.Key.Equals("r", StringComparison.OrdinalIgnoreCase)
|| arg.Key.Equals("recurse", StringComparison.OrdinalIgnoreCase))
{
searchOption = SearchOption.AllDirectories;
}
else if (arg.Key.Equals("newer", StringComparison.OrdinalIgnoreCase)
|| arg.Key.Equals("n", StringComparison.OrdinalIgnoreCase))
{
newer = true;
}
else if (arg.Key.Equals("purge", StringComparison.OrdinalIgnoreCase)
|| arg.Key.Equals("p", StringComparison.OrdinalIgnoreCase))
{
purge = true;
}
else if (arg.Key.Equals("continue", StringComparison.OrdinalIgnoreCase)
|| arg.Key.Equals("c", StringComparison.OrdinalIgnoreCase))
{
cont = true;
}
else if (arg.Key == "")
{
zip_path = arg.Value.FirstOrDefault();
files_to_add = arg.Value.Skip(1);
}
else
{
Console.Error.WriteLine(@"Syntax:
zipio add [-s] [--newer] [--purge] [--continue] file.zip [files ...]
Add files to zip archive.
-s
-r
--recurse Recurse into subdirectories.
-n
--newer Only files newer than existing files in archive, or files that do
not already exist in archive.
-p
--purge Remove existing files in archive that are not found on disk
-c
--continue Ignore source file read errors
");
return 0;
}
}
if (zip_path is null || files_to_add is null)
{
Console.Error.WriteLine("Missing zip file path and source file names");
return 0;
}
using var archive = ZipFile.Open(zip_path, ZipArchiveMode.Update);
var existing_files = new List<string>();
foreach (var file in files_to_add.SelectMany(path => ResolveWildcards(path, searchOption)))
{
try
{
var fileinfo = new FileInfo(file);
using var source = fileinfo.OpenRead();
var entry = archive
.Entries
.FirstOrDefault(e => e.FullName.Equals(file, StringComparison.CurrentCultureIgnoreCase));
var lastWriteTimeUtc = fileinfo.LastWriteTimeUtc;
if (entry is null)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Adding: {file}");
Console.ResetColor();
entry = archive.CreateEntry(file, CompressionLevel.Optimal);
using var entryStream = entry.Open();
source.CopyTo(entryStream);
entryStream.SetLength(source.Length);
entry.LastWriteTime = lastWriteTimeUtc.ToLocalTime();
}
else if (!newer ||
(lastWriteTimeUtc - entry.LastWriteTime.UtcDateTime).TotalSeconds > 2)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"Updating: {file}");
Console.ResetColor();
using var entryStream = entry.Open();
source.CopyTo(entryStream);
entryStream.SetLength(source.Length);
entry.LastWriteTime = lastWriteTimeUtc.ToLocalTime();
}
if (purge && entry is not null)
{
existing_files.Add(entry.FullName);
}
}
catch (Exception ex) when (cont)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Error.WriteLine($"File '{file}': {ex.JoinMessages()}");
Console.ResetColor();
}
}
if (purge)
{
var to_be_removed = archive.Entries
.Where(entry => !existing_files.Contains(entry.FullName, StringComparer.OrdinalIgnoreCase))
.ToList();
foreach (var entry in to_be_removed)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine($"Removing '{entry.FullName}'");
Console.ResetColor();
entry.Delete();
}
}
return 0;
}
public static int ZipDel(params string[] args)
=> ZipDel((IEnumerable<string>)args);
public static int ZipDel(IEnumerable<string> cmdLine)
{
var cmd = CommandLineParser.ParseCommandLine(cmdLine, StringComparer.OrdinalIgnoreCase);
foreach (var arg in cmd)
{
if (arg.Key != "")
{
Console.WriteLine(@"Syntax:
zipio del zipfile file1 [file2 ...]
Deletes files from zip archive.
");
return -1;
}
}
if (!cmd.TryGetValue("", out var args) || args.Length < 2)
{
Console.WriteLine("Missing zip archive path or file names.");
return 0;
}
using var archive = ZipFile.Open(args[0], ZipArchiveMode.Update);
var entries = archive
.Entries
.Where(e => args.Skip(1).Any(a => Regex.IsMatch(e.FullName, a, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace)))
.ToArray();
foreach (var entry in entries)
{
Console.WriteLine(entry.FullName);
entry.Delete();
}
return 0;
}
public static int ZipFromDir(params string[] args)
=> ZipFromDir((IEnumerable<string>)args);
public static int ZipFromDir(IEnumerable<string> cmdLine)
{
var cmd = CommandLineParser.ParseCommandLine(cmdLine, StringComparer.OrdinalIgnoreCase);
foreach (var arg in cmd)
{
if (arg.Key != "")
{
Console.Error.WriteLine(@"Syntax:
zipio fromdir zipfile directory
Create a zip archive from directory contents.
");
return -1;
}
}
if (!cmd.TryGetValue("", out var args) || args.Length != 2)
{
Console.WriteLine("Missing zip archive or directory path.");
return 0;
}
ZipFile.CreateFromDirectory(args[1], args[0]);
return 0;
}
public static int ZipToDir(params string[] args)
=> ZipToDir((IEnumerable<string>)args);
public static int ZipToDir(IEnumerable<string> cmdLine)
{
var cmd = CommandLineParser.ParseCommandLine(cmdLine, StringComparer.OrdinalIgnoreCase);
var overwriteFiles = false;
foreach (var arg in cmd)
{
if (arg.Key.Equals("o", StringComparison.OrdinalIgnoreCase)
|| arg.Key.Equals("overwrite", StringComparison.OrdinalIgnoreCase))
{
overwriteFiles = true;
}
else if (arg.Key != "")
{
Console.Error.WriteLine(@"Syntax:
zipio todir [--overwrite] zipfile directory
Extract contents of zip archive to a directory.
-o
--overwrite Overwrite existing files
");
return -1;
}
}
if (!cmd.TryGetValue("", out var args) || args.Length != 2)
{
Console.WriteLine("Missing zip archive or directory path.");
return 0;
}
if (Uri.IsWellFormedUriString(args[0], UriKind.Absolute))
{
using var httpClient = new HttpClient();
using var archive = new ZipArchive(httpClient.GetStreamAsync(args[0]).GetAwaiter().GetResult(), ZipArchiveMode.Read);
if (overwriteFiles)
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP
archive.ExtractToDirectory(args[1], overwriteFiles);
#else
throw new PlatformNotSupportedException("Overwrite mode is not supported on .NET Framework 4.x or .NET Standard 2.0 or lower. Required: .NET Core or .NET 5.0 or later.");
#endif
}
else
{
archive.ExtractToDirectory(args[1]);
}
}
else
{
if (overwriteFiles)
{
#if NETSTANDARD2_1_OR_GREATER || NETCOREAPP
ZipFile.ExtractToDirectory(args[0], args[1], overwriteFiles);
#else
throw new PlatformNotSupportedException("Overwrite mode is not supported on .NET Framework 4.x or .NET Standard 2.0 or lower. Required: .NET Core or .NET 5.0 or later.");
#endif
}
else
{
ZipFile.ExtractToDirectory(args[0], args[1]);
}
}
return 0;
}
}