-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
657 lines (578 loc) · 24.7 KB
/
Program.cs
File metadata and controls
657 lines (578 loc) · 24.7 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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
using Linea.Args;
using Linea.Utils;
using Some.Restraint;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
namespace FileCopyUtil
{
public static class Program
{
static void Main(string[] args)
{
ArgumentDescriptorCollection expected = new ArgumentDescriptorCollection();
expected.LoadFromXML(typeof(Program).Assembly.GetManifestResourceStream("FileCopyUtil.Arguments.xml"));
string commands = string.Empty;
var splitargs = Environment.GetCommandLineArgs();
if (splitargs.Length > 1)
{
var ExecutableNameLen = splitargs[0].Length;
if (Environment.CommandLine.StartsWith("\""))
ExecutableNameLen += 2;
commands = Environment.CommandLine.Substring(ExecutableNameLen).Trim();
}
ParsedArguments p = ParsedArguments.ProcessArguments(commands, expected);
if (p.HasFlag("debug"))
Debugger.Launch();
bool exit = false;
bool shouldExplain = p.HasFlag("e");
if (shouldExplain)
{
Console.Error.WriteLine();
if (p.Count <= 1)
{
Console.Error.WriteLine("************************");
Console.Error.WriteLine("[No arguments received]");
Console.Error.WriteLine("************************");
}
else
{
IEnumerable<string> explanations = p.GetArgumentExplanations().RowsToFixedLengthStrings(separator: " | ", maxColumnLen: 24);
int explLen = explanations.First().Length;
Console.Error.WriteLine(new string('*', explLen));
foreach (string item in explanations)
{
Console.Error.WriteLine(item);
}
Console.Error.WriteLine(new string('*', explLen));
}
}
if (p.HasFlag("h"))
{
exit = true;
Stream source = typeof(Program).Assembly.GetManifestResourceStream("FileCopyUtil.help.txt");
TextWriter destination = Console.Out;
if (source != null)
{
using (StreamReader reader = new StreamReader(source))
{
string line;
while ((line = reader.ReadLine()) != null)
{
destination.WriteLine(line);
}
}
}
else
{
Console.Error.WriteLine("Help file not found.");
}
}
if (!exit && p.HasErrors)
{
exit = true;
p.GetErrorsDescriptions().ForEach(s => Console.Error.WriteLine(s));
Console.Error.WriteLine(expected.CreateUsageString(Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0])));
}
if (exit)
return;
//-----------
string baseDir, UserArg;
bool isRecursiveSelection = p.HasFlag("r") || p.HasFlag("rs");
bool isRecursiveCopy = p.HasFlag("r") || p.HasFlag("rc");
bool flatten = p.HasFlag("flatten");
bool selectFiles, selectDirs;
if (!(p.HasFlag("f") || p.HasFlag("d") || p.HasFlag("fd")))
{
selectFiles = selectDirs = true;
}
else
{
selectFiles = p.HasFlag("f") || p.HasFlag("fd");
selectDirs = p.HasFlag("d") || p.HasFlag("fd");
}
bool IsPathRegex = false;
Regex userRegex = null;
ParsedArgument arg;
UserArg = p["arg"].Value;
if (p.HasArgument("base", out arg))
{
baseDir = arg.Value;
}
else baseDir = Environment.CurrentDirectory;
baseDir = baseDir.TrimEnd(Path.DirectorySeparatorChar);
if (shouldExplain)
{
Console.Error.WriteLine("Base Directory: {0}", baseDir);
}
string sourceRoot;
if (p.HasArgument("SourceRoot"))
sourceRoot = p["SourceRoot"];
else sourceRoot = baseDir;
if (!Directory.Exists(sourceRoot))
{
sourceRoot = Path.Combine(Environment.CurrentDirectory, sourceRoot);
}
sourceRoot = Path.GetFullPath(sourceRoot);
bool verbose = p.HasFlag("v");
if (p.HasFlag("watch"))
{
Options opt = Options.None;
if (flatten) opt |= Options.Flatten;
if (verbose) opt |= Options.Verbose;
if (isRecursiveCopy) opt |= Options.RecursiveCopy;
if (isRecursiveSelection) opt |= Options.RecursiveSelection;
if (selectFiles) opt |= Options.CopyFiles;
if (selectDirs) opt |= Options.CopyDirectories;
SetupFileWatch(UserArg, sourceRoot, p["destinationRoot"], opt);
return;
}
if (p.HasFlag("nx"))
{
userRegex = new Regex(UserArg);
IsPathRegex = false;
}
else if (p.HasFlag("px"))
{
userRegex = new Regex(UserArg);
IsPathRegex = true;
}
else
{
//not a regex, let's clean it before use
UserArg = UserArg.TrimEnd(Path.DirectorySeparatorChar);
}
HashSet<string> allFoundEntries = new HashSet<string>();
bool EntryMatches(string entry)
{
if (userRegex != null)
{
string ToMatch = IsPathRegex ? entry : Path.GetFileName(entry);
return userRegex.IsMatch(ToMatch);
}
else
{
return true;
}
}
;
if (userRegex != null)
{
if (isRecursiveSelection)
{
// Select n entries recursively from base directory using Name-Regex > <arg> -x -rs
// Select n entries recursively from base directory using Path-Regex > <arg> -px -rs
NavigateFileSystem(baseDir,
shouldExploreThisDirectory: dir =>
!isRecursiveCopy //if the copy process is not recursive, we should check if the contents of the folder should be included separately
|| !allFoundEntries.Contains(dir)/* if the copy process IS recursive and the folder is already in the copy list,
* all content will already be included and we don't need further exploration */,
shouldConsiderThisDirectory: dir => selectDirs && EntryMatches(dir),
shouldConsiderThisFile: file => selectFiles && EntryMatches(file),
OnFileFound: entry => allFoundEntries.Add(entry),
OnDirectoryFound: entry => allFoundEntries.Add(entry)
);
}
else
{
// Select n entries from current directory using Name-Regex > <arg> -x
Directory.EnumerateFileSystemEntries(baseDir).ForEach(
entry =>
{
if (((selectFiles && File.Exists(entry)) || (selectDirs && Directory.Exists(entry))) && EntryMatches(entry))
allFoundEntries.Add(entry);
});
}
}
else
{
//normal search
if (isRecursiveSelection)
{
LoopAllDirectoriesRecursively(baseDir, _ => true, dir =>
{
string combined = Path.Combine(dir, UserArg);
if ((selectFiles && File.Exists(combined)) || (selectDirs && Directory.Exists(combined)))
allFoundEntries.Add(combined);
});
}
else
{
string ToCopy = UserArg;
if (!Path.IsPathRooted(ToCopy))
{
ToCopy = Path.Combine(baseDir, ToCopy);
}
if ((selectFiles && File.Exists(ToCopy)) || (selectDirs && Directory.Exists(ToCopy)))
{
//absolute file or folder path
allFoundEntries.Add(ToCopy);
}
else
{
//maybe relative?
string combined = Path.Combine(baseDir, ToCopy);
if ((selectFiles && File.Exists(combined)) || (selectDirs && Directory.Exists(combined)))
allFoundEntries.Add(combined);
}
}
}
Action<string, string> OnCopy = null;
if (verbose) OnCopy = ReportCopy;
if (flatten)
{
CopyFlattened(allFoundEntries, p["destinationRoot"], CopyDirectoryContents: isRecursiveCopy, OnCopied: OnCopy);
}
else
{
CopyFromRootPath(allFoundEntries, sourceRoot, p["destinationRoot"], CopyDirectoryContents: isRecursiveCopy, OnCopied: OnCopy);
}
}
private static void ReportCopy(string from, string to)
{
Console.WriteLine("Copied : {0} => {1}", from, to);
}
[Flags]
enum Options
{
None = 0,
CopyFiles = 1,
CopyDirectories = 2,
RecursiveCopy = 4,
RecursiveSelection = 8,
Flatten = 16,
Verbose = 32,
Recursive = RecursiveSelection | RecursiveCopy,
CopyAll = CopyFiles | CopyDirectories
}
private static void SetupFileWatch(string fileRegex, string source, string destination, Options opt)
{
bool recursiveCopy = opt.HasFlag(Options.RecursiveCopy);
bool recursiveSelection = opt.HasFlag(Options.RecursiveSelection);
bool flatten = opt.HasFlag(Options.Flatten);
bool verbose = opt.HasFlag(Options.Verbose);
bool abort = false;
if (!Directory.Exists(source))
{
Console.Error.WriteLine("The watch source is invalid!");
abort = true;
}
if (!Directory.Exists(destination))
{
Console.Error.WriteLine("The watch source is invalid!");
abort = true;
}
if (abort) return;
HashSet<string> toCopy = new HashSet<string>();
void ActualCopy()
{
lock (toCopy)
{
while (toCopy.Count > 0)
{
string s = toCopy.First();
toCopy.Remove(s);
if (File.Exists(s) && !opt.HasFlag(Options.CopyFiles))
{
continue;
}
if (Directory.Exists(s) && !opt.HasFlag(Options.CopyDirectories))
{
continue;
}
int retries = 0;
if (verbose) Console.Error.Write($"Copying : {s} ...");
while (true)
{
try
{
if (flatten)
{
CopyFlattened(s, destination, CopyDirectoryContents: recursiveCopy, OnCopied: null);
}
else
{
CopyFromRootPath(s, source, destination, CopyDirectoryContents: recursiveCopy, ShouldOverride: _ => true);
}
if (verbose) Console.Error.WriteLine($"Done [{DateTime.Now:H:mm:ss}]");
break;
}
catch (Exception)
{
retries++;
System.Threading.Thread.Sleep(1000);
if (verbose && retries % 5 == 0)
Console.Error.Write($".");
}
}
}
}
}
Regex r = new Regex(fileRegex);
Defer d = Defer.UsingTask()
.ForAtLeast(500).ToExecute(ActualCopy)
.Named("DeferredCopy").Build();
void BufferAction(string s)
{
if (r.IsMatch(s))
{
lock (toCopy)
{
toCopy.Add(s);
d.Trigger();
}
}
}
CreateFileWatcher(source, recursiveSelection, BufferAction);
Console.Error.WriteLine("Created file watch from ");
Console.Error.WriteLine($" {source}");
Console.Error.WriteLine("to ");
Console.Error.WriteLine($" {destination}");
object dummyMonitor = new object();
while (true)
{
lock (dummyMonitor)
{
Monitor.Wait(dummyMonitor, 1000);
}
}
}
public static void CreateFileWatcher(string path, bool recursive, Action<string> deleg)
{
// Add event handlers.
FileSystemEventHandler f = new FileSystemEventHandler((object source, FileSystemEventArgs e) =>
{
switch (e.ChangeType)
{
case WatcherChangeTypes.Created:
case WatcherChangeTypes.Renamed:
case WatcherChangeTypes.Changed:
deleg(e.FullPath);
break;
case WatcherChangeTypes.All:
case WatcherChangeTypes.Deleted:
break;
}
}
);
RenamedEventHandler f2 = new RenamedEventHandler((object source, RenamedEventArgs e) => deleg(e.FullPath));
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher
{
Path = path,
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName,
IncludeSubdirectories = recursive
};
watcher.Changed += f;
watcher.Created += f;
watcher.Deleted += f;
watcher.Renamed += f2;
// Begin watching.
watcher.EnableRaisingEvents = true;
}
public static void LoopAllDirectoriesRecursively(string rootFolder, Func<string, bool> shouldConsiderThisDir, Action<String> OnDirFound) =>
NavigateFileSystem(
rootFolder,
_ => true, //explore all
shouldConsiderThisDir, OnDirFound,
_ => false, _ => { } //ignore files
);
public static bool CopyFlattened(string entryToCopy_absolutePath, string destination, bool CopyDirectoryContents = true, Action<string, string> OnCopied = null)
{
bool IsDirectory;
string name;
if (Directory.Exists(entryToCopy_absolutePath))
{
IsDirectory = true;
name = Path.GetFileName(entryToCopy_absolutePath);
}
else if (File.Exists(entryToCopy_absolutePath))
{
IsDirectory = false;
name = Path.GetFileName(entryToCopy_absolutePath);
}
else
{
//this entry does not exist, nothing to do
return false;
}
string newPath = Path.Combine(destination, name);
if (IsDirectory)
{
Directory.CreateDirectory(newPath);
OnCopied?.Invoke(entryToCopy_absolutePath, newPath);
if (CopyDirectoryContents)
{
//The elements inside the folder must not be flattened
bool result = true;
NavigateFileSystem(entryToCopy_absolutePath, _ => true, s =>
result &= CopyFromRootPath(s, entryToCopy_absolutePath, newPath, CopyDirectoryContents: CopyDirectoryContents, OnCopied: OnCopied)
);
return result;
}
else
{
return true;
}
}
else
{
Directory.CreateDirectory(Directory.GetParent(newPath).FullName);
if (File.Exists(newPath))
{
File.Delete(newPath);
}
File.Copy(entryToCopy_absolutePath, newPath);
OnCopied?.Invoke(entryToCopy_absolutePath, newPath);
return true;
}
}
public static bool CopyFlattened(IEnumerable<string> entriesToCopy, string destinationRoot, bool CopyDirectoryContents = true, Action<string, string> OnCopied = null)
{
bool result = true;
foreach (var entryToCopy_absolutePath in entriesToCopy)
{
result &= CopyFlattened(entryToCopy_absolutePath, destinationRoot, CopyDirectoryContents, OnCopied: OnCopied);
}
return result;
}
public static bool CopyFromRootPath(IEnumerable<string> entriesToCopy, string sourceRoot, string destinationRoot, bool CopyDirectoryContents = true, Action<string, string> OnCopied = null)
{
bool success = true;
foreach (var item in entriesToCopy)
{
bool copied = CopyFromRootPath(item, sourceRoot, destinationRoot, CopyDirectoryContents, OnCopied: OnCopied);
success &= copied;
}
return success;
}
public static bool CopyFromRootPath(string entryToCopy_absolutePath, string sourceRoot, string destinationRoot,
bool CopyDirectoryContents = true, Func<string, bool> ShouldOverride = null,
Action<string, string> OnCopied = null)
{
bool IsDirectory;
if (Directory.Exists(entryToCopy_absolutePath))
{
IsDirectory = true;
}
else if (File.Exists(entryToCopy_absolutePath))
{
IsDirectory = false;
}
else
{
//this entry does not exist, nothing to do
return false;
}
sourceRoot = sourceRoot.TrimEnd(Path.DirectorySeparatorChar);
destinationRoot = destinationRoot.TrimEnd(Path.DirectorySeparatorChar);
string destinationSubPath;
if (entryToCopy_absolutePath.StartsWith(sourceRoot, StringComparison.InvariantCultureIgnoreCase))
{
destinationSubPath = entryToCopy_absolutePath.Substring(sourceRoot.Length);
}
else
{
//not part of the source root
return false;
}
destinationSubPath = destinationSubPath.TrimStart(Path.DirectorySeparatorChar);
string newPath = Path.Combine(destinationRoot, destinationSubPath);
if (IsDirectory)
{
Directory.CreateDirectory(newPath);
OnCopied?.Invoke(entryToCopy_absolutePath, newPath);
if (CopyDirectoryContents)
{
bool result = true;
NavigateFileSystem(entryToCopy_absolutePath, _ => true, s =>
result &= CopyFromRootPath(s, sourceRoot, destinationRoot, CopyDirectoryContents: false, OnCopied: OnCopied)
//The "copydirectorycontents" flag must only apply to the first folder!
);
return result;
}
else
{
return true;
}
}
else
{
Directory.CreateDirectory(Directory.GetParent(newPath).FullName);
if (File.Exists(newPath))
{
if (ShouldOverride?.Invoke(newPath) ?? false)
File.Delete(newPath);
else
{
return false;
}
}
File.Copy(entryToCopy_absolutePath, newPath);
OnCopied?.Invoke(entryToCopy_absolutePath, newPath);
return true;
}
}
public static void NavigateFileSystem(string startFrom, Func<string, bool> shouldConsiderThisElement, Action<String> OnElementFound) =>
NavigateFileSystem(startFrom,
shouldExploreThisDirectory: s => true,
shouldConsiderThisDirectory: shouldConsiderThisElement,
OnDirectoryFound: OnElementFound,
shouldConsiderThisFile: shouldConsiderThisElement,
OnFileFound: OnElementFound);
public static void NavigateFileSystem(
string startFrom,
Func<string, bool> shouldExploreThisDirectory,
Func<string, bool> shouldConsiderThisDirectory,
Action<String> OnDirectoryFound,
Func<string, bool> shouldConsiderThisFile,
Action<String> OnFileFound)
{
IEnumerable<String> files;
try
{
files = Directory.EnumerateFiles(startFrom);
}
catch (UnauthorizedAccessException)
{
return;
}
foreach (string file in files)
{
if (shouldConsiderThisFile(file))
OnFileFound(file);
}
IEnumerable<String> dirs = Directory.EnumerateDirectories(startFrom);
foreach (string directory in dirs)
{
if (shouldConsiderThisDirectory(directory))
OnDirectoryFound(directory);
if (shouldExploreThisDirectory(directory))
NavigateFileSystem(directory, shouldExploreThisDirectory, shouldConsiderThisDirectory, OnDirectoryFound, shouldConsiderThisFile, OnFileFound);
}
}
public static void ForEach<EnumerableType>
(this IEnumerable<EnumerableType> list, Action<EnumerableType> action)
{
foreach (EnumerableType item in list)
{
action(item);
}
}
public static IEnumerable<ResultType> ForEach<EnumerableType, ResultType>(
this IEnumerable<EnumerableType> list,
Func<EnumerableType, ResultType> function)
{
List<ResultType> _result = new List<ResultType>();
list.ForEach(l => _result.Add(function(l)));
return _result;
}
}
}