private static void Sync(ISyncClientFactory syncClientFactory, FileUploadWorker fileUploadWorker, string source, string target) { using (var syncClient = syncClientFactory.Create(target)) { foreach (var i in Directory.EnumerateFiles(source, "*", SearchOption.AllDirectories)) { if (fileUploadWorker.ValidateFile(i)) { var targetFile = fileUploadWorker.ResolveTargetFile(i); for (;;) { try { var dirty = false; var sourceFileInfo = new FileInfo(i); var targetFileInfo = syncClient.GetFileInfo(targetFile); if (!targetFileInfo.Exists) { Log("Sync file:{0} not exists", targetFile); dirty = true; } else { if (targetFileInfo?.Size != null && sourceFileInfo.Length != targetFileInfo.Size.Value) { Log("Sync file:{0} size:{1} {2}", targetFile, sourceFileInfo.Length, targetFileInfo.Size.Value); dirty = true; } if (targetFileInfo?.Timestamp != null && sourceFileInfo.LastWriteTime > targetFileInfo.Timestamp.Value) { Log("Sync file:{0} timestamp:{1} {2}", targetFile, sourceFileInfo.LastWriteTime.ToDateTimeString(), targetFileInfo.Timestamp.Value.ToDateTimeString()); dirty = true; } } if (dirty) { fileUploadWorker.Add(i, false); } break; } catch (Exception ex) { LogError("Sync file:{0} exception:{1}", targetFile, ex); syncClient.Close(); Thread.Sleep(1000); } } } } } }
public static void Main(string[] args) { var argIndex = 0; var source = args[argIndex++]; var targetType = args[argIndex++]; var target = args[argIndex++]; Log("Source: {0}", source); Log("Target: {0} {1}", targetType, target); Log("Starting"); var syncClientFactory = GetSyncClientFactory(targetType); var syncClient = syncClientFactory.Create(target); syncClient.Test(); var syncIgnoreFile = Path.Combine(source, ".syncignore"); Func <string, bool> validateFile; if (File.Exists(syncIgnoreFile)) { var ignoreFiles = File.ReadAllLines(syncIgnoreFile) .Where(i => !string.IsNullOrWhiteSpace(i)) .Select(i => i.Trim()) .ToArray(); validateFile = file => file != ".syncignore" && !ignoreFiles.Any(i => file.StartsWith(i)); } else { validateFile = file => true; } var fileUploadWorker = new FileUploadWorker(syncClient, source, validateFile, Log, LogError); var syncTask = SyncAsync(syncClientFactory, fileUploadWorker, source, target); fileUploadWorker.Idle += () => { if (syncTask.IsCompleted) { Log("Idle", new object[0]); } else { Log("Still syncing", new object[0]); } }; using (var fsw = (IFileSystemWatcher)FswatchFileSystemWatcher.Create(source) ?? new DotnetFileSystemWatcher(source)) { Log("Watch started using {0}", new[] { fsw.GetType() }); for (;;) { var file = fsw.WaitForChanged(); if ((File.Exists(file) || Directory.Exists(file)) && fileUploadWorker.ValidateFile(file)) { Log("Changed file:{0}", fileUploadWorker.ResolveTargetFile(file)); fileUploadWorker.Add(file, true); } } } }