diff --git a/GVFS/GVFS.Common/Sparse/ConeBuilder.cs b/GVFS/GVFS.Common/Sparse/ConeBuilder.cs new file mode 100644 index 000000000..7d5e1b1c2 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/ConeBuilder.cs @@ -0,0 +1,211 @@ +using System; +using System.Collections.Generic; + +namespace GVFS.Common.Sparse +{ + /// + /// Maps a set of modified paths to a git cone-mode sparse-checkout pattern set. + /// + /// + /// A modified file contributes parent-only patterns for its parent directory and + /// every ancestor directory, so a single edited file never pulls its whole subtree + /// into the index. A modified folder contributes one recursive pattern for the whole + /// subtree, which matches the existing recursive meaning of a folder entry in the + /// modified-paths list. + /// + /// GVFS builds the patterns itself and does not call git sparse-checkout set. + /// In cone mode, set passes each input directory through + /// strbuf_to_cone_pattern to insert_recursive_pattern + /// (builtin/sparse-checkout.c), so every input becomes a recursive pattern. To + /// include one modified file, set would have to include its whole parent + /// directory recursively, with every file below it. + /// + /// + /// This type performs no I/O. The output is sorted ordinally, as git's + /// write_cone_to_file sorts with strcmp. Directory de-duplication uses + /// , so it must use the same case rule as the repository's + /// core.ignoreCase. If git reads two directories that differ only in case while + /// core.ignoreCase is true, it reports a repeated pattern and turns off cone + /// matching, and the sparse index cannot stay sparse. + /// + /// + public static class ConeBuilder + { + /// + /// Build a cone pattern set from modified-path entries. + /// + /// + /// Modified-path entries. A file entry has no trailing slash; a folder entry ends + /// in a slash. Entries can use either path separator and can have a leading slash + /// or duplicate separators; the builder normalizes them. Null entries are skipped. + /// The repo root itself contributes no directory pattern. + /// + /// + /// The repository's core.ignoreCase value. When true, directories that differ + /// only in ASCII case are one directory, and the output keeps the ordinally smallest + /// spelling, whatever the input order. + /// + /// + /// A modified path has a directory that a cone-mode file cannot contain (see + /// ). The builder fails instead of writing + /// a cone that leaves the path out. + /// + public static ConePatternSet BuildFromModifiedPaths(IEnumerable modifiedPaths, bool ignoreCase) + { + ArgumentNullException.ThrowIfNull(modifiedPaths); + + GitPathComparer comparer = GitPathComparer.GetComparer(ignoreCase); + + List<(string Path, bool IsFolder)> entries = new List<(string Path, bool IsFolder)>(); + foreach (string rawPath in modifiedPaths) + { + if (rawPath == null) + { + continue; + } + + string cleanPath = ConePath.Normalize(rawPath, out bool isFolder); + if (cleanPath.Length == 0) + { + // An empty path is the repo root or a bare separator. Root files are + // already included by the "/*" header, so there is nothing to add. + continue; + } + + entries.Add((cleanPath, isFolder)); + } + + // Process the entries in ordinal order, and give every directory the first spelling + // seen for it. When case is ignored, each directory then keeps its ordinally smallest + // spelling in both lists, and the output does not depend on the input order. + entries.Sort((left, right) => string.CompareOrdinal(left.Path, right.Path)); + + Dictionary spellings = new Dictionary(comparer); + HashSet recursiveDirectories = new HashSet(comparer); + HashSet parentOnlyDirectories = new HashSet(comparer); + + foreach ((string Path, bool IsFolder) entry in entries) + { + string cleanPath = entry.Path; + if (entry.IsFolder) + { + ThrowIfInvalidDirectory(cleanPath); + recursiveDirectories.Add(Spell(cleanPath, spellings)); + AddAncestors(cleanPath, parentOnlyDirectories, spellings); + } + else + { + string parent = ConePath.GetParent(cleanPath); + if (parent.Length != 0) + { + ThrowIfInvalidDirectory(parent); + parentOnlyDirectories.Add(Spell(parent, spellings)); + AddAncestors(parent, parentOnlyDirectories, spellings); + } + } + } + + // A recursive directory nested inside another recursive directory is redundant; + // the ancestor already covers the whole subtree. + RemoveRedundantRecursiveDirectories(recursiveDirectories, comparer); + + // A parent-only directory that a recursive directory already covers is redundant: + // either it equals a recursive directory, or it is below one. Parent-only + // ancestors of a recursive directory are kept, because a recursive directory + // does not include the direct files of its ancestors. + RemoveParentOnlyDirectoriesCoveredByRecursive(parentOnlyDirectories, recursiveDirectories, comparer); + + List sortedParents = new List(parentOnlyDirectories); + sortedParents.Sort(StringComparer.Ordinal); + + List sortedRecursive = new List(recursiveDirectories); + sortedRecursive.Sort(StringComparer.Ordinal); + + return new ConePatternSet(sortedParents, sortedRecursive, ignoreCase); + } + + private static void ThrowIfInvalidDirectory(string directory) + { + // Check every input directory before the cleanup below can remove it. Otherwise + // "A/D/../C" would vanish as a descendant of "A/D", and "A/C" would stay outside the + // cone. The ancestors of a valid directory are also valid. + if (!ConePatternSet.IsValidDirectory(directory)) + { + throw new ArgumentException($"'{directory}' is not a directory that a cone-mode sparse-checkout file can contain."); + } + } + + private static string Spell(string directory, Dictionary spellings) + { + if (!spellings.TryGetValue(directory, out string spelling)) + { + spelling = directory; + spellings.Add(directory, spelling); + } + + return spelling; + } + + private static void AddAncestors(string directory, HashSet parentOnlyDirectories, Dictionary spellings) + { + // Add every proper ancestor of the directory, but not the directory itself. + int separator = directory.IndexOf(GVFSConstants.GitPathSeparator); + while (separator >= 0) + { + parentOnlyDirectories.Add(Spell(directory.Substring(0, separator), spellings)); + separator = directory.IndexOf(GVFSConstants.GitPathSeparator, separator + 1); + } + } + + private static void RemoveRedundantRecursiveDirectories(HashSet recursiveDirectories, GitPathComparer comparer) + { + List toRemove = new List(); + foreach (string candidate in recursiveDirectories) + { + foreach (string other in recursiveDirectories) + { + if (comparer.IsDescendantOf(candidate, other)) + { + toRemove.Add(candidate); + break; + } + } + } + + foreach (string redundant in toRemove) + { + recursiveDirectories.Remove(redundant); + } + } + + private static void RemoveParentOnlyDirectoriesCoveredByRecursive( + HashSet parentOnlyDirectories, + HashSet recursiveDirectories, + GitPathComparer comparer) + { + List toRemove = new List(); + foreach (string parent in parentOnlyDirectories) + { + if (recursiveDirectories.Contains(parent)) + { + toRemove.Add(parent); + continue; + } + + foreach (string recursive in recursiveDirectories) + { + if (comparer.IsDescendantOf(parent, recursive)) + { + toRemove.Add(parent); + break; + } + } + } + + foreach (string covered in toRemove) + { + parentOnlyDirectories.Remove(covered); + } + } + } +} diff --git a/GVFS/GVFS.Common/Sparse/ConeFileWriteResult.cs b/GVFS/GVFS.Common/Sparse/ConeFileWriteResult.cs new file mode 100644 index 000000000..d43f15bb2 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/ConeFileWriteResult.cs @@ -0,0 +1,17 @@ +namespace GVFS.Common.Sparse +{ + /// + /// The result of . + /// + public enum ConeFileWriteResult + { + /// The file already had the serialized content. Nothing was written. + Unchanged, + + /// The file now has the new serialized content. + Written, + + /// The write failed. The file keeps its previous content. + Failed, + } +} diff --git a/GVFS/GVFS.Common/Sparse/ConeFileWriter.cs b/GVFS/GVFS.Common/Sparse/ConeFileWriter.cs new file mode 100644 index 000000000..7b6fe33c4 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/ConeFileWriter.cs @@ -0,0 +1,333 @@ +using System; +using System.ComponentModel; +using System.IO; +using System.Text; +using System.Threading; +using GVFS.Common.FileSystem; + +namespace GVFS.Common.Sparse +{ + /// + /// Serializes a to git's cone-mode + /// info/sparse-checkout format and writes it atomically. + /// + /// + /// The serialization mirrors git's write_cone_to_file + /// (builtin/sparse-checkout.c): a root include line, a root directory exclude line, + /// a positive and negative pair for each parent-only directory, and a single positive + /// line for each recursive directory. Glob-special characters are escaped as git's + /// escaped_pattern does. The file is UTF-8 without a byte order mark, and lines end + /// with \n, as in git's own writer. + /// + /// The writer does not lock the file. The caller must make sure that no other writer, + /// including a git command, changes the file between , the use of the + /// new cone, and a possible . + /// + /// + /// A git process that reads the file keeps it open without delete sharing, so the rename + /// over the file can fail with ERROR_ACCESS_DENIED or + /// ERROR_SHARING_VIOLATION for a short time. The writer then tries the replace + /// again with a short backoff, as git's mingw_rename does. The caller sets the + /// retry budget. + /// + /// + public class ConeFileWriter + { + /// + /// Suffix for the backup of the previous sparse-checkout file, which a caller can use + /// to roll back when it cannot apply the new cone. + /// + public const string BackupExtension = ".gvfsbackup"; + + /// + /// The total time that the writer waits between attempts to replace the file when the + /// caller does not give a retry budget. + /// + public static readonly TimeSpan DefaultReplaceRetryBudget = TimeSpan.FromMilliseconds(100); + + private const string LineEnding = "\n"; + private const string ConeHeader = "/*" + LineEnding + "!/*/" + LineEnding; + + private const int ErrorAccessDenied = 5; + private const int ErrorSharingViolation = 32; + private const uint Win32HResultFacilityMask = 0xFFFF0000; + private const uint Win32HResultFacility = 0x80070000; + + // The same delays as git's retry_ask_yes_no in compat/mingw.c. After the last delay, + // the writer keeps the last delay until the budget is spent. + private static readonly int[] ReplaceRetryDelaysMilliseconds = { 0, 1, 10, 20, 40 }; + + // PhysicalFileSystem.TryWriteTempFileAndRename writes through a StreamWriter, which + // uses UTF-8 without a byte order mark. + private static readonly UTF8Encoding FileEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + + private readonly PhysicalFileSystem fileSystem; + private readonly Action sleep; + + public ConeFileWriter(PhysicalFileSystem fileSystem) + : this(fileSystem, Thread.Sleep) + { + } + + internal ConeFileWriter(PhysicalFileSystem fileSystem, Action sleep) + { + ArgumentNullException.ThrowIfNull(fileSystem); + ArgumentNullException.ThrowIfNull(sleep); + this.fileSystem = fileSystem; + this.sleep = sleep; + } + + private delegate bool ReplaceOperation(out Exception handledException); + + /// + /// Serialize a cone pattern set to git's cone-mode sparse-checkout file content. + /// + public static string Serialize(ConePatternSet cone) + { + ArgumentNullException.ThrowIfNull(cone); + + StringBuilder builder = new StringBuilder(); + builder.Append(ConeHeader); + + foreach (string parentOnlyDirectory in cone.ParentOnlyDirectories) + { + string escaped = EscapePattern(parentOnlyDirectory); + builder.Append(GVFSConstants.GitPathSeparator).Append(escaped).Append(GVFSConstants.GitPathSeparator).Append(LineEnding); + builder.Append('!').Append(GVFSConstants.GitPathSeparator).Append(escaped).Append("/*/").Append(LineEnding); + } + + foreach (string recursiveDirectory in cone.RecursiveDirectories) + { + string escaped = EscapePattern(recursiveDirectory); + builder.Append(GVFSConstants.GitPathSeparator).Append(escaped).Append(GVFSConstants.GitPathSeparator).Append(LineEnding); + } + + return builder.ToString(); + } + + /// + /// Escape glob-special characters (*, ?, [, \) with a + /// leading backslash, as git's escaped_pattern does. + /// + internal static string EscapePattern(string pattern) + { + ArgumentNullException.ThrowIfNull(pattern); + + StringBuilder escaped = new StringBuilder(pattern.Length); + foreach (char character in pattern) + { + if (IsGlobSpecial(character)) + { + escaped.Append('\\'); + } + + escaped.Append(character); + } + + return escaped.ToString(); + } + + /// + /// Write the cone file atomically: write a temporary file, then rename it over the + /// target. + /// + /// The full path of the sparse-checkout file. + /// The cone to write. + /// + /// When the method replaced an existing file, the path of a backup of its previous + /// content. Otherwise null. If the method fails after it writes the backup, the backup + /// path is still set. Restore only the backup path that this call returns. Each write + /// replaces the backup of the previous write, and the method does not delete an old + /// backup. The caller deletes the backup when it no longer needs it. + /// + /// The exception that made the write fail, or null. + /// + /// The total time to wait between attempts when the rename over the target fails with + /// access denied or a sharing violation. Zero makes one attempt only. Null uses + /// . The budget does not include the time of + /// the attempts. + /// + /// + /// when the file already has exactly the + /// serialized bytes. The method then writes nothing, not even a backup. + /// when the method wrote the new content. + /// when the read, the backup, or the write + /// failed. A failed write leaves the target file with its previous content. + /// + public ConeFileWriteResult Write( + string sparseCheckoutPath, + ConePatternSet cone, + out string backupPath, + out Exception handledException, + TimeSpan? replaceRetryBudget = null) + { + ArgumentNullException.ThrowIfNull(sparseCheckoutPath); + ArgumentNullException.ThrowIfNull(cone); + TimeSpan retryBudget = GetRetryBudget(replaceRetryBudget); + + backupPath = null; + handledException = null; + + string content = Serialize(cone); + + try + { + // Read the file instead of asking whether it exists. File.Exists also returns + // false when access is denied, and the write must not then replace the file + // without a backup. + byte[] existingBytes = this.ReadExistingFileOrNull(sparseCheckoutPath); + if (existingBytes != null) + { + // Compare bytes, not decoded text: git reads bytes, so the same text in + // another encoding is a different file to git. + if (existingBytes.AsSpan().SequenceEqual(FileEncoding.GetBytes(content))) + { + return ConeFileWriteResult.Unchanged; + } + + string candidateBackupPath = sparseCheckoutPath + BackupExtension; + if (!this.fileSystem.TryCopyToTempFileAndRename(sparseCheckoutPath, candidateBackupPath, out handledException)) + { + return ConeFileWriteResult.Failed; + } + + backupPath = candidateBackupPath; + } + + if (!this.TryReplaceWithRetry( + (out Exception e) => this.fileSystem.TryWriteTempFileAndRename(sparseCheckoutPath, content, out e), + retryBudget, + out handledException)) + { + return ConeFileWriteResult.Failed; + } + } + catch (IOException e) + { + handledException = e; + return ConeFileWriteResult.Failed; + } + catch (UnauthorizedAccessException e) + { + handledException = e; + return ConeFileWriteResult.Failed; + } + + return ConeFileWriteResult.Written; + } + + /// + /// Restore the sparse-checkout file from a backup written by . The + /// method copies the backup bytes exactly. The rename over the target uses the same + /// retry as . + /// + public bool TryRestoreBackup( + string sparseCheckoutPath, + string backupPath, + out Exception handledException, + TimeSpan? replaceRetryBudget = null) + { + ArgumentNullException.ThrowIfNull(sparseCheckoutPath); + ArgumentNullException.ThrowIfNull(backupPath); + TimeSpan retryBudget = GetRetryBudget(replaceRetryBudget); + + return this.TryReplaceWithRetry( + (out Exception e) => this.fileSystem.TryCopyToTempFileAndRename(backupPath, sparseCheckoutPath, out e), + retryBudget, + out handledException); + } + + /// + /// Return true for the failures that a short wait can fix: access denied and sharing + /// violation. .NET reports these as a from + /// MoveFileEx, as an , or as an + /// with the Win32 HRESULT. + /// + internal static bool IsTransientReplaceFailure(Exception exception) + { + switch (exception) + { + case Win32Exception win32Exception: + return IsTransientWin32Error(win32Exception.NativeErrorCode); + case UnauthorizedAccessException: + return true; + case IOException ioException: + uint hresult = unchecked((uint)ioException.HResult); + return (hresult & Win32HResultFacilityMask) == Win32HResultFacility + && IsTransientWin32Error((int)(hresult & 0xFFFF)); + default: + return false; + } + } + + private static bool IsTransientWin32Error(int error) + { + return error == ErrorAccessDenied || error == ErrorSharingViolation; + } + + private static TimeSpan GetRetryBudget(TimeSpan? replaceRetryBudget) + { + TimeSpan budget = replaceRetryBudget ?? DefaultReplaceRetryBudget; + if (budget < TimeSpan.Zero) + { + throw new ArgumentOutOfRangeException(nameof(replaceRetryBudget), budget, "The retry budget must not be negative."); + } + + return budget; + } + + private bool TryReplaceWithRetry(ReplaceOperation replace, TimeSpan retryBudget, out Exception handledException) + { + TimeSpan waited = TimeSpan.Zero; + for (int attempt = 0; ; attempt++) + { + if (replace(out handledException)) + { + return true; + } + + if (retryBudget == TimeSpan.Zero || !IsTransientReplaceFailure(handledException)) + { + return false; + } + + int delayIndex = Math.Min(attempt, ReplaceRetryDelaysMilliseconds.Length - 1); + TimeSpan delay = TimeSpan.FromMilliseconds(ReplaceRetryDelaysMilliseconds[delayIndex]); + + // waited never exceeds retryBudget, so the subtraction cannot overflow. + if (delay > retryBudget - waited) + { + return false; + } + + this.sleep(delay); + waited += delay; + } + } + + private static bool IsGlobSpecial(char character) + { + return character == '*' || character == '?' || character == '[' || character == '\\'; + } + + /// + /// Return the file's bytes, or null when the file or its directory does not exist. + /// Any other failure throws. + /// + private byte[] ReadExistingFileOrNull(string path) + { + try + { + return this.fileSystem.ReadAllBytes(path); + } + catch (FileNotFoundException) + { + return null; + } + catch (DirectoryNotFoundException) + { + return null; + } + } + } +} diff --git a/GVFS/GVFS.Common/Sparse/ConePath.cs b/GVFS/GVFS.Common/Sparse/ConePath.cs new file mode 100644 index 000000000..1876a104e --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/ConePath.cs @@ -0,0 +1,34 @@ +using System; + +namespace GVFS.Common.Sparse +{ + /// + /// Path normalization shared by and . + /// + internal static class ConePath + { + /// + /// Convert a repo-relative path to git form: forward slashes, no leading or trailing + /// separator, and no duplicate separators. A trailing separator on the input marks a + /// directory. An empty result is the repository root. + /// + public static string Normalize(string rawPath, out bool isDirectory) + { + string forwardSlashed = rawPath.Replace('\\', GVFSConstants.GitPathSeparator); + isDirectory = forwardSlashed.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal); + + string[] parts = forwardSlashed.Split(GVFSConstants.GitPathSeparator, StringSplitOptions.RemoveEmptyEntries); + return string.Join(GVFSConstants.GitPathSeparatorString, parts); + } + + /// + /// Return the parent directory of a git-form path, or an empty string for a path at + /// the repository root. + /// + public static string GetParent(string path) + { + int lastSeparator = path.LastIndexOf(GVFSConstants.GitPathSeparator); + return lastSeparator < 0 ? string.Empty : path.Substring(0, lastSeparator); + } + } +} diff --git a/GVFS/GVFS.Common/Sparse/ConePathMatcher.cs b/GVFS/GVFS.Common/Sparse/ConePathMatcher.cs new file mode 100644 index 000000000..d8fe79fed --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/ConePathMatcher.cs @@ -0,0 +1,109 @@ +using System; +using System.Collections.Generic; + +namespace GVFS.Common.Sparse +{ + /// + /// Decides whether a path is inside a cone, with the same rules that git uses for + /// cone-mode sparse-checkout patterns. + /// + /// + /// The rules follow path_matches_pattern_list in git's dir.c: + /// + /// A file at the repository root is always in the cone. + /// A file is in the cone when its parent directory is a parent-only directory. + /// A file is in the cone when the file path itself, or one of its ancestor + /// directories, is a recursive directory. + /// A directory is in the cone when a file directly inside it would be in the cone. + /// Thus a parent-only directory is in the cone, but its child directories are not, unless + /// the cone names them. + /// + /// Git compares cone paths with ASCII-only case folding when core.ignoreCase is + /// true (see ). The matcher uses the case rule of the + /// that it is built from. + /// + public sealed class ConePathMatcher + { + private const string DirectoryProbeName = "-"; + + private readonly HashSet parentOnlyDirectories; + private readonly HashSet recursiveDirectories; + + public ConePathMatcher(ConePatternSet cone) + { + ArgumentNullException.ThrowIfNull(cone); + + GitPathComparer comparer = GitPathComparer.GetComparer(cone.IgnoreCase); + this.parentOnlyDirectories = new HashSet(cone.ParentOnlyDirectories, comparer); + this.recursiveDirectories = new HashSet(cone.RecursiveDirectories, comparer); + } + + /// + /// Return true when git would treat the path as inside the cone. + /// + /// + /// A repo-relative path. A trailing separator marks a directory. Either path separator + /// is accepted, and a leading separator is ignored. An empty path is the repository + /// root, which is always in the cone. + /// + public bool IsInCone(string path) + { + ArgumentNullException.ThrowIfNull(path); + + string cleanPath = ConePath.Normalize(path, out bool isDirectory); + if (cleanPath.Length == 0) + { + return true; + } + + // Git checks a directory as if it were a file named "-" directly inside that + // directory, so the directory itself takes the place of the file's parent. + string parent; + if (isDirectory) + { + if (this.recursiveDirectories.Contains(cleanPath + GVFSConstants.GitPathSeparatorString + DirectoryProbeName)) + { + return true; + } + + parent = cleanPath; + } + else + { + if (this.recursiveDirectories.Contains(cleanPath)) + { + return true; + } + + parent = ConePath.GetParent(cleanPath); + if (parent.Length == 0) + { + return true; + } + } + + if (this.parentOnlyDirectories.Contains(parent)) + { + return true; + } + + return this.IsSelfOrAncestorRecursive(parent); + } + + private bool IsSelfOrAncestorRecursive(string directory) + { + string current = directory; + while (current.Length != 0) + { + if (this.recursiveDirectories.Contains(current)) + { + return true; + } + + current = ConePath.GetParent(current); + } + + return false; + } + } +} diff --git a/GVFS/GVFS.Common/Sparse/ConePatternSet.cs b/GVFS/GVFS.Common/Sparse/ConePatternSet.cs new file mode 100644 index 000000000..96e81de2e --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/ConePatternSet.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace GVFS.Common.Sparse +{ + /// + /// The computed cone-mode sparse-checkout pattern set for a worktree. It is the + /// output of and the input to + /// and . + /// + /// + /// Directory paths are stored in git form: forward slashes, no leading slash, and + /// no trailing slash (for example A or A/B). A parent-only directory + /// includes the files directly in that directory but not its subtree. A recursive + /// directory includes the whole subtree. + /// + /// The constructor rejects a directory that git cannot read back from a cone-mode file + /// as the same directory. If git finds such a pattern, it turns off cone matching, or it + /// reads extra patterns, and files that GVFS puts in the cone can be outside it. Thus + /// every set that the constructor accepts serializes to a file that git reads in cone + /// mode with the same meaning. + /// + /// + public class ConePatternSet + { + /// Directories whose direct files are in the cone. + /// Directories whose whole subtree is in the cone. + /// + /// The repository's core.ignoreCase value. When true, directories that differ + /// only in ASCII case are the same directory (see ). + /// + /// + /// A directory is not a valid cone directory (see ), or it + /// is in the lists more than once under the case rule. Git reports a repeated directory + /// and turns off cone matching. + /// + public ConePatternSet(IReadOnlyList parentOnlyDirectories, IReadOnlyList recursiveDirectories, bool ignoreCase) + { + ArgumentNullException.ThrowIfNull(parentOnlyDirectories); + ArgumentNullException.ThrowIfNull(recursiveDirectories); + + HashSet seen = new HashSet(GitPathComparer.GetComparer(ignoreCase)); + AddDistinct(parentOnlyDirectories, seen, nameof(parentOnlyDirectories)); + AddDistinct(recursiveDirectories, seen, nameof(recursiveDirectories)); + + // Copy the lists, so that a later change to the caller's lists cannot skip the checks. + this.ParentOnlyDirectories = Array.AsReadOnly(parentOnlyDirectories.ToArray()); + this.RecursiveDirectories = Array.AsReadOnly(recursiveDirectories.ToArray()); + this.IgnoreCase = ignoreCase; + } + + /// + /// Directories whose direct files are in the cone, without their subtrees. + /// Each emits a positive directory pattern and a negative child-directory pattern. + /// + public IReadOnlyList ParentOnlyDirectories { get; } + + /// + /// Directories whose entire subtree is in the cone. Each emits a single positive + /// directory pattern. + /// + public IReadOnlyList RecursiveDirectories { get; } + + /// + /// True when the directories follow git's core.ignoreCase=true rule. + /// + public bool IgnoreCase { get; } + + /// + /// Return true when git can read the directory back from a cone-mode file with the + /// same meaning that GVFS gives it. + /// + /// + /// The directory must be a non-empty git-form path. It must not contain a line break + /// or NUL, because git reads the file line by line. It must not contain a backslash, + /// because GVFS reads a backslash as a separator and git does not. It must not contain + /// an empty, ., or .. segment, which git does not allow in a tracked path. + /// No segment can be *: git's dup_and_filter_pattern removes the escape + /// and then a trailing /*, so /A/\*/ becomes /A. It must be valid + /// UTF-16, because the file is written as UTF-8. + /// + public static bool IsValidDirectory(string directory) + { + if (string.IsNullOrEmpty(directory)) + { + return false; + } + + foreach (string segment in directory.Split(GVFSConstants.GitPathSeparator)) + { + if (segment.Length == 0 || segment == "." || segment == ".." || segment == "*") + { + return false; + } + } + + for (int i = 0; i < directory.Length; i++) + { + char character = directory[i]; + if (character == '\n' || character == '\r' || character == '\0' || character == '\\') + { + return false; + } + + if (char.IsHighSurrogate(character) && i + 1 < directory.Length && char.IsLowSurrogate(directory[i + 1])) + { + i++; + } + else if (char.IsSurrogate(character)) + { + return false; + } + } + + return true; + } + + private static void AddDistinct(IReadOnlyList directories, HashSet seen, string parameterName) + { + foreach (string directory in directories) + { + if (!IsValidDirectory(directory)) + { + throw new ArgumentException($"'{directory}' is not a directory that a cone-mode sparse-checkout file can contain.", parameterName); + } + + if (!seen.Add(directory)) + { + throw new ArgumentException($"'{directory}' is in the cone more than once.", parameterName); + } + } + } + } +} diff --git a/GVFS/GVFS.Common/Sparse/GitPathComparer.cs b/GVFS/GVFS.Common/Sparse/GitPathComparer.cs new file mode 100644 index 000000000..45e7f4780 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/GitPathComparer.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; + +namespace GVFS.Common.Sparse +{ + /// + /// Compares git paths the way git compares sparse-checkout cone patterns. + /// + /// + /// Git keys its cone pattern hashmaps with fspathhash and fspathncmp + /// (dir.c). When core.ignoreCase is false they compare bytes exactly. When it + /// is true they fold ASCII letters only, through strihash and strncasecmp, + /// so A matches a but Ä does not match ä. + /// also folds non-ASCII letters, so it + /// does not agree with git and must not be used for cone paths. + /// + internal sealed class GitPathComparer : IEqualityComparer + { + private GitPathComparer(bool ignoreCase) + { + this.IgnoreCase = ignoreCase; + } + + /// Exact comparison, as git does when core.ignoreCase is false. + public static GitPathComparer Ordinal { get; } = new GitPathComparer(ignoreCase: false); + + /// ASCII-only case folding, as git does when core.ignoreCase is true. + public static GitPathComparer IgnoreAsciiCase { get; } = new GitPathComparer(ignoreCase: true); + + public bool IgnoreCase { get; } + + public static GitPathComparer GetComparer(bool ignoreCase) + { + return ignoreCase ? IgnoreAsciiCase : Ordinal; + } + + public bool Equals(string x, string y) + { + if (ReferenceEquals(x, y)) + { + return true; + } + + if (x == null || y == null || x.Length != y.Length) + { + return false; + } + + return this.RegionEquals(x, y, y.Length); + } + + public int GetHashCode(string path) + { + ArgumentNullException.ThrowIfNull(path); + + if (!this.IgnoreCase) + { + return StringComparer.Ordinal.GetHashCode(path); + } + + HashCode hash = default; + foreach (char character in path) + { + hash.Add(FoldAscii(character)); + } + + return hash.ToHashCode(); + } + + /// + /// Return true when is strictly below the directory + /// . Both paths are in git form, without leading or + /// trailing separators. + /// + public bool IsDescendantOf(string path, string potentialAncestor) + { + return path.Length > potentialAncestor.Length + && path[potentialAncestor.Length] == GVFSConstants.GitPathSeparator + && this.RegionEquals(path, potentialAncestor, potentialAncestor.Length); + } + + private static char FoldAscii(char character) + { + return character >= 'A' && character <= 'Z' ? (char)(character + ('a' - 'A')) : character; + } + + private bool RegionEquals(string left, string right, int length) + { + if (!this.IgnoreCase) + { + return string.CompareOrdinal(left, 0, right, 0, length) == 0; + } + + for (int i = 0; i < length; i++) + { + if (FoldAscii(left[i]) != FoldAscii(right[i])) + { + return false; + } + } + + return true; + } + } +} diff --git a/GVFS/GVFS.Common/Sparse/SparseCheckoutPathResolver.cs b/GVFS/GVFS.Common/Sparse/SparseCheckoutPathResolver.cs new file mode 100644 index 000000000..45e54c741 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/SparseCheckoutPathResolver.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; + +namespace GVFS.Common.Sparse +{ + /// + /// Resolves the per-worktree info/sparse-checkout file path for a GVFS + /// enlistment. The cone file is worktree-scoped, so a linked worktree must write + /// its own file, not the shared one. + /// + /// + /// A linked worktree's sparse-checkout file is in its per-worktree git dir + /// (.git/worktrees/<name>/info/sparse-checkout), not in the shared git dir. + /// For a linked worktree, is the shared git dir, + /// so it must not be used to find the cone file. The primary enlistment uses + /// .git/info/sparse-checkout. Git finds the same per-worktree location through + /// git_pathdup, which sends info/sparse-checkout to the worktree git dir. + /// + public static class SparseCheckoutPathResolver + { + /// + /// Resolve the sparse-checkout file path for an enlistment. Use the per-worktree git + /// dir for a linked worktree, and the shared git dir otherwise. + /// + public static string GetSparseCheckoutFilePath(GVFSEnlistment enlistment) + { + ArgumentNullException.ThrowIfNull(enlistment); + + return GetSparseCheckoutFilePath( + enlistment.IsWorktree, + enlistment.DotGitRoot, + enlistment.IsWorktree ? enlistment.Worktree.WorktreeGitDir : null); + } + + /// + /// Resolve the sparse-checkout file path from primitive inputs. When + /// is true, the file is under + /// . Otherwise it is under + /// (the shared .git directory). + /// + public static string GetSparseCheckoutFilePath(bool isWorktree, string dotGitRoot, string worktreeGitDir) + { + string gitDir = isWorktree ? worktreeGitDir : dotGitRoot; + if (string.IsNullOrEmpty(gitDir)) + { + throw new ArgumentException( + isWorktree + ? "worktreeGitDir must be provided for a worktree enlistment." + : "dotGitRoot must be provided for a primary enlistment."); + } + + return Path.Combine(gitDir, GVFSConstants.DotGit.Info.Name, GVFSConstants.DotGit.Info.SparseCheckoutName); + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/LocalComponents/ConePathMatcherGitTests.cs b/GVFS/GVFS.FunctionalTests/Tests/LocalComponents/ConePathMatcherGitTests.cs new file mode 100644 index 000000000..941d889bd --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/LocalComponents/ConePathMatcherGitTests.cs @@ -0,0 +1,236 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using GVFS.Common.Sparse; +using GVFS.FunctionalTests.Properties; +using GVFS.Tests.Should; +using NUnit.Framework; + +namespace GVFS.FunctionalTests.Tests.LocalComponents +{ + /// + /// Compares with git's own cone matching. The test writes a + /// cone from to a temporary repository and asks + /// git sparse-checkout check-rules about the same paths. No enlistment is needed. + /// + [TestFixture] + public class ConePathMatcherGitTests + { + private const int GitTimeoutMilliseconds = 60000; + + // Modified paths for the comparison. They include directories that differ only in ASCII + // case, directories that differ only in non-ASCII case, glob-special characters, and a + // folder entry below a case variant. + private static readonly string[] ModifiedPaths = new[] + { + "root.txt", + "A/B/b.txt", + "A/D/", + "src/x.cs", + "Src/y.cs", + "SRC/Deep/z.cs", + "lower/UPPER/f.txt", + "Lower/upper/Sub/", + "\u00C4/x.txt", + "\u00E4/y.txt", + "glob*dir/f.txt", + "q?dir/sub/f.txt", + "br[1]/f.txt", + }; + + // Directories that the comparison queries, in addition to every directory from + // ModifiedPaths. + private static readonly string[] ExtraDirectories = new[] + { + "A", + "A/C", + "A/B/E", + "A/D/E/F", + "X", + "src/other", + "SRC/Deep/er", + "Lower/upper/Sub/x", + "lower/other", + "\u00C4/sub", + "globXdir", + "brX1]", + }; + + private string repoRoot; + + [SetUp] + public void SetUp() + { + this.repoRoot = Path.Combine(Path.GetTempPath(), "ConePathMatcherGitTests_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Path.Combine(this.repoRoot, "repo")); + this.RunGit(new[] { "init", "--quiet", "." }, input: null, out _, out _); + } + + [TearDown] + public void TearDown() + { + if (this.repoRoot != null && Directory.Exists(this.repoRoot)) + { + Directory.Delete(this.repoRoot, recursive: true); + } + + this.repoRoot = null; + } + + [TestCase(false)] + [TestCase(true)] + public void MatcherAgreesWithGitCheckRules(bool ignoreCase) + { + ConePatternSet cone = ConeBuilder.BuildFromModifiedPaths(ModifiedPaths, ignoreCase); + ConePathMatcher matcher = new ConePathMatcher(cone); + List queries = BuildQueries(); + + string sparseCheckoutPath = Path.Combine(this.repoRoot, "repo", ".git", "info", "sparse-checkout"); + Directory.CreateDirectory(Path.GetDirectoryName(sparseCheckoutPath)); + File.WriteAllText(sparseCheckoutPath, ConeFileWriter.Serialize(cone), new UTF8Encoding(false)); + + // check-rules reads the repository's own patterns here. With --rules-file and --cone + // it would read directory names instead of raw patterns. + string[] arguments = new[] + { + "-c", "core.ignoreCase=" + (ignoreCase ? "true" : "false"), + "-c", "core.sparseCheckout=true", + "-c", "core.sparseCheckoutCone=true", + "sparse-checkout", "check-rules", "-z", + }; + + string input = string.Join("\0", queries) + "\0"; + this.RunGit(arguments, input, out string output, out string errors); + + // A warning means that git found a pattern it does not accept in cone mode, for + // example a repeated directory, and turned off cone matching. + errors.ShouldEqual(string.Empty, "git reported: " + errors); + + HashSet gitInCone = new HashSet( + output.Split('\0', StringSplitOptions.RemoveEmptyEntries), + StringComparer.Ordinal); + + List disagreements = queries + .Where(query => matcher.IsInCone(query) != gitInCone.Contains(query)) + .Select(query => query + " (git: " + gitInCone.Contains(query) + ")") + .ToList(); + + disagreements.ShouldBeEmpty(string.Join(", ", disagreements)); + + // Every modified path must be in the cone, as git sees it. + List modifiedOutsideCone = ModifiedPaths.Where(path => !gitInCone.Contains(path)).ToList(); + modifiedOutsideCone.ShouldBeEmpty(string.Join(", ", modifiedOutsideCone)); + + // Make sure that the comparison covers both answers. + gitInCone.Count.ShouldBeAtLeast(1); + (queries.Count - gitInCone.Count).ShouldBeAtLeast(1); + } + + private static List BuildQueries() + { + HashSet directories = new HashSet(StringComparer.Ordinal); + foreach (string path in ModifiedPaths.Concat(ExtraDirectories)) + { + string current = path.TrimEnd('/'); + if (!ExtraDirectories.Contains(path) && !path.EndsWith("/", StringComparison.Ordinal)) + { + int lastSlash = current.LastIndexOf('/'); + current = lastSlash < 0 ? string.Empty : current.Substring(0, lastSlash); + } + + while (current.Length != 0) + { + directories.Add(current); + int lastSlash = current.LastIndexOf('/'); + current = lastSlash < 0 ? string.Empty : current.Substring(0, lastSlash); + } + } + + // Query the modified paths themselves, then each directory in its own case and in + // upper and lower case: as a file inside it, a file in a child of it, a directory, and + // a file with the directory's own name. + HashSet queries = new HashSet(ModifiedPaths, StringComparer.Ordinal) { "ROOT.TXT" }; + foreach (string directory in directories) + { + foreach (string spelling in new[] { directory, directory.ToUpperInvariant(), directory.ToLowerInvariant() }) + { + queries.Add(spelling + "/f.txt"); + queries.Add(spelling + "/child/f.txt"); + queries.Add(spelling + "/"); + queries.Add(spelling); + } + } + + List sorted = queries.ToList(); + sorted.Sort(StringComparer.Ordinal); + return sorted; + } + + private void RunGit(string[] arguments, string input, out string output, out string errors) + { + ProcessStartInfo startInfo = new ProcessStartInfo(Settings.Default.PathToGit) + { + WorkingDirectory = Path.Combine(this.repoRoot, "repo"), + UseShellExecute = false, + RedirectStandardInput = true, + RedirectStandardOutput = true, + RedirectStandardError = true, + StandardInputEncoding = new UTF8Encoding(false), + StandardOutputEncoding = new UTF8Encoding(false), + StandardErrorEncoding = new UTF8Encoding(false), + }; + + foreach (string argument in arguments) + { + startInfo.ArgumentList.Add(argument); + } + + // Configure only the child process, so that the functional runner's environment does + // not change. Remove inherited repository and configuration overrides, and point + // user and system configuration away from the machine's files. + foreach (string key in startInfo.Environment.Keys.Where(key => + key.StartsWith("GIT_CONFIG", StringComparison.OrdinalIgnoreCase)).ToArray()) + { + startInfo.Environment.Remove(key); + } + + startInfo.Environment.Remove("GIT_DIR"); + startInfo.Environment.Remove("GIT_COMMON_DIR"); + startInfo.Environment.Remove("GIT_WORK_TREE"); + startInfo.Environment.Remove("GIT_INDEX_FILE"); + startInfo.Environment.Remove("GIT_CEILING_DIRECTORIES"); + startInfo.Environment["HOME"] = this.repoRoot; + startInfo.Environment["XDG_CONFIG_HOME"] = Path.Combine(this.repoRoot, "xdg"); + startInfo.Environment["GIT_CONFIG_NOSYSTEM"] = "1"; + + using (Process process = Process.Start(startInfo)) + { + // Read both outputs before writing the input, so that a full output pipe cannot + // block git while the test writes. + Task outputTask = process.StandardOutput.ReadToEndAsync(); + Task errorTask = process.StandardError.ReadToEndAsync(); + + if (input != null) + { + process.StandardInput.Write(input); + } + + process.StandardInput.Close(); + + if (!process.WaitForExit(GitTimeoutMilliseconds)) + { + process.Kill(entireProcessTree: true); + Assert.Fail("git " + string.Join(" ", arguments) + " did not finish in time."); + } + + output = outputTask.Result; + errors = errorTask.Result; + process.ExitCode.ShouldEqual(0, "git " + string.Join(" ", arguments) + " failed: " + errors); + } + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/ConeBuilderTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/ConeBuilderTests.cs new file mode 100644 index 000000000..ecd8361e8 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/ConeBuilderTests.cs @@ -0,0 +1,332 @@ +using System; +using System.Linq; +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using GVFS.UnitTests.Category; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class ConeBuilderTests + { + // The worked examples use this tree: + // / + // root.txt + // .gitattributes + // A/ + // a.txt + // .gitattributes + // B/ + // b.txt + // C/ + // c.txt + // D/ + // d.txt + private const string Header = "/*\n!/*/\n"; + + [TestCase] + public void EmptyModifiedSetProducesHeaderOnly() + { + SerializeCone().ShouldEqual(Header); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void NullModifiedPathsThrows() + { + Assert.Throws(() => ConeBuilder.BuildFromModifiedPaths(null, ignoreCase: false)); + } + + [TestCase] + public void OneRootFileProducesHeaderOnly() + { + SerializeCone("root.txt").ShouldEqual(Header); + } + + [TestCase] + public void RootGitAttributesProducesNoExtraPattern() + { + SerializeCone(".gitattributes").ShouldEqual(Header); + } + + [TestCase] + public void OneDeepFileProducesParentOnlyChain() + { + SerializeCone("A/B/b.txt").ShouldEqual( + Header + + "/A/\n!/A/*/\n" + + "/A/B/\n!/A/B/*/\n"); + } + + [TestCase] + public void DeeplyNestedFileProducesFullParentOnlyChain() + { + SerializeCone("A/B/C/c.txt").ShouldEqual( + Header + + "/A/\n!/A/*/\n" + + "/A/B/\n!/A/B/*/\n" + + "/A/B/C/\n!/A/B/C/*/\n"); + } + + [TestCase] + public void TwoFilesInAdjacentDirectories() + { + SerializeCone("A/B/b.txt", "A/D/d.txt").ShouldEqual( + Header + + "/A/\n!/A/*/\n" + + "/A/B/\n!/A/B/*/\n" + + "/A/D/\n!/A/D/*/\n"); + } + + [TestCase] + public void OneDeepFileAndOneDeeperFile() + { + SerializeCone("A/B/b.txt", "A/B/C/c.txt").ShouldEqual( + Header + + "/A/\n!/A/*/\n" + + "/A/B/\n!/A/B/*/\n" + + "/A/B/C/\n!/A/B/C/*/\n"); + } + + [TestCase] + public void ModifiedFolderMapsToRecursive() + { + SerializeCone("A/B/").ShouldEqual( + Header + + "/A/\n!/A/*/\n" + + "/A/B/\n"); + } + + [TestCase] + public void FolderPlusSiblingFile() + { + SerializeCone("A/B/", "A/D/d.txt").ShouldEqual( + Header + + "/A/\n!/A/*/\n" + + "/A/D/\n!/A/D/*/\n" + + "/A/B/\n"); + } + + [TestCase] + public void TwoFilesInSameDirectoryProduceOneParentPair() + { + ConePatternSet cone = Build("A/B/b.txt", "A/B/b2.txt"); + + cone.RecursiveDirectories.ShouldBeEmpty(); + cone.ParentOnlyDirectories.ShouldMatchInOrder("A", "A/B"); + } + + [TestCase] + public void SingleModifiedFileNeverProducesRecursivePattern() + { + ConePatternSet cone = Build("A/B/b.txt"); + + // An edited file must not pull its subtree into the index, so it must not + // create a recursive pattern. + cone.RecursiveDirectories.ShouldBeEmpty(); + cone.ParentOnlyDirectories.ShouldMatchInOrder("A", "A/B"); + } + + [TestCase] + public void FileInsideModifiedFolderNeedsNoParentPair() + { + // A/B/ (folder) is recursive. The file A/B/b.txt below it needs no parent-only + // pattern, because the recursive pattern already covers it. + ConePatternSet cone = Build("A/B/b.txt", "A/B/"); + + cone.RecursiveDirectories.ShouldMatchInOrder("A/B"); + cone.ParentOnlyDirectories.ShouldMatchInOrder("A"); + + SerializeCone("A/B/b.txt", "A/B/").ShouldEqual( + Header + + "/A/\n!/A/*/\n" + + "/A/B/\n"); + } + + [TestCase] + public void RecursiveAncestorRemovesChildRecursiveEntries() + { + ConePatternSet cone = Build("A/", "A/B/"); + + cone.RecursiveDirectories.ShouldMatchInOrder("A"); + cone.ParentOnlyDirectories.ShouldBeEmpty(); + + SerializeCone("A/", "A/B/").ShouldEqual(Header + "/A/\n"); + } + + [TestCase] + public void ParentOnlyDirectoriesBelowRecursiveVanish() + { + // The file's parent-only chain (A, A/B) is entirely inside the recursive A/, + // so nothing parent-only survives. + ConePatternSet cone = Build("A/B/x.txt", "A/"); + + cone.RecursiveDirectories.ShouldMatchInOrder("A"); + cone.ParentOnlyDirectories.ShouldBeEmpty(); + } + + [TestCase] + public void ParentOnlyAncestorOfRecursiveIsKept() + { + // A is an ancestor of the recursive A/B, not a descendant, so it stays + // parent-only: a recursive directory does not include its ancestors' direct files. + ConePatternSet cone = Build("A/B/"); + + cone.RecursiveDirectories.ShouldMatchInOrder("A/B"); + cone.ParentOnlyDirectories.ShouldMatchInOrder("A"); + } + + [TestCase] + public void SiblingRecursiveFoldersAreBothKept() + { + ConePatternSet cone = Build("A/B/", "A/D/"); + + cone.RecursiveDirectories.ShouldMatchInOrder("A/B", "A/D"); + cone.ParentOnlyDirectories.ShouldMatchInOrder("A"); + } + + [TestCase] + public void SimilarPrefixIsNotTreatedAsAncestor() + { + // "AB" starts with "A" but is not below it, so the recursive A/ must not remove it. + ConePatternSet cone = Build("A/", "AB/x.txt"); + + cone.RecursiveDirectories.ShouldMatchInOrder("A"); + cone.ParentOnlyDirectories.ShouldMatchInOrder("AB"); + } + + [TestCase] + public void NullAndEmptyEntriesAreSkipped() + { + ConePatternSet cone = Build(null, string.Empty, "/", "A/B/b.txt"); + + cone.RecursiveDirectories.ShouldBeEmpty(); + cone.ParentOnlyDirectories.ShouldMatchInOrder("A", "A/B"); + } + + [TestCase] + public void PathsAreNormalizedBeforeMapping() + { + // Backslashes, a leading slash, and duplicate separators must all give the + // same cone as the canonical git-form input. + string canonical = SerializeCone("A/B/b.txt"); + + SerializeCone(@"A\B\b.txt").ShouldEqual(canonical); + SerializeCone("/A/B/b.txt").ShouldEqual(canonical); + SerializeCone("A//B/b.txt").ShouldEqual(canonical); + SerializeCone(@"A\B\").ShouldEqual(SerializeCone("A/B/")); + } + + [TestCase] + public void OutputIsSortedOrdinally() + { + // Ordinal sort places all uppercase letters before lowercase, as git's + // strcmp-based writer does. + ConePatternSet cone = Build("a/one.txt", "B/two.txt"); + + cone.ParentOnlyDirectories.ShouldMatchInOrder("B", "a"); + } + + [TestCase] + public void GlobSpecialCharactersInPathAreEscaped() + { + SerializeCone("A/B[1]/x.txt", "weird*dir/f.txt", "q?dir/f.txt").ShouldEqual( + Header + + "/A/\n!/A/*/\n" + + "/A/B\\[1]/\n!/A/B\\[1]/*/\n" + + "/q\\?dir/\n!/q\\?dir/*/\n" + + "/weird\\*dir/\n!/weird\\*dir/*/\n"); + } + + [TestCase] + public void CaseVariantDirectoriesStaySeparateWhenCaseMatters() + { + ConePatternSet cone = Build("src/x.cs", "Src/y.cs"); + + cone.ParentOnlyDirectories.ShouldMatchInOrder("Src", "src"); + } + + [TestCase] + public void CaseVariantDirectoriesMergeWhenIgnoringCase() + { + // Under core.ignoreCase, git treats "Src" and "src" as one pattern. If the file + // names both, git reports a repeated pattern and turns off cone matching. + ConePatternSet cone = BuildIgnoringCase("src/x.cs", "Src/y.cs", "SRC/Deep/z.cs"); + + cone.RecursiveDirectories.ShouldBeEmpty(); + cone.ParentOnlyDirectories.ShouldMatchInOrder("SRC", "SRC/Deep"); + } + + [TestCase] + public void CaseVariantMergeKeepsOrdinallySmallestSpellingForAnyInputOrder() + { + string[] paths = new[] { "src/x.cs", "lower/UPPER/f.txt", "Src/y.cs", "Lower/upper/Sub/" }; + + ConePatternSet forward = BuildIgnoringCase(paths); + ConePatternSet reversed = BuildIgnoringCase(paths.Reverse().ToArray()); + + forward.ParentOnlyDirectories.ShouldMatchInOrder("Lower", "Lower/upper", "Src"); + forward.RecursiveDirectories.ShouldMatchInOrder("Lower/upper/Sub"); + reversed.ParentOnlyDirectories.ShouldMatchInOrder(forward.ParentOnlyDirectories); + reversed.RecursiveDirectories.ShouldMatchInOrder(forward.RecursiveDirectories); + } + + [TestCase] + public void RecursiveDirectoryCoversCaseVariantParentsWhenIgnoringCase() + { + // "A/B" and "A/B/C" are the recursive "a/b" or below it when case is ignored. + // The recursive directory also takes the ordinally smallest spelling, "A/B". + ConePatternSet cone = BuildIgnoringCase("a/b/", "A/B/C/f.txt"); + + cone.IgnoreCase.ShouldBeTrue(); + cone.RecursiveDirectories.ShouldMatchInOrder("A/B"); + cone.ParentOnlyDirectories.ShouldMatchInOrder("A"); + } + + [TestCase] + public void NonAsciiCaseVariantsStaySeparateWhenIgnoringCase() + { + // Git folds only ASCII letters, so it treats "\u00C4" and "\u00E4" as different + // directories. Merging them would leave the files of one directory out of the cone. + ConePatternSet cone = BuildIgnoringCase("\u00C4/x.txt", "\u00E4/y.txt"); + + cone.ParentOnlyDirectories.ShouldMatchInOrder("\u00C4", "\u00E4"); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void PathWithLineBreakInADirectoryFailsTheBuild() + { + // Serialized as is, this path would add a "!src" line to the file. Git would then + // turn off cone matching and leave the modified file src/main.c out of the cone. + Assert.Throws( + () => ConeBuilder.BuildFromModifiedPaths(new[] { "src/main.c", "z\n!src\nb/f.txt" }, ignoreCase: false)); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void DotDotDirectoryFailsTheBuildEvenBelowARecursiveDirectory() + { + // "A/D/../C" looks like a descendant of the recursive "A/D". If the builder dropped + // it as covered, "A/C/f.txt" would be outside the cone. + Assert.Throws( + () => ConeBuilder.BuildFromModifiedPaths(new[] { "A/D/", "A/D/../C/f.txt" }, ignoreCase: false)); + } + + private static ConePatternSet Build(params string[] modifiedPaths) + { + return ConeBuilder.BuildFromModifiedPaths(modifiedPaths, ignoreCase: false); + } + + private static ConePatternSet BuildIgnoringCase(params string[] modifiedPaths) + { + return ConeBuilder.BuildFromModifiedPaths(modifiedPaths, ignoreCase: true); + } + + private static string SerializeCone(params string[] modifiedPaths) + { + return ConeFileWriter.Serialize(Build(modifiedPaths)); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/ConeFileWriterTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/ConeFileWriterTests.cs new file mode 100644 index 000000000..5db8c5d7b --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/ConeFileWriterTests.cs @@ -0,0 +1,527 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using GVFS.UnitTests.Category; +using GVFS.UnitTests.Mock.FileSystem; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class ConeFileWriterTests + { + private const string RepoRoot = @"mock:\repo"; + private const string GitDir = @"mock:\repo\.git"; + private const string InfoDir = @"mock:\repo\.git\info"; + private const string SparseCheckoutPath = @"mock:\repo\.git\info\sparse-checkout"; + private const string BackupPath = SparseCheckoutPath + ConeFileWriter.BackupExtension; + private const string Header = "/*\n!/*/\n"; + private const string LegacyContent = "/.gitattributes"; + private const string OneFileCone = Header + "/A/\n!/A/*/\n" + "/A/B/\n!/A/B/*/\n"; + + public enum TransientFailure + { + Win32AccessDenied, + Win32SharingViolation, + IOSharingViolation, + UnauthorizedAccess, + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void ConstructorThrowsOnNullFileSystem() + { + Assert.Throws(() => new ConeFileWriter(null)); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void SerializeThrowsOnNullCone() + { + Assert.Throws(() => ConeFileWriter.Serialize(null)); + } + + [TestCase] + public void SerializeEmptyConeProducesHeaderOnly() + { + ConeFileWriter.Serialize(new ConePatternSet(new string[0], new string[0], ignoreCase: false)).ShouldEqual(Header); + } + + [TestCase] + public void SerializeEmitsParentPairsThenRecursiveLines() + { + ConePatternSet cone = new ConePatternSet( + new[] { "A", "A/B" }, + new[] { "A/D" }, + ignoreCase: false); + + ConeFileWriter.Serialize(cone).ShouldEqual( + Header + + "/A/\n!/A/*/\n" + + "/A/B/\n!/A/B/*/\n" + + "/A/D/\n"); + } + + [TestCase("simple", "simple")] + [TestCase("A/B", "A/B")] + [TestCase("star*", "star\\*")] + [TestCase("q?", "q\\?")] + [TestCase("br[x", "br\\[x")] + [TestCase("back\\slash", "back\\\\slash")] + [TestCase("close]bracket", "close]bracket")] + [TestCase("all*?[\\", "all\\*\\?\\[\\\\")] + public void EscapePatternEscapesGlobSpecialCharacters(string input, string expected) + { + ConeFileWriter.EscapePattern(input).ShouldEqual(expected); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void EscapePatternThrowsOnNull() + { + Assert.Throws(() => ConeFileWriter.EscapePattern(null)); + } + + [TestCase] + public void WriteCreatesFileWhenNoneExists() + { + MockFileSystem fileSystem = CreateFileSystem(); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out Exception handledException) + .ShouldEqual(ConeFileWriteResult.Written); + + handledException.ShouldBeNull(); + backupPath.ShouldBeNull(); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(OneFileCone); + fileSystem.FileExists(SparseCheckoutPath + ".temp").ShouldBeFalse(); + } + + [TestCase] + public void WriteBacksUpLegacyContentAndReplacesIt() + { + MockFileSystem fileSystem = CreateFileSystem(); + fileSystem.WriteAllText(SparseCheckoutPath, LegacyContent + "\r\n"); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out Exception handledException) + .ShouldEqual(ConeFileWriteResult.Written); + + handledException.ShouldBeNull(); + backupPath.ShouldEqual(BackupPath); + fileSystem.ReadAllText(backupPath).ShouldEqual(LegacyContent + "\r\n"); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(OneFileCone); + } + + [TestCase] + public void WriteWithUnchangedContentWritesNothing() + { + MockFileSystem fileSystem = CreateFileSystem(); + fileSystem.WriteAllText(SparseCheckoutPath, OneFileCone); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out Exception handledException) + .ShouldEqual(ConeFileWriteResult.Unchanged); + + handledException.ShouldBeNull(); + backupPath.ShouldBeNull(); + fileSystem.FileExists(BackupPath).ShouldBeFalse(); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(OneFileCone); + } + + [TestCase] + public void WriteTreatsDifferentLineEndingsAsChangedContent() + { + // Git reads either line ending, but the writer compares exact content. A file with + // CRLF line endings is rewritten with LF, as git's own writer would write it. + MockFileSystem fileSystem = CreateFileSystem(); + fileSystem.WriteAllText(SparseCheckoutPath, OneFileCone.Replace("\n", "\r\n")); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out _, out _).ShouldEqual(ConeFileWriteResult.Written); + + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(OneFileCone); + } + + [TestCase] + public void WriteReplacesSameTextInAnotherEncoding() + { + // Git reads bytes. It cannot parse a UTF-16 file, even when the decoded text is the + // same as the serialized cone. + MockFileSystem fileSystem = CreateFileSystem(); + byte[] utf16Content = Encoding.Unicode.GetPreamble().Concat(Encoding.Unicode.GetBytes(OneFileCone)).ToArray(); + WriteBytes(fileSystem, SparseCheckoutPath, utf16Content); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out _).ShouldEqual(ConeFileWriteResult.Written); + + fileSystem.ReadAllBytes(SparseCheckoutPath).ShouldMatchInOrder(Encoding.UTF8.GetBytes(OneFileCone)); + fileSystem.ReadAllBytes(backupPath).ShouldMatchInOrder(utf16Content); + } + + [TestCase] + public void BackupAndRestoreKeepTheExactBytes() + { + // 0xE9 is not valid UTF-8. A text round trip would change it to U+FFFD. + byte[] originalBytes = new byte[] { (byte)'/', (byte)'*', (byte)'\n', 0xE9, (byte)'\n' }; + MockFileSystem fileSystem = CreateFileSystem(); + WriteBytes(fileSystem, SparseCheckoutPath, originalBytes); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out _).ShouldEqual(ConeFileWriteResult.Written); + fileSystem.ReadAllBytes(backupPath).ShouldMatchInOrder(originalBytes); + + writer.TryRestoreBackup(SparseCheckoutPath, backupPath, out Exception restoreException).ShouldBeTrue(); + restoreException.ShouldBeNull(); + fileSystem.ReadAllBytes(SparseCheckoutPath).ShouldMatchInOrder(originalBytes); + } + + [TestCase] + public void WriteWithUnchangedNonAsciiContentWritesNothing() + { + ConePatternSet cone = ConeBuilder.BuildFromModifiedPaths(new[] { "\u00C4/x.txt" }, ignoreCase: false); + MockFileSystem fileSystem = CreateFileSystem(); + WriteBytes(fileSystem, SparseCheckoutPath, Encoding.UTF8.GetBytes(Header + "/\u00C4/\n!/\u00C4/*/\n")); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, cone, out string backupPath, out _).ShouldEqual(ConeFileWriteResult.Unchanged); + + backupPath.ShouldBeNull(); + } + + [TestCase(false)] + [TestCase(true)] + [Category(CategoryConstants.ExceptionExpected)] + public void WriteFailsWhenExistingFileCannotBeRead(bool accessDenied) + { + // A file that cannot be read must not look like a missing file, or the write would + // replace it without a backup. + Exception readFailure = accessDenied ? new UnauthorizedAccessException("Injected access failure") : new IOException("Injected read failure"); + FailingFileSystem fileSystem = new FailingFileSystem { FailReadPath = SparseCheckoutPath, ReadFailure = readFailure }; + fileSystem.WriteAllText(SparseCheckoutPath, LegacyContent); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out Exception handledException) + .ShouldEqual(ConeFileWriteResult.Failed); + + backupPath.ShouldBeNull(); + handledException.ShouldBeSameAs(readFailure); + fileSystem.FileExists(BackupPath).ShouldBeFalse(); + fileSystem.FailReadPath = null; + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(LegacyContent); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void WriteFailsAndKeepsTargetWhenBackupCannotBeWritten() + { + FailingFileSystem fileSystem = new FailingFileSystem { FailRenameDestination = BackupPath }; + fileSystem.WriteAllText(SparseCheckoutPath, LegacyContent); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out Exception handledException) + .ShouldEqual(ConeFileWriteResult.Failed); + + backupPath.ShouldBeNull(); + handledException.ShouldBeOfType(); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(LegacyContent); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void WriteFailsAndKeepsTargetWhenRenameFails() + { + // The new content goes to a temporary file first. If the rename over the target + // fails, the target keeps its previous content, and the backup path is still + // returned so that the caller can roll back other state. A failure that is not + // access denied or a sharing violation gets no retry. + FailingFileSystem fileSystem = new FailingFileSystem { FailRenameDestination = SparseCheckoutPath }; + fileSystem.WriteAllText(SparseCheckoutPath, LegacyContent); + List sleeps = new List(); + ConeFileWriter writer = new ConeFileWriter(fileSystem, sleeps.Add); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out Exception handledException) + .ShouldEqual(ConeFileWriteResult.Failed); + + backupPath.ShouldEqual(BackupPath); + handledException.ShouldBeOfType(); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(LegacyContent); + fileSystem.ReadAllText(BackupPath).ShouldEqual(LegacyContent); + fileSystem.RenameAttempts.ShouldEqual(1); + sleeps.ShouldBeEmpty(); + } + + [TestCase(TransientFailure.Win32AccessDenied)] + [TestCase(TransientFailure.Win32SharingViolation)] + [TestCase(TransientFailure.IOSharingViolation)] + [TestCase(TransientFailure.UnauthorizedAccess)] + [Category(CategoryConstants.ExceptionExpected)] + public void WriteRetriesReplaceAfterTransientFailure(TransientFailure failure) + { + FailingFileSystem fileSystem = new FailingFileSystem + { + FailRenameDestination = SparseCheckoutPath, + RenameFailure = () => CreateTransientFailure(failure), + RenameFailureCount = 2, + }; + fileSystem.WriteAllText(SparseCheckoutPath, LegacyContent); + List sleeps = new List(); + ConeFileWriter writer = new ConeFileWriter(fileSystem, sleeps.Add); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out Exception handledException) + .ShouldEqual(ConeFileWriteResult.Written); + + handledException.ShouldBeNull(); + backupPath.ShouldEqual(BackupPath); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(OneFileCone); + fileSystem.RenameAttempts.ShouldEqual(3); + sleeps.ShouldMatchInOrder(TimeSpan.Zero, TimeSpan.FromMilliseconds(1)); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void WriteStopsRetryingWhenDefaultBudgetIsSpent() + { + FailingFileSystem fileSystem = new FailingFileSystem + { + FailRenameDestination = SparseCheckoutPath, + RenameFailure = () => new System.ComponentModel.Win32Exception(32), + }; + fileSystem.WriteAllText(SparseCheckoutPath, LegacyContent); + List sleeps = new List(); + ConeFileWriter writer = new ConeFileWriter(fileSystem, sleeps.Add); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out _, out Exception handledException) + .ShouldEqual(ConeFileWriteResult.Failed); + + handledException.ShouldBeOfType().NativeErrorCode.ShouldEqual(32); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(LegacyContent); + fileSystem.RenameAttempts.ShouldEqual(6); + sleeps.Select(sleep => sleep.TotalMilliseconds).ShouldMatchInOrder(0.0, 1.0, 10.0, 20.0, 40.0); + sleeps.Aggregate(TimeSpan.Zero, (total, sleep) => total + sleep).ShouldBeAtMost(ConeFileWriter.DefaultReplaceRetryBudget); + } + + [TestCase(0, 1)] + [TestCase(10, 3)] + [TestCase(11, 4)] + [TestCase(150, 7)] + [Category(CategoryConstants.ExceptionExpected)] + public void WriteRetriesWithinCallerBudget(int budgetMilliseconds, int expectedAttempts) + { + // The delays are 0, 1, 10, 20, 40, then 40 again, so a budget of 10 ms allows two + // waits and a budget of 150 ms allows six. + FailingFileSystem fileSystem = new FailingFileSystem + { + FailRenameDestination = SparseCheckoutPath, + RenameFailure = () => new System.ComponentModel.Win32Exception(5), + }; + fileSystem.WriteAllText(SparseCheckoutPath, LegacyContent); + List sleeps = new List(); + ConeFileWriter writer = new ConeFileWriter(fileSystem, sleeps.Add); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out _, out _, TimeSpan.FromMilliseconds(budgetMilliseconds)) + .ShouldEqual(ConeFileWriteResult.Failed); + + fileSystem.RenameAttempts.ShouldEqual(expectedAttempts); + sleeps.Count.ShouldEqual(expectedAttempts - 1); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(LegacyContent); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void WriteThrowsOnNegativeRetryBudget() + { + ConeFileWriter writer = new ConeFileWriter(CreateFileSystem()); + + Assert.Throws( + () => writer.Write(SparseCheckoutPath, OneFileConeSet(), out _, out _, TimeSpan.FromMilliseconds(-1))); + Assert.Throws( + () => writer.TryRestoreBackup(SparseCheckoutPath, BackupPath, out _, TimeSpan.FromMilliseconds(-1))); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void WriteFailsWhenInfoDirectoryCannotBeCreated() + { + MockFileSystem fileSystem = CreateFileSystem(); + fileSystem.ExceptionThrownByCreateDirectory = new UnauthorizedAccessException("denied"); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out _, out Exception handledException) + .ShouldEqual(ConeFileWriteResult.Failed); + + handledException.ShouldBeOfType(); + } + + [TestCase] + public void TryRestoreBackupRestoresPreviousContent() + { + MockFileSystem fileSystem = CreateFileSystem(); + fileSystem.WriteAllText(SparseCheckoutPath, LegacyContent + "\r\n"); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.Write(SparseCheckoutPath, OneFileConeSet(), out string backupPath, out _).ShouldEqual(ConeFileWriteResult.Written); + + writer.TryRestoreBackup(SparseCheckoutPath, backupPath, out Exception restoreException).ShouldBeTrue(); + + restoreException.ShouldBeNull(); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(LegacyContent + "\r\n"); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void TryRestoreBackupRetriesReplaceAfterTransientFailure() + { + FailingFileSystem fileSystem = new FailingFileSystem + { + FailRenameDestination = SparseCheckoutPath, + RenameFailure = () => new System.ComponentModel.Win32Exception(5), + RenameFailureCount = 1, + }; + fileSystem.WriteAllText(SparseCheckoutPath, OneFileCone); + fileSystem.WriteAllText(BackupPath, LegacyContent); + List sleeps = new List(); + ConeFileWriter writer = new ConeFileWriter(fileSystem, sleeps.Add); + + writer.TryRestoreBackup(SparseCheckoutPath, BackupPath, out Exception restoreException).ShouldBeTrue(); + + restoreException.ShouldBeNull(); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(LegacyContent); + fileSystem.RenameAttempts.ShouldEqual(2); + sleeps.ShouldMatchInOrder(TimeSpan.Zero); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void TryRestoreBackupFailsWhenBackupCannotBeRead() + { + FailingFileSystem fileSystem = new FailingFileSystem { FailReadPath = BackupPath }; + fileSystem.WriteAllText(SparseCheckoutPath, OneFileCone); + fileSystem.WriteAllText(BackupPath, LegacyContent); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.TryRestoreBackup(SparseCheckoutPath, BackupPath, out Exception restoreException).ShouldBeFalse(); + + restoreException.ShouldBeOfType(); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(OneFileCone); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void TryRestoreBackupFailsWhenBackupIsMissing() + { + MockFileSystem fileSystem = CreateFileSystem(); + fileSystem.WriteAllText(SparseCheckoutPath, OneFileCone); + ConeFileWriter writer = new ConeFileWriter(fileSystem); + + writer.TryRestoreBackup(SparseCheckoutPath, BackupPath, out Exception restoreException).ShouldBeFalse(); + + restoreException.ShouldBeOfType(); + fileSystem.ReadAllText(SparseCheckoutPath).ShouldEqual(OneFileCone); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void WriteThrowsOnNullArguments() + { + ConeFileWriter writer = new ConeFileWriter(CreateFileSystem()); + ConePatternSet cone = new ConePatternSet(new string[0], new string[0], ignoreCase: false); + + Assert.Throws(() => writer.Write(null, cone, out _, out _)); + Assert.Throws(() => writer.Write(SparseCheckoutPath, null, out _, out _)); + } + + private static ConePatternSet OneFileConeSet() + { + return ConeBuilder.BuildFromModifiedPaths(new[] { "A/B/b.txt" }, ignoreCase: false); + } + + private static Exception CreateTransientFailure(TransientFailure failure) + { + switch (failure) + { + case TransientFailure.Win32AccessDenied: + return new System.ComponentModel.Win32Exception(5); + case TransientFailure.Win32SharingViolation: + return new System.ComponentModel.Win32Exception(32); + case TransientFailure.IOSharingViolation: + return new IOException("Injected sharing violation", unchecked((int)0x80070020)); + case TransientFailure.UnauthorizedAccess: + return new UnauthorizedAccessException("Injected access denied"); + default: + throw new ArgumentOutOfRangeException(nameof(failure)); + } + } + + private static void WriteBytes(MockFileSystem fileSystem, string path, byte[] contents) + { + fileSystem.RootDirectory.AddOrOverwriteFile(new MockFile(path, contents), path); + } + + private static MockFileSystem CreateFileSystem() + { + MockDirectory info = new MockDirectory(InfoDir, folders: null, files: null); + MockDirectory git = new MockDirectory(GitDir, new[] { info }, files: null); + MockDirectory root = new MockDirectory(RepoRoot, new[] { git }, files: null); + return new MockFileSystem(root); + } + + private sealed class FailingFileSystem : MockFileSystem + { + public FailingFileSystem() + : base(CreateFileSystem().RootDirectory) + { + } + + public string FailReadPath { get; set; } + + public Exception ReadFailure { get; set; } + + public string FailRenameDestination { get; set; } + + public Func RenameFailure { get; set; } + + public int RenameFailureCount { get; set; } = int.MaxValue; + + public int RenameAttempts { get; private set; } + + public override string ReadAllText(string path) + { + this.ThrowIfReadFails(path); + return base.ReadAllText(path); + } + + public override byte[] ReadAllBytes(string path) + { + this.ThrowIfReadFails(path); + return base.ReadAllBytes(path); + } + + public override void MoveAndOverwriteFile(string sourcePath, string destinationPath) + { + if (string.Equals(destinationPath, this.FailRenameDestination, StringComparison.OrdinalIgnoreCase)) + { + this.RenameAttempts++; + if (this.RenameAttempts <= this.RenameFailureCount) + { + throw this.RenameFailure?.Invoke() ?? new IOException("Injected rename failure"); + } + } + + base.MoveAndOverwriteFile(sourcePath, destinationPath); + } + + private void ThrowIfReadFails(string path) + { + if (string.Equals(path, this.FailReadPath, StringComparison.OrdinalIgnoreCase)) + { + throw this.ReadFailure ?? new IOException("Injected read failure"); + } + } + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/ConePathMatcherTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/ConePathMatcherTests.cs new file mode 100644 index 000000000..e637f8e8f --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/ConePathMatcherTests.cs @@ -0,0 +1,91 @@ +using System; +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using GVFS.UnitTests.Category; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class ConePathMatcherTests + { + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void ConstructorThrowsOnNullCone() + { + Assert.Throws(() => new ConePathMatcher(null)); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void IsInConeThrowsOnNullPath() + { + ConePathMatcher matcher = new ConePathMatcher(Cone()); + Assert.Throws(() => matcher.IsInCone(null)); + } + + [TestCase("root.txt", true)] + [TestCase("", true)] + [TestCase("/", true)] + [TestCase("X/f.txt", false)] + [TestCase("X/", false)] + [TestCase("A/f.txt", true)] + [TestCase("A/", true)] + [TestCase("A/C/f.txt", false)] + [TestCase("A/C/", false)] + [TestCase("A/B/f.txt", true)] + [TestCase("A/B/", true)] + [TestCase("A/B/E/f.txt", false)] + [TestCase("A/D/f.txt", true)] + [TestCase("A/D/E/F/f.txt", true)] + [TestCase("A/D/E/F/", true)] + [TestCase(@"A\D\E\f.txt", true)] + [TestCase("/A/f.txt", true)] + public void IsInConeFollowsConeRules(string path, bool expected) + { + // Parent-only A and A/B, recursive A/D. + ConePathMatcher matcher = new ConePathMatcher( + ConeBuilder.BuildFromModifiedPaths(new[] { "A/B/b.txt", "A/D/" }, ignoreCase: false)); + + matcher.IsInCone(path).ShouldEqual(expected); + } + + [TestCase] + public void PathThatIsItselfRecursiveIsInCone() + { + // Git checks the full path against the recursive set before it checks the parent, + // so the path is in the cone even when the cone omits the parent pair. For a + // directory query, git checks the file "-" inside the directory the same way. + ConePathMatcher matcher = new ConePathMatcher(Cone(recursive: new[] { "A/B", "C/-" })); + + matcher.IsInCone("A/B").ShouldBeTrue(); + matcher.IsInCone("A/B/f.txt").ShouldBeTrue(); + matcher.IsInCone("A/f.txt").ShouldBeFalse(); + matcher.IsInCone("C/").ShouldBeTrue(); + matcher.IsInCone("C/f.txt").ShouldBeFalse(); + } + + [TestCase(false, "a/f.txt", false)] + [TestCase(true, "a/f.txt", true)] + [TestCase(true, "a/c/f.txt", false)] + [TestCase(true, "a/d/e/f.txt", true)] + [TestCase(true, "a/D/", true)] + [TestCase(false, "\u00C4/f.txt", true)] + [TestCase(false, "\u00E4/f.txt", false)] + [TestCase(true, "\u00E4/f.txt", false)] + public void IgnoreCaseFoldsAsciiOnly(bool ignoreCase, string path, bool expected) + { + // The matcher uses the case rule of the cone. Git folds only ASCII letters under + // core.ignoreCase (see GitPathComparer). + ConePathMatcher matcher = new ConePathMatcher( + Cone(parentOnly: new[] { "A", "\u00C4" }, recursive: new[] { "A/D" }, ignoreCase: ignoreCase)); + + matcher.IsInCone(path).ShouldEqual(expected); + } + + private static ConePatternSet Cone(string[] parentOnly = null, string[] recursive = null, bool ignoreCase = false) + { + return new ConePatternSet(parentOnly ?? new string[0], recursive ?? new string[0], ignoreCase); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/ConePatternSetTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/ConePatternSetTests.cs new file mode 100644 index 000000000..37961ffe1 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/ConePatternSetTests.cs @@ -0,0 +1,94 @@ +using System; +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using GVFS.UnitTests.Category; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class ConePatternSetTests + { + [TestCase(false)] + [TestCase(true)] + public void AcceptsDistinctDirectories(bool ignoreCase) + { + ConePatternSet cone = new ConePatternSet(new[] { "A", "A/B" }, new[] { "A/C", "\u00C4", "\u00E4" }, ignoreCase); + + cone.IgnoreCase.ShouldEqual(ignoreCase); + cone.ParentOnlyDirectories.ShouldMatchInOrder("A", "A/B"); + cone.RecursiveDirectories.ShouldMatchInOrder("A/C", "\u00C4", "\u00E4"); + } + + [TestCase] + public void AcceptsAsciiCaseVariantsWhenCaseMatters() + { + new ConePatternSet(new[] { "Src", "src" }, new[] { "SRC" }, ignoreCase: false) + .ParentOnlyDirectories.ShouldMatchInOrder("Src", "src"); + } + + // Git turns off cone matching for most of these. The set rejects all of them, so that + // each directory has one meaning in the cone. + [TestCase(new[] { "A", "A" }, new string[0], false)] + [TestCase(new string[0], new[] { "A", "A" }, false)] + [TestCase(new[] { "A" }, new[] { "A" }, false)] + [TestCase(new[] { "Src", "src" }, new string[0], true)] + [TestCase(new[] { "Src" }, new[] { "src" }, true)] + [Category(CategoryConstants.ExceptionExpected)] + public void RejectsRepeatedDirectories(string[] parentOnly, string[] recursive, bool ignoreCase) + { + Assert.Throws(() => new ConePatternSet(parentOnly, recursive, ignoreCase)); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("/A")] + [TestCase("A/")] + [TestCase("A//B")] + [TestCase(".")] + [TestCase("A/..")] + [TestCase("A/./B")] + [TestCase("*")] + [TestCase("A/*")] + [TestCase("A\nB")] + [TestCase("A\rB")] + [TestCase("A\0B")] + [TestCase(@"A\B")] + [TestCase(@"\")] + [Category(CategoryConstants.ExceptionExpected)] + public void RejectsDirectoriesThatGitCannotReadBack(string directory) + { + ConePatternSet.IsValidDirectory(directory).ShouldBeFalse(); + Assert.Throws(() => new ConePatternSet(new[] { directory }, new string[0], ignoreCase: false)); + Assert.Throws(() => new ConePatternSet(new string[0], new[] { directory }, ignoreCase: false)); + } + + [TestCase] + public void RejectsUnpairedSurrogates() + { + // Attribute arguments cannot hold an unpaired surrogate, so build the strings here. + ConePatternSet.IsValidDirectory(new string(new[] { 'A', '\uD800' })).ShouldBeFalse(); + ConePatternSet.IsValidDirectory(new string(new[] { '\uDC00', 'A' })).ShouldBeFalse(); + ConePatternSet.IsValidDirectory(new string(new[] { '\uD800', 'A', '\uDC00' })).ShouldBeFalse(); + } + + [TestCase("A")] + [TestCase("A/B")] + [TestCase("weird*dir")] + [TestCase("br[1]")] + [TestCase("...")] + [TestCase("\u00C4/\uD83D\uDE00")] + public void AcceptsOtherDirectories(string directory) + { + ConePatternSet.IsValidDirectory(directory).ShouldBeTrue(); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void RejectsNullLists() + { + Assert.Throws(() => new ConePatternSet(null, new string[0], ignoreCase: false)); + Assert.Throws(() => new ConePatternSet(new string[0], null, ignoreCase: false)); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/GitPathComparerTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/GitPathComparerTests.cs new file mode 100644 index 000000000..8fe3ced1e --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/GitPathComparerTests.cs @@ -0,0 +1,51 @@ +using System; +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using GVFS.UnitTests.Category; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class GitPathComparerTests + { + [TestCase(false, "Src", "Src", true)] + [TestCase(false, "Src", "src", false)] + [TestCase(true, "Src", "src", true)] + [TestCase(true, "SRC/Deep", "src/deep", true)] + [TestCase(true, "\u00C4", "\u00E4", false)] + [TestCase(true, "a", "ab", false)] + [TestCase(true, "ab", "a", false)] + [TestCase(true, null, "a", false)] + [TestCase(true, "a", null, false)] + [TestCase(true, null, null, true)] + public void EqualsFoldsAsciiOnlyWhenIgnoringCase(bool ignoreCase, string left, string right, bool expected) + { + GitPathComparer comparer = GitPathComparer.GetComparer(ignoreCase); + + comparer.Equals(left, right).ShouldEqual(expected); + if (expected && left != null) + { + comparer.GetHashCode(left).ShouldEqual(comparer.GetHashCode(right)); + } + } + + [TestCase(false, "A/B", "A", true)] + [TestCase(false, "A/B", "a", false)] + [TestCase(true, "A/B", "a", true)] + [TestCase(true, "AB", "a", false)] + [TestCase(true, "A", "A", false)] + [TestCase(true, "A", "A/B", false)] + public void IsDescendantOfRequiresASeparatorAfterTheAncestor(bool ignoreCase, string path, string ancestor, bool expected) + { + GitPathComparer.GetComparer(ignoreCase).IsDescendantOf(path, ancestor).ShouldEqual(expected); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void GetHashCodeThrowsOnNull() + { + Assert.Throws(() => GitPathComparer.IgnoreAsciiCase.GetHashCode(null)); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/SparseCheckoutPathResolverTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/SparseCheckoutPathResolverTests.cs new file mode 100644 index 000000000..62ad6746a --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/SparseCheckoutPathResolverTests.cs @@ -0,0 +1,71 @@ +using System; +using System.IO; +using GVFS.Common; +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using GVFS.UnitTests.Category; +using GVFS.UnitTests.Mock.Common; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class SparseCheckoutPathResolverTests + { + private const string PrimaryGitDir = @"mock:\repo\src\.git"; + private const string WorktreeGitDir = @"mock:\repo\src\.git\worktrees\linked1"; + + [TestCase] + public void PrimaryEnlistmentUsesDotGitRoot() + { + SparseCheckoutPathResolver.GetSparseCheckoutFilePath(isWorktree: false, dotGitRoot: PrimaryGitDir, worktreeGitDir: WorktreeGitDir) + .ShouldEqual(Path.Combine(PrimaryGitDir, "info", "sparse-checkout")); + } + + [TestCase] + public void LinkedWorktreeUsesWorktreeGitDir() + { + // GVFSEnlistment.DotGitRoot is the shared git dir for a worktree, but each worktree + // has its own sparse-checkout file. + SparseCheckoutPathResolver.GetSparseCheckoutFilePath(isWorktree: true, dotGitRoot: PrimaryGitDir, worktreeGitDir: WorktreeGitDir) + .ShouldEqual(Path.Combine(WorktreeGitDir, "info", "sparse-checkout")); + } + + [TestCase] + public void PrimaryEnlistmentOverloadUsesDotGitRoot() + { + GVFSEnlistment enlistment = new MockGVFSEnlistment(); + + SparseCheckoutPathResolver.GetSparseCheckoutFilePath(enlistment) + .ShouldEqual(Path.Combine(enlistment.DotGitRoot, "info", "sparse-checkout")); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void PrimaryEnlistmentThrowsWhenDotGitRootMissing() + { + Assert.Throws( + () => SparseCheckoutPathResolver.GetSparseCheckoutFilePath(isWorktree: false, dotGitRoot: null, worktreeGitDir: WorktreeGitDir)); + Assert.Throws( + () => SparseCheckoutPathResolver.GetSparseCheckoutFilePath(isWorktree: false, dotGitRoot: string.Empty, worktreeGitDir: WorktreeGitDir)); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void WorktreeEnlistmentThrowsWhenWorktreeGitDirMissing() + { + Assert.Throws( + () => SparseCheckoutPathResolver.GetSparseCheckoutFilePath(isWorktree: true, dotGitRoot: PrimaryGitDir, worktreeGitDir: null)); + Assert.Throws( + () => SparseCheckoutPathResolver.GetSparseCheckoutFilePath(isWorktree: true, dotGitRoot: PrimaryGitDir, worktreeGitDir: string.Empty)); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void EnlistmentOverloadThrowsOnNull() + { + Assert.Throws( + () => SparseCheckoutPathResolver.GetSparseCheckoutFilePath(null)); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/WorktreeEnlistmentTests.cs b/GVFS/GVFS.UnitTests/Common/WorktreeEnlistmentTests.cs index 2dac93294..5387a68ba 100644 --- a/GVFS/GVFS.UnitTests/Common/WorktreeEnlistmentTests.cs +++ b/GVFS/GVFS.UnitTests/Common/WorktreeEnlistmentTests.cs @@ -1,6 +1,7 @@ using GVFS.Common; using GVFS.Common.FileSystem; using GVFS.Common.Git; +using GVFS.Common.Sparse; using GVFS.Tests.Should; using GVFS.UnitTests.Mock.Common; using GVFS.UnitTests.Mock.Git; @@ -92,6 +93,15 @@ public void IsWorktreeReturnsTrueForWorktreeEnlistment() enlistment.IsWorktree.ShouldBeTrue(); } + [TestCase] + public void SparseCheckoutFileIsInTheWorktreeGitDir() + { + GVFSEnlistment enlistment = this.CreateWorktreeEnlistment(); + + SparseCheckoutPathResolver.GetSparseCheckoutFilePath(enlistment) + .ShouldEqual(Path.Combine(this.worktreeGitDir, "info", "sparse-checkout")); + } + [TestCase] public void WorktreeInfoIsPopulated() { diff --git a/GVFS/GVFS.UnitTests/Mock/FileSystem/MockFileSystem.cs b/GVFS/GVFS.UnitTests/Mock/FileSystem/MockFileSystem.cs index 8f039a7dc..d162624ad 100644 --- a/GVFS/GVFS.UnitTests/Mock/FileSystem/MockFileSystem.cs +++ b/GVFS/GVFS.UnitTests/Mock/FileSystem/MockFileSystem.cs @@ -5,6 +5,7 @@ using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; +using System.ComponentModel; using System.IO; namespace GVFS.UnitTests.Mock.FileSystem @@ -107,10 +108,38 @@ public override void MoveAndOverwriteFile(string sourcePath, string destinationP this.RootDirectory.RemoveFile(destinationPath); } - this.WriteAllText(destinationPath, this.ReadAllText(sourcePath)); + this.RootDirectory.AddOrOverwriteFile(new MockFile(destinationPath, this.ReadAllBytes(sourcePath)), destinationPath); this.RootDirectory.RemoveFile(sourcePath); } + public override bool TryCopyToTempFileAndRename(string sourcePath, string destinationPath, out Exception handledException) + { + handledException = null; + string tempFilePath = destinationPath + ".temp"; + + try + { + this.RootDirectory.AddOrOverwriteFile(new MockFile(tempFilePath, this.ReadAllBytes(sourcePath)), tempFilePath); + this.MoveAndOverwriteFile(tempFilePath, destinationPath); + return true; + } + catch (Win32Exception e) + { + handledException = e; + return false; + } + catch (IOException e) + { + handledException = e; + return false; + } + catch (UnauthorizedAccessException e) + { + handledException = e; + return false; + } + } + public override bool TryGetNormalizedPath(string path, out string normalizedPath, out string errorMessage) { normalizedPath = path; @@ -159,7 +188,7 @@ public override void WriteAllText(string path, string contents) public override string ReadAllText(string path) { - MockFile file = this.RootDirectory.FindFile(path); + MockFile file = this.FindExistingFile(path); using (StreamReader reader = new StreamReader(file.GetContentStream())) { @@ -169,7 +198,7 @@ public override string ReadAllText(string path) public override byte[] ReadAllBytes(string path) { - MockFile file = this.RootDirectory.FindFile(path); + MockFile file = this.FindExistingFile(path); using (Stream s = file.GetContentStream()) { @@ -344,5 +373,16 @@ private Stream CreateAndOpenFileStream(string path) return this.OpenFileStream(path, FileMode.Open, (FileAccess)NativeMethods.FileAccess.FILE_GENERIC_READ, FileShare.Read, callFlushFileBuffers: false); } + + private MockFile FindExistingFile(string path) + { + MockFile file = this.RootDirectory.FindFile(path); + if (file == null) + { + throw new FileNotFoundException("Mock file not found", path); + } + + return file; + } } }