| 1 | /************************************************************************************ |
| 2 | |
| 3 | Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. |
| 4 | |
| 5 | Licensed under the Oculus SDK License Version 3.4.1 (the "License"); |
| 6 | you may not use the Oculus SDK except in compliance with the License, |
| 7 | which is provided at the time of installation or download, or which |
| 8 | otherwise accompanies this software in either electronic or hard copy form. |
| 9 | |
| 10 | You may obtain a copy of the License at |
| 11 | |
| 12 | https://developer.oculus.com/licenses/sdk-3.4.1 |
| 13 | |
| 14 | Unless required by applicable law or agreed to in writing, the Oculus SDK |
| 15 | distributed under the License is distributed on an "AS IS" BASIS, |
| 16 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 17 | See the License for the specific language governing permissions and |
| 18 | limitations under the License. |
| 19 | |
| 20 | ************************************************************************************/ |
| 21 | using System.Collections.Generic; |
| 22 | using System.Diagnostics.CodeAnalysis; |
| 23 | using System.IO; |
| 24 | using System.Linq; |
| 25 | using System.Text.RegularExpressions; |
| 26 | using System; |
| 27 | |
| 28 | public class DirectorySyncer |
| 29 | { |
| 30 | public delegate void SyncResultDelegate(SyncResult syncResult); |
| 31 | |
| 32 | public readonly string Source; |
| 33 | public readonly string Target; |
| 34 | public SyncResultDelegate WillPerformOperations; |
| 35 | private readonly Regex _ignoreExpression; |
| 36 | |
| 37 | // helper classes to simplify transition beyond .NET runtime 3.5 |
| 38 | public abstract class CancellationToken |
| 39 | { |
| 40 | protected abstract bool _IsCancellationRequested(); |
| 41 | |
| 42 | public virtual bool IsCancellationRequested |
| 43 | { |
| 44 | get { return _IsCancellationRequested(); } |
| 45 | } |
| 46 | |
| 47 | public void ThrowIfCancellationRequested() |
| 48 | { |
| 49 | if (IsCancellationRequested) |
| 50 | { |
| 51 | throw new Exception("Operation Cancelled"); |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | public static readonly CancellationToken None = new CancellationTokenNone(); |
| 56 | |
| 57 | private class CancellationTokenNone : CancellationToken |
| 58 | { |
| 59 | protected override bool _IsCancellationRequested() |
| 60 | { |
| 61 | return false; |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | public class CancellationTokenSource : CancellationToken |
| 67 | { |
| 68 | private bool _isCancelled; |
| 69 | |
| 70 | protected override bool _IsCancellationRequested() |
| 71 | { |
| 72 | return _isCancelled; |
| 73 | } |
| 74 | |
| 75 | public void Cancel() |
| 76 | { |
| 77 | _isCancelled = true; |
| 78 | } |
| 79 | |
| 80 | public CancellationToken Token |
| 81 | { |
| 82 | get { return this; } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | private static string EnsureTrailingDirectorySeparator(string path) |
| 87 | { |
| 88 | return path.EndsWith("" + Path.DirectorySeparatorChar) |
| 89 | ? path |
| 90 | : path + Path.DirectorySeparatorChar; |
| 91 | } |
| 92 | |
| 93 | private static string CheckedDirectory(string nameInExceptionText, string directory) |
| 94 | { |
| 95 | directory = Path.GetFullPath(directory); |
| 96 | if (!Directory.Exists(directory)) |
| 97 | { |
| 98 | throw new ArgumentException(string.Format("{0} is not a valid directory for argument ${1}", directory, |
| 99 | nameInExceptionText)); |
| 100 | } |
| 101 | |
| 102 | return EnsureTrailingDirectorySeparator(directory); |
| 103 | } |
| 104 | |
| 105 | public DirectorySyncer(string source, string target, string ignoreRegExPattern = null) |
| 106 | { |
| 107 | Source = CheckedDirectory("source", source); |
| 108 | Target = CheckedDirectory("target", target); |
| 109 | if (Source.StartsWith(Target, StringComparison.OrdinalIgnoreCase) || |
| 110 | Target.StartsWith(Source, StringComparison.OrdinalIgnoreCase)) |
| 111 | { |
| 112 | throw new ArgumentException(string.Format("Paths must not contain each other (source: {0}, target: {1}", |
| 113 | Source, Target)); |
| 114 | } |
| 115 | |
| 116 | ignoreRegExPattern = ignoreRegExPattern ?? "^$"; |
| 117 | _ignoreExpression = new Regex(ignoreRegExPattern, RegexOptions.IgnoreCase); |
| 118 | } |
| 119 | |
| 120 | public class SyncResult |
| 121 | { |
| 122 | public readonly IEnumerable<string> Created; |
| 123 | public readonly IEnumerable<string> Updated; |
| 124 | public readonly IEnumerable<string> Deleted; |
| 125 | |
| 126 | public SyncResult(IEnumerable<string> created, IEnumerable<string> updated, IEnumerable<string> deleted) |
| 127 | { |
| 128 | Created = created; |
| 129 | Updated = updated; |
| 130 | Deleted = deleted; |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | public bool RelativeFilePathIsRelevant(string relativeFilename) |
| 135 | { |
| 136 | return !_ignoreExpression.IsMatch(relativeFilename); |
| 137 | } |
| 138 | |
| 139 | public bool RelativeDirectoryPathIsRelevant(string relativeDirName) |
| 140 | { |
| 141 | // Since our ignore patterns look at file names, they may contain trailing path separators |
| 142 | // In order for paths to match those rules, we add a path separator here |
| 143 | return !_ignoreExpression.IsMatch(EnsureTrailingDirectorySeparator(relativeDirName)); |
| 144 | } |
| 145 | |
| 146 | private HashSet<string> RelevantRelativeFilesBeneathDirectory(string path, CancellationToken cancellationToken) |
| 147 | { |
| 148 | return new HashSet<string>(Directory.GetFiles(path, "*", SearchOption.AllDirectories) |
| 149 | .TakeWhile((s) => !cancellationToken.IsCancellationRequested) |
| 150 | .Select(p => PathHelper.MakeRelativePath(path, p)).Where(RelativeFilePathIsRelevant)); |
| 151 | } |
| 152 | |
| 153 | private HashSet<string> RelevantRelativeDirectoriesBeneathDirectory(string path, |
| 154 | CancellationToken cancellationToken) |
| 155 | { |
| 156 | return new HashSet<string>(Directory.GetDirectories(path, "*", SearchOption.AllDirectories) |
| 157 | .TakeWhile((s) => !cancellationToken.IsCancellationRequested) |
| 158 | .Select(p => PathHelper.MakeRelativePath(path, p)).Where(RelativeDirectoryPathIsRelevant)); |
| 159 | } |
| 160 | |
| 161 | public SyncResult Synchronize() |
| 162 | { |
| 163 | return Synchronize(CancellationToken.None); |
| 164 | } |
| 165 | |
| 166 | private void DeleteOutdatedFilesFromTarget(SyncResult syncResult, CancellationToken cancellationToken) |
| 167 | { |
| 168 | var outdatedFiles = syncResult.Updated.Union(syncResult.Deleted); |
| 169 | foreach (var fileName in outdatedFiles) |
| 170 | { |
| 171 | File.Delete(Path.Combine(Target, fileName)); |
| 172 | cancellationToken.ThrowIfCancellationRequested(); |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | [SuppressMessage("ReSharper", "ParameterTypeCanBeEnumerable.Local")] |
| 177 | private void DeleteOutdatedEmptyDirectoriesFromTarget(HashSet<string> sourceDirs, HashSet<string> targetDirs, |
| 178 | CancellationToken cancellationToken) |
| 179 | { |
| 180 | var deleted = targetDirs.Except(sourceDirs).OrderByDescending(s => s); |
| 181 | |
| 182 | // By sorting in descending order above, we delete leaf-first, |
| 183 | // this is simpler than collapsing the list above (which would also allow us to run these ops in parallel). |
| 184 | // Assumption is that there are few empty folders to delete |
| 185 | foreach (var dir in deleted) |
| 186 | { |
| 187 | Directory.Delete(Path.Combine(Target, dir)); |
| 188 | cancellationToken.ThrowIfCancellationRequested(); |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | [SuppressMessage("ReSharper", "ParameterTypeCanBeEnumerable.Local")] |
| 193 | private void CreateRelevantDirectoriesAtTarget(HashSet<string> sourceDirs, HashSet<string> targetDirs, |
| 194 | CancellationToken cancellationToken) |
| 195 | { |
| 196 | var created = sourceDirs.Except(targetDirs); |
| 197 | foreach (var dir in created) |
| 198 | { |
| 199 | Directory.CreateDirectory(Path.Combine(Target, dir)); |
| 200 | cancellationToken.ThrowIfCancellationRequested(); |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | private void MoveRelevantFilesToTarget(SyncResult syncResult, CancellationToken cancellationToken) |
| 205 | { |
| 206 | // step 3: we move all new files to target |
| 207 | var newFiles = syncResult.Created.Union(syncResult.Updated); |
| 208 | foreach (var fileName in newFiles) |
| 209 | { |
| 210 | var sourceFileName = Path.Combine(Source, fileName); |
| 211 | var destFileName = Path.Combine(Target, fileName); |
| 212 | // target directory exists due to step CreateRelevantDirectoriesAtTarget() |
| 213 | File.Move(sourceFileName, destFileName); |
| 214 | cancellationToken.ThrowIfCancellationRequested(); |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | public SyncResult Synchronize(CancellationToken cancellationToken) |
| 219 | { |
| 220 | var sourceDirs = RelevantRelativeDirectoriesBeneathDirectory(Source, cancellationToken); |
| 221 | var targetDirs = RelevantRelativeDirectoriesBeneathDirectory(Target, cancellationToken); |
| 222 | var sourceFiles = RelevantRelativeFilesBeneathDirectory(Source, cancellationToken); |
| 223 | var targetFiles = RelevantRelativeFilesBeneathDirectory(Target, cancellationToken); |
| 224 | |
| 225 | var created = sourceFiles.Except(targetFiles).OrderBy(s => s).ToList(); |
| 226 | var updated = sourceFiles.Intersect(targetFiles).OrderBy(s => s).ToList(); |
| 227 | var deleted = targetFiles.Except(sourceFiles).OrderBy(s => s).ToList(); |
| 228 | var syncResult = new SyncResult(created, updated, deleted); |
| 229 | |
| 230 | if (WillPerformOperations != null) |
| 231 | { |
| 232 | WillPerformOperations.Invoke(syncResult); |
| 233 | } |
| 234 | |
| 235 | DeleteOutdatedFilesFromTarget(syncResult, cancellationToken); |
| 236 | DeleteOutdatedEmptyDirectoriesFromTarget(sourceDirs, targetDirs, cancellationToken); |
| 237 | CreateRelevantDirectoriesAtTarget(sourceDirs, targetDirs, cancellationToken); |
| 238 | MoveRelevantFilesToTarget(syncResult, cancellationToken); |
| 239 | |
| 240 | return syncResult; |
| 241 | } |
| 242 | } |