diff --git a/GVFS/GVFS.Common/GVFSConstants.cs b/GVFS/GVFS.Common/GVFSConstants.cs index a9bdccaf9..425e9b3d4 100644 --- a/GVFS/GVFS.Common/GVFSConstants.cs +++ b/GVFS/GVFS.Common/GVFSConstants.cs @@ -103,6 +103,13 @@ public static class GitConfig public const string PrefetchOffload = GVFSPrefix + "prefetch-offload"; public const bool PrefetchOffloadDefault = false; + + /* Gates sparse-index support (git index.sparse). When true, the projection expands each + * sparse-directory entry from its tree, so the working directory stays full. When false + * (default), the projection rejects a sparse index. The mount reads it when it starts, + * and 'gvfs repair' reads it when it checks the index. */ + public const string AutoSparseIndex = GVFSPrefix + "auto-sparse-index"; + public const bool AutoSparseIndexDefault = false; } public static class LocalGVFSConfig @@ -170,6 +177,12 @@ public static class DotGVFS public const string LogName = "logs"; public const string MountLock = "mount.lock"; + /// + /// The mount creates this file when a working-tree change needs a sparse-index cone + /// change that the index does not have yet. The pre-command hook checks it. + /// + public const string ConeChangePending = "ConeChangePending"; + public static class Databases { public const string Name = "databases"; diff --git a/GVFS/GVFS.Common/Git/GVFSGitObjects.cs b/GVFS/GVFS.Common/Git/GVFSGitObjects.cs index 582d6b464..e6f7d4a4d 100644 --- a/GVFS/GVFS.Common/Git/GVFSGitObjects.cs +++ b/GVFS/GVFS.Common/Git/GVFSGitObjects.cs @@ -32,6 +32,7 @@ public enum RequestSource GVFSVerb, NamedPipeMessage, SymLinkCreation, + ProjectionBuild, } /// @@ -261,6 +262,12 @@ public DownloadAndSaveObjectResult TryDownloadAndSaveObject(string objectId, Req return this.TryDownloadAndSaveObject(objectId, CancellationToken.None, requestSource, retryOnFailure: true).Result; } + /// was canceled + public DownloadAndSaveObjectResult TryDownloadAndSaveObject(string objectId, CancellationToken cancellationToken, RequestSource requestSource) + { + return this.TryDownloadAndSaveObject(objectId, cancellationToken, requestSource, retryOnFailure: true).Result; + } + public bool TryGetBlobSizeLocally(string sha, out long length) { return this.Context.Repository.TryGetBlobLength(sha, out length); diff --git a/GVFS/GVFS.Common/Git/GitConfigSetting.cs b/GVFS/GVFS.Common/Git/GitConfigSetting.cs index e64dad75e..27c03d42f 100644 --- a/GVFS/GVFS.Common/Git/GitConfigSetting.cs +++ b/GVFS/GVFS.Common/Git/GitConfigSetting.cs @@ -6,6 +6,9 @@ public class GitConfigSetting { public const string CoreVirtualizeObjectsName = "core.virtualizeobjects"; public const string CoreVirtualFileSystemName = "core.virtualfilesystem"; + public const string CoreIgnoreCaseName = "core.ignorecase"; + public const string CoreSparseCheckoutName = "core.sparsecheckout"; + public const string IndexSparseName = "index.sparse"; public const string CredentialUseHttpPath = "credential.\"https://dev.azure.com\".useHttpPath"; public const string HttpSslCert = "http.sslcert"; diff --git a/GVFS/GVFS.Common/Git/GitProcess.cs b/GVFS/GVFS.Common/Git/GitProcess.cs index e5b4ceb39..edcbd728b 100644 --- a/GVFS/GVFS.Common/Git/GitProcess.cs +++ b/GVFS/GVFS.Common/Git/GitProcess.cs @@ -831,6 +831,167 @@ public Result Reset(string target, string paths) return this.InvokeGitInWorkingDirectoryRoot($"reset {target} {paths}", useReadObjectHook: false); } + /// + /// Make the sparse-directory entries of the index match the cone file with + /// git sparse-checkout reapply. Git expands each sparse-directory entry that the + /// cone now includes, and collapses each directory that the cone no longer includes. + /// + /// + /// For a mounted enlistment: + /// + /// The virtual file system stays on. Git then keeps the skip-worktree bits that + /// the mount reports, and it does not write working-tree files. + /// The hooks path stays as it is, because Git asks the virtual file system hook + /// which paths are present. + /// The read-object hook stays on, because Git can read tree objects that are not + /// local yet when it expands a directory. + /// COMMAND_HOOK_LOCK makes Git skip the pre-command and post-command hooks, + /// so this process does not ask for the GVFS lock or for a cone change. + /// index.deleteSparseDirectories=false stops Git from deleting the + /// working-tree directories that leave the cone. + /// + /// Git does not do the same with update-index --force-write-index: it does not + /// expand a sparse-directory entry that the cone now includes. + /// + public Result ReapplySparseCheckout() + { + return this.InvokeGitImpl( + "-c index.deleteSparseDirectories=false sparse-checkout reapply", + workingDirectory: this.workingDirectoryRoot, + dotGitDirectory: null, + useReadObjectHook: true, + writeStdIn: null, + parseStdOutLine: null, + timeoutMs: -1, + usePreCommandHook: false); + } + + /// + /// List the sparse-directory entries of the index with git ls-files --sparse. + /// + /// + /// ls-files --sparse reads a sparse index without expanding it. The virtual file + /// system stays on, so Git keeps the skip-worktree bits that the mount reports. + /// COMMAND_HOOK_LOCK makes Git skip the pre-command and post-command hooks. + /// + public Result ListSparseDirectories(Action onSparseDirectory) + { + ArgumentNullException.ThrowIfNull(onSparseDirectory); + + return this.InvokeGitImpl( + "ls-files --sparse -z", + workingDirectory: this.workingDirectoryRoot, + dotGitDirectory: null, + useReadObjectHook: false, + writeStdIn: null, + parseStdOutLine: null, + timeoutMs: -1, + usePreCommandHook: false, + parseStdOutToken: path => + { + if (path.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal)) + { + onSparseDirectory(path); + } + }); + } + + /// + /// List the paths that differ between HEAD and the index or the working tree, with + /// git status --porcelain=v2: changed and unmerged tracked paths, and untracked + /// files. An untracked folder ends with '/'. Git does not list ignored files. + /// + /// + /// git status reads a sparse index without expanding it, and it compares the + /// content of a file whose stat data changed, so a file that has the content of HEAD + /// again is not listed. --no-optional-locks stops Git from writing the refreshed + /// index, so this does not need the GVFS lock. --no-deserialize stops Git from + /// reading the GVFS status cache. The virtual file system stays on, so Git checks only + /// the paths that the mount reports, and it looks for untracked files only there. + /// COMMAND_HOOK_LOCK makes Git skip the pre-command and post-command hooks. + /// + public Result ListPathsThatDifferFromHead(Action onPath, int timeoutMs) + { + ArgumentNullException.ThrowIfNull(onPath); + + return this.InvokeGitImpl( + "--no-optional-locks status --porcelain=v2 -z --untracked-files=normal --no-renames --ignore-submodules=all --no-deserialize", + workingDirectory: this.workingDirectoryRoot, + dotGitDirectory: null, + useReadObjectHook: true, + writeStdIn: null, + parseStdOutLine: null, + timeoutMs: timeoutMs, + usePreCommandHook: false, + parseStdOutToken: record => + { + string path = GetPorcelainV2Path(record); + if (path != null) + { + onPath(path); + } + }); + } + + /// Run git version --build-options. + public Result VersionBuildOptions() + { + return this.InvokeGitOutsideEnlistment("version --build-options"); + } + + /// + /// Return true when the output of git version --build-options has a line that is + /// exactly , apart from white space at the ends. + /// + internal static bool HasBuildOption(string buildOptionsOutput, string option) + { + if (buildOptionsOutput == null) + { + return false; + } + + foreach (string line in buildOptionsOutput.Split('\n')) + { + if (string.Equals(line.Trim(), option, StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } + + /// + /// Return the path of a git status --porcelain=v2 -z record for a changed, + /// unmerged, or untracked entry, or null for any other record. The path of an untracked + /// folder ends with '/'. + /// + internal static string GetPorcelainV2Path(string record) + { + // "1 XY sub mH mI mW hH hI path", "u XY sub m1 m2 m3 mW h1 h2 h3 path", and + // "? path". The path is the rest of the record, so it can contain spaces. + int pathField; + if (record.StartsWith("1 ", StringComparison.Ordinal)) + { + pathField = 8; + } + else if (record.StartsWith("u ", StringComparison.Ordinal)) + { + pathField = 10; + } + else if (record.StartsWith("? ", StringComparison.Ordinal)) + { + pathField = 1; + } + else + { + return null; + } + + string[] fields = record.Split(' ', pathField + 1); + return fields.Length == pathField + 1 && fields[pathField].Length > 0 ? fields[pathField] : null; + } + public Result Status(bool allowObjectDownloads, bool useStatusCache, bool showUntracked = false) { string command = "status"; diff --git a/GVFS/GVFS.Common/Git/GitRepo.cs b/GVFS/GVFS.Common/Git/GitRepo.cs index 1d74c911a..29029e717 100644 --- a/GVFS/GVFS.Common/Git/GitRepo.cs +++ b/GVFS/GVFS.Common/Git/GitRepo.cs @@ -216,6 +216,39 @@ public virtual bool TryGetConfigValue(string name, out string value) return this.libgit2RepoInvoker.TryInvoke(repo => repo.GetConfigString(name), out value); } + /// + /// Reads a boolean git config value through the in-process libgit2 repo (no git.exe spawn). + /// + /// + /// The config value, or if the setting is unset or no + /// libgit2 repo is available. + /// + public virtual bool GetConfigBoolOrDefault(string name, bool defaultValue) + { + if (this.libgit2RepoInvoker == null) + { + return defaultValue; + } + + return this.libgit2RepoInvoker.GetConfigBoolOrDefault(name, defaultValue); + } + + /// + /// Reads the entries of a tree object from the local object store. Does not download objects. + /// + /// The 20-byte object id of the tree + /// Receives each entry, in tree order. The spans are valid only during the call. + public virtual TreeEnumerationResult TryEnumerateTree(byte[] treeId, TreeEntryVisitor visitor) + { + if (this.libgit2RepoInvoker == null || + !this.libgit2RepoInvoker.TryInvoke(repo => repo.EnumerateTree(treeId, visitor), out TreeEnumerationResult result)) + { + return TreeEnumerationResult.RepositoryUnavailable; + } + + return result; + } + public void Dispose() { if (this.libgit2RepoInvoker != null) diff --git a/GVFS/GVFS.Common/Git/LibGit2Repo.cs b/GVFS/GVFS.Common/Git/LibGit2Repo.cs index 06c703e86..c1429472c 100644 --- a/GVFS/GVFS.Common/Git/LibGit2Repo.cs +++ b/GVFS/GVFS.Common/Git/LibGit2Repo.cs @@ -28,6 +28,8 @@ namespace GVFS.Common.Git /// public class LibGit2Repo : IDisposable { + private const int GitOidLength = 20; + // git.exe reads config from these variables, or uses them to select config files. // libgit2 does not. // @@ -338,6 +340,80 @@ public virtual string[] GetMissingSubTrees(string treeSha) return missingSubtreesList.ToArray(); } + /// + /// Reads the entries of a tree object from the local object store, and calls + /// once for each entry, in tree order. Does not download objects. + /// + /// The 20-byte object id of the tree + /// Receives each entry. The spans are valid only during the call. + public virtual unsafe TreeEnumerationResult EnumerateTree(byte[] treeId, TreeEntryVisitor visitor) + { + if (treeId == null || treeId.Length != GitOidLength) + { + throw new ArgumentException($"A tree id must have {GitOidLength} bytes", nameof(treeId)); + } + + GitOid oid = new GitOid { Id = treeId }; + Native.ResultCode lookupResult = Native.Object.Lookup(out IntPtr treeHandle, this.RepoHandle, ref oid, Native.Object.AnyType); + if (lookupResult == Native.ResultCode.NotFound) + { + return TreeEnumerationResult.MissingTree; + } + + if (lookupResult != Native.ResultCode.Success || treeHandle == IntPtr.Zero) + { + EventMetadata metadata = new EventMetadata(); + metadata.Add("TreeSha", oid.ToString()); + metadata.Add("ResultCode", (int)lookupResult); + metadata.Add("NativeError", this.GetLastNativeError()); + this.Tracer?.RelatedWarning(metadata, $"{nameof(this.EnumerateTree)}: git_object_lookup failed"); + return TreeEnumerationResult.CorruptTree; + } + + try + { + if (Native.Object.GetType(treeHandle) != Native.ObjectTypes.Tree) + { + return TreeEnumerationResult.NotTree; + } + + uint entryCount = Native.Tree.GetEntryCount(treeHandle); + for (uint i = 0; i < entryCount; i++) + { + // The entry, its name, and its id belong to the tree. Do not free them. + IntPtr entryHandle = Native.Tree.GetEntryByIndex(treeHandle, i); + if (entryHandle == IntPtr.Zero) + { + return TreeEnumerationResult.CorruptTree; + } + + byte* name = Native.Tree.GetEntryName(entryHandle); + IntPtr entryId = Native.Tree.GetEntryId(entryHandle); + if (name == null || entryId == IntPtr.Zero) + { + return TreeEnumerationResult.CorruptTree; + } + + int nameLength = 0; + while (name[nameLength] != 0) + { + nameLength++; + } + + visitor( + new ReadOnlySpan(name, nameLength), + new ReadOnlySpan((byte*)entryId, GitOidLength), + Native.Tree.GetEntryFileMode(entryHandle)); + } + } + finally + { + Native.Object.Free(treeHandle); + } + + return TreeEnumerationResult.Success; + } + /// /// Get a config value from the repo's git config. /// @@ -1267,6 +1343,12 @@ private static string MarshalUtf8String(IntPtr ptr) public static class Object { + // GIT_OBJECT_ANY: git_object_lookup returns an object of any type. + public const int AnyType = -2; + + [DllImport(Git2NativeLibName, EntryPoint = "git_object_lookup")] + public static extern ResultCode Lookup(out IntPtr objectHandle, IntPtr repoHandle, ref GitOid id, int type); + [DllImport(Git2NativeLibName, EntryPoint = "git_object_type")] public static extern ObjectTypes GetType(IntPtr objectHandle); @@ -1302,6 +1384,11 @@ public static class Tree [DllImport(Git2NativeLibName, EntryPoint = "git_tree_entry_id")] public static extern IntPtr GetEntryId(IntPtr entryHandle); + // Returns a borrowed, NUL-terminated UTF-8 name that the tree owns. It is read as raw + // bytes, so the marshaller does not copy or free it. + [DllImport(Git2NativeLibName, EntryPoint = "git_tree_entry_name")] + public static unsafe extern byte* GetEntryName(IntPtr entryHandle); + /* git_tree_entry_type requires the object to exist, so we can't use it to check if * a missing entry is a tree. Instead, we can use the file mode to determine if it is a tree. */ [DllImport(Git2NativeLibName, EntryPoint = "git_tree_entry_filemode")] diff --git a/GVFS/GVFS.Common/Git/TreeEnumeration.cs b/GVFS/GVFS.Common/Git/TreeEnumeration.cs new file mode 100644 index 000000000..189e1199c --- /dev/null +++ b/GVFS/GVFS.Common/Git/TreeEnumeration.cs @@ -0,0 +1,49 @@ +using System; + +namespace GVFS.Common.Git +{ + /// + /// The result of an attempt to read the entries of a tree object from the local object store. + /// + public enum TreeEnumerationResult + { + /// + /// The object is a tree. The visitor received every entry, in tree order. + /// + Success, + + /// + /// The object is not in the local object store. The visitor received no entries. + /// A download can make the object available. + /// + MissingTree, + + /// + /// The object is in the local object store, but it is not a tree. The visitor received no entries. + /// + NotTree, + + /// + /// The object is in the local object store, but it cannot be read. The visitor can have + /// received some entries before the failure. The caller must discard them. + /// + CorruptTree, + + /// + /// The repository is not available, for example because it is shutting down. + /// The visitor received no entries. + /// + RepositoryUnavailable, + } + + /// + /// Receives one entry of a tree object. + /// + /// The UTF-8 name of the entry. It is valid only during the call. + /// The 20-byte object id of the entry. It is valid only during the call. + /// + /// The git file mode of the entry, for example 0100644 (file), 0100755 (executable), + /// 0120000 (symbolic link), 0160000 (gitlink), or 040000 (tree). + /// + public delegate void TreeEntryVisitor(ReadOnlySpan name, ReadOnlySpan objectId, uint fileMode); +} diff --git a/GVFS/GVFS.Common/GitPathspecParser.cs b/GVFS/GVFS.Common/GitPathspecParser.cs new file mode 100644 index 000000000..d0fc3aded --- /dev/null +++ b/GVFS/GVFS.Common/GitPathspecParser.cs @@ -0,0 +1,601 @@ +using System; +using System.Collections.Generic; + +namespace GVFS.Common +{ + /// + /// General-purpose parser for a Git command line as seen by the GVFS + /// pre/post-command hooks. Its job is to extract the set of working-tree + /// paths (pathspecs) that a command names, so the mount process can widen + /// the sparse-index cone to cover them before Git runs. + /// + /// + /// + /// This is distinct from , which classifies + /// a whole command string into coarse verbs for the virtualization layer. + /// This parser instead extracts pathspecs from the argv the hooks receive. + /// + /// + /// The hook args array has the shape produced by the GVFS git-hooks loader + /// plus Git itself: + /// [hookType, gitCommand, arg0, arg1, ..., --git-pid=<pid>[, --exit_code=<n>]]. + /// + /// + /// Git strips its global options (-C, -c, --git-dir, + /// --work-tree, ...) in handle_options() before it dispatches + /// the builtin, so run_pre_command_hook() receives an argv that + /// starts at the command name. In normal operation the hook therefore never + /// sees global options. This parser still recognizes a leading run of global + /// options so that it is a correct general Git command-line parser (and so + /// callers that construct a full command line are handled), but that path is + /// defensive: the common case consumes zero global options. + /// + /// + /// Extraction never has to be exact. A missed pathspec only means that Git + /// expands the sparse index in memory to resolve the path, which is slower + /// but correct. An over-broad pathspec only makes the cone wider than + /// necessary. Both error directions are benign, so ambiguous positional + /// arguments are classified conservatively rather than perfectly. + /// + /// + public static class GitPathspecParser + { + internal const string GitPidArgPrefix = "--git-pid="; + private const string ExitCodeArgPrefix = "--exit_code="; + private const string PathspecFromFileArg = "--pathspec-from-file"; + private const string PathspecFromFileEqualsArg = "--pathspec-from-file="; + private const string PathspecFileNulArg = "--pathspec-file-nul"; + private const string DashDash = "--"; + private const string EndOfOptions = "--end-of-options"; + + // Global (pre-command) long options that consume a following token as + // their value. Matches git.c handle_options(). The "=value" form of any + // of these is self-contained and needs no special handling. + private static readonly HashSet GlobalLongOptionsWithValue = new HashSet(StringComparer.Ordinal) + { + "--git-dir", + "--work-tree", + "--namespace", + "--super-prefix", + "--config-env", + "--attr-source", + "-c", + }; + + private static readonly Dictionary CommandSpecs = BuildCommandSpecs(); + + private enum PositionalKind + { + /// Every positional argument is a pathspec (add, rm, mv, restore, commit). + Pathspec, + + /// The first positionals are refs; the rest are pathspecs (checkout, reset). + LeadingRefsThenPathspec, + + /// No positional before "--" is a pathspec; only "-- <paths>" count (diff, log, show, grep, blame, and unknown commands). + RefsOnly, + + /// The command takes no pathspecs at all (switch). + None, + + /// The first positional is a stash subcommand; pathspecs follow only for push/save. + StashSubcommand, + } + + /// + /// Parses a hook args array and returns the pathspecs the command names. + /// + /// + /// The full hook argument array, where hookArgs[0] is the hook + /// type and hookArgs[1] is normally the Git command. + /// + public static ParsedGitCommand ParseHookArgs(string[] hookArgs) + { + if (hookArgs == null || hookArgs.Length < 2) + { + return ParsedGitCommand.Empty; + } + + // hookArgs[0] is the hook type (pre-command / post-command). + return ParseTokens(hookArgs, startIndex: 1); + } + + /// + /// Parses a token list starting at , which + /// must point at the leading global options or the command name. + /// + private static ParsedGitCommand ParseTokens(IReadOnlyList tokens, int startIndex) + { + string changeDirectory = null; + string gitDir = null; + string workTree = null; + + int index = startIndex; + + // Phase 1: consume a leading run of Git global options. In the normal + // hook case there are none and this loop exits immediately with the + // command at the first token. + while (index < tokens.Count) + { + string token = tokens[index]; + + if (IsInjectedArg(token)) + { + index++; + continue; + } + + if (!token.StartsWith("-", StringComparison.Ordinal) || token == DashDash) + { + // First non-option token is the command name. + break; + } + + index++; + + if (TrySplitEquals(token, out string name, out string value)) + { + RecordGlobal(name, value, ref changeDirectory, ref gitDir, ref workTree); + continue; + } + + if (token == "-C") + { + if (index < tokens.Count) + { + changeDirectory = tokens[index++]; + } + + continue; + } + + if (GlobalLongOptionsWithValue.Contains(token)) + { + if (index < tokens.Count) + { + string globalValue = tokens[index++]; + RecordGlobal(token, globalValue, ref changeDirectory, ref gitDir, ref workTree); + } + + continue; + } + + // Boolean global option (or an unrecognized one) — nothing to consume. + } + + if (index >= tokens.Count) + { + return new ParsedGitCommand(null, null, null, false, false, changeDirectory, gitDir, workTree); + } + + string command = NormalizeCommand(tokens[index]); + index++; + + GitCommandSpec spec = GetSpec(command); + return ParseCommandArgs(tokens, index, command, spec, changeDirectory, gitDir, workTree); + } + + private static ParsedGitCommand ParseCommandArgs( + IReadOnlyList tokens, + int startIndex, + string command, + GitCommandSpec spec, + string changeDirectory, + string gitDir, + string workTree) + { + List pathspecs = new List(); + string pathspecFromFile = null; + bool pathspecFileNul = false; + + bool pastDashDash = false; + bool pastEndOfOptions = false; + bool captureNextAsPathspecFile = false; + bool skipNextAsValue = false; + int positionalIndex = 0; + bool stashTakesPaths = false; + + // Some flags remove the command's leading ref operand, so every + // positional becomes a pathspec. The canonical case is conflict + // resolution: "git checkout --ours " / "--theirs " and + // "git checkout -p " name a working-tree path with no ref, yet + // the default checkout grammar would misread that first positional as + // a branch. Detect these up front so classification uses the right + // leading-ref count regardless of token order. + int leadingRefCount = spec.LeadingRefCount; + if (leadingRefCount > 0 && HasRefSuppressingFlag(tokens, startIndex, spec)) + { + leadingRefCount = 0; + } + + for (int i = startIndex; i < tokens.Count; i++) + { + string token = tokens[i]; + + if (captureNextAsPathspecFile) + { + pathspecFromFile = token; + captureNextAsPathspecFile = false; + continue; + } + + if (skipNextAsValue) + { + skipNextAsValue = false; + continue; + } + + // Git appends --git-pid / --exit_code after all user arguments, + // so filter them even past "--". + if (IsInjectedArg(token)) + { + continue; + } + + if (!pastDashDash) + { + if (token == DashDash) + { + pastDashDash = true; + continue; + } + + if (pastEndOfOptions) + { + // After --end-of-options, a token that starts with "-" is a + // positional argument (for example a ref named "-topic"), + // but "--" still separates the refs from the pathspecs. + ClassifyPositional(spec, leadingRefCount, token, positionalIndex, pathspecs, ref stashTakesPaths); + positionalIndex++; + continue; + } + + if (token == EndOfOptions) + { + pastEndOfOptions = true; + continue; + } + + if (token.StartsWith(PathspecFromFileEqualsArg, StringComparison.Ordinal)) + { + pathspecFromFile = token.Substring(PathspecFromFileEqualsArg.Length); + continue; + } + + if (token == PathspecFromFileArg) + { + captureNextAsPathspecFile = true; + continue; + } + + if (token == PathspecFileNulArg) + { + pathspecFileNul = true; + continue; + } + + if (token.StartsWith("--", StringComparison.Ordinal)) + { + // Long option. The "=value" form is self-contained; the + // bare form consumes a following token only when this + // command declares the option as value-taking. + if (token.IndexOf('=') < 0 && spec.LongOptionsWithValue.Contains(token)) + { + skipNextAsValue = true; + } + + continue; + } + + if (token.Length > 1 && token[0] == '-') + { + // Short option cluster, possibly combined (e.g. "-am"). + // A value-taking letter that is the last character + // consumes the following token; otherwise the remainder + // of the cluster is its baked-in value. + if (ShortClusterConsumesNextArg(token, spec.ShortOptionsWithValue)) + { + skipNextAsValue = true; + } + + continue; + } + + ClassifyPositional(spec, leadingRefCount, token, positionalIndex, pathspecs, ref stashTakesPaths); + positionalIndex++; + } + else + { + // Everything after "--" is a literal pathspec, for commands + // that take pathspecs at all. + if (PathspecsEnabledPastSeparator(spec, stashTakesPaths)) + { + pathspecs.Add(token); + } + } + } + + bool failed = pathspecFromFile == "-"; + + return new ParsedGitCommand( + command, + pathspecs, + pathspecFromFile, + pathspecFileNul, + failed, + changeDirectory, + gitDir, + workTree); + } + + private static void ClassifyPositional( + GitCommandSpec spec, + int leadingRefCount, + string token, + int positionalIndex, + List pathspecs, + ref bool stashTakesPaths) + { + switch (spec.PositionalKind) + { + case PositionalKind.Pathspec: + pathspecs.Add(token); + break; + + case PositionalKind.LeadingRefsThenPathspec: + if (positionalIndex >= leadingRefCount) + { + pathspecs.Add(token); + } + + break; + + case PositionalKind.StashSubcommand: + if (positionalIndex == 0) + { + stashTakesPaths = + token.Equals("push", StringComparison.Ordinal) || + token.Equals("save", StringComparison.Ordinal); + } + else if (stashTakesPaths) + { + pathspecs.Add(token); + } + + break; + + case PositionalKind.RefsOnly: + case PositionalKind.None: + default: + break; + } + } + + private static bool PathspecsEnabledPastSeparator(GitCommandSpec spec, bool stashTakesPaths) + { + switch (spec.PositionalKind) + { + case PositionalKind.None: + return false; + case PositionalKind.StashSubcommand: + return stashTakesPaths; + default: + return true; + } + } + + private static bool ShortClusterConsumesNextArg(string token, HashSet shortOptionsWithValue) + { + // token[0] == '-'. Scan the cluster; the first value-taking letter + // determines the outcome. + for (int j = 1; j < token.Length; j++) + { + if (shortOptionsWithValue.Contains(token[j])) + { + // Last character: value is the following token. + // Otherwise: the rest of the cluster is a baked-in value. + return j == token.Length - 1; + } + } + + return false; + } + + /// + /// Returns true when any of the command's ref-suppressing flags appears + /// before a "--" separator. Such a flag means the command has no ref + /// operand, so every positional is a pathspec. + /// + private static bool HasRefSuppressingFlag(IReadOnlyList tokens, int startIndex, GitCommandSpec spec) + { + if (spec.RefSuppressingFlags.Count == 0) + { + return false; + } + + for (int i = startIndex; i < tokens.Count; i++) + { + string token = tokens[i]; + + if (token == DashDash || token == EndOfOptions) + { + // Past "--" or "--end-of-options" a matching token is a + // positional argument, not a flag. + break; + } + + if (IsInjectedArg(token)) + { + continue; + } + + if (spec.RefSuppressingFlags.Contains(token)) + { + return true; + } + } + + return false; + } + + private static bool IsInjectedArg(string token) + { + return token.StartsWith(GitPidArgPrefix, StringComparison.Ordinal) + || token.StartsWith(ExitCodeArgPrefix, StringComparison.Ordinal); + } + + private static bool TrySplitEquals(string token, out string name, out string value) + { + int equalsIndex = token.IndexOf('='); + if (equalsIndex < 0) + { + name = null; + value = null; + return false; + } + + name = token.Substring(0, equalsIndex); + value = token.Substring(equalsIndex + 1); + return true; + } + + private static void RecordGlobal( + string name, + string value, + ref string changeDirectory, + ref string gitDir, + ref string workTree) + { + switch (name) + { + case "-C": + changeDirectory = value; + break; + case "--git-dir": + gitDir = value; + break; + case "--work-tree": + workTree = value; + break; + } + } + + private static string NormalizeCommand(string command) + { + string normalized = command.ToLowerInvariant(); + if (normalized.StartsWith("git-", StringComparison.Ordinal)) + { + normalized = normalized.Substring(4); + } + + return normalized; + } + + private static GitCommandSpec GetSpec(string command) + { + if (CommandSpecs.TryGetValue(command, out GitCommandSpec spec)) + { + return spec; + } + + // Unknown command: trust only an explicit "--" pathspec separator. + return GitCommandSpec.RefsOnlyDefault; + } + + private static Dictionary BuildCommandSpecs() + { + Dictionary specs = new Dictionary(StringComparer.Ordinal); + + GitCommandSpec pathspecPositional = new GitCommandSpec(PositionalKind.Pathspec); + specs["add"] = pathspecPositional; + specs["stage"] = pathspecPositional; + specs["rm"] = new GitCommandSpec(PositionalKind.Pathspec); + specs["mv"] = new GitCommandSpec(PositionalKind.Pathspec); + + specs["restore"] = new GitCommandSpec( + PositionalKind.Pathspec, + longOptionsWithValue: new[] { "--source", "--conflict" }, + shortOptionsWithValue: new[] { 's' }); + + specs["commit"] = new GitCommandSpec( + PositionalKind.Pathspec, + longOptionsWithValue: new[] + { + "--message", "--author", "--date", "--reuse-message", "--reedit-message", + "--fixup", "--squash", "--file", "--template", "--cleanup", "--trailer", + }, + shortOptionsWithValue: new[] { 'm', 'C', 'c', 'F', 't' }); + + specs["checkout"] = new GitCommandSpec( + PositionalKind.LeadingRefsThenPathspec, + leadingRefCount: 1, + longOptionsWithValue: new[] { "--conflict", "--orphan" }, + shortOptionsWithValue: new[] { 'b', 'B' }, + refSuppressingFlags: new[] { "--ours", "--theirs", "--patch", "-p" }); + + specs["switch"] = new GitCommandSpec( + PositionalKind.None, + longOptionsWithValue: new[] { "--orphan" }, + shortOptionsWithValue: new[] { 'c', 'C' }); + + specs["reset"] = new GitCommandSpec( + PositionalKind.LeadingRefsThenPathspec, + leadingRefCount: 1); + + specs["stash"] = new GitCommandSpec( + PositionalKind.StashSubcommand, + longOptionsWithValue: new[] { "--message" }, + shortOptionsWithValue: new[] { 'm' }); + + // Commands whose paths are only unambiguous after "--". + specs["diff"] = GitCommandSpec.RefsOnlyDefault; + specs["log"] = GitCommandSpec.RefsOnlyDefault; + specs["show"] = GitCommandSpec.RefsOnlyDefault; + specs["grep"] = GitCommandSpec.RefsOnlyDefault; + specs["blame"] = GitCommandSpec.RefsOnlyDefault; + + return specs; + } + + /// + /// Immutable per-command grammar description used by the parser. + /// + private sealed class GitCommandSpec + { + private static readonly HashSet EmptyLongOptions = new HashSet(StringComparer.Ordinal); + private static readonly HashSet EmptyShortOptions = new HashSet(); + + public static readonly GitCommandSpec RefsOnlyDefault = new GitCommandSpec(PositionalKind.RefsOnly); + + public GitCommandSpec( + PositionalKind positionalKind, + int leadingRefCount = 0, + IEnumerable longOptionsWithValue = null, + IEnumerable shortOptionsWithValue = null, + IEnumerable refSuppressingFlags = null) + { + this.PositionalKind = positionalKind; + this.LeadingRefCount = leadingRefCount; + this.LongOptionsWithValue = longOptionsWithValue == null + ? EmptyLongOptions + : new HashSet(longOptionsWithValue, StringComparer.Ordinal); + this.ShortOptionsWithValue = shortOptionsWithValue == null + ? EmptyShortOptions + : new HashSet(shortOptionsWithValue); + this.RefSuppressingFlags = refSuppressingFlags == null + ? EmptyLongOptions + : new HashSet(refSuppressingFlags, StringComparer.Ordinal); + } + + public PositionalKind PositionalKind { get; } + + public int LeadingRefCount { get; } + + public HashSet LongOptionsWithValue { get; } + + public HashSet ShortOptionsWithValue { get; } + + public HashSet RefSuppressingFlags { get; } + } + } +} diff --git a/GVFS/GVFS.Common/GitStatusCache.cs b/GVFS/GVFS.Common/GitStatusCache.cs index 3ac34f287..a48cfe96f 100644 --- a/GVFS/GVFS.Common/GitStatusCache.cs +++ b/GVFS/GVFS.Common/GitStatusCache.cs @@ -58,6 +58,7 @@ public class GitStatusCache : IDisposable private readonly Lock hydrationStatisticsLock = new Lock(); private Func projectedFolderCountProvider; + private Func projectedFileCountProvider; private Func> modifiedPathsProvider; private volatile CacheState cacheState = CacheState.Dirty; @@ -99,6 +100,15 @@ public void SetProjectedFolderCountProvider(Func provider) this.projectedFolderCountProvider = provider; } + /// + /// Sets the provider of the projected file count for the hydration summary. The provider + /// returns -1 when the index entry count is the file count (a full index). + /// + public void SetProjectedFileCountProvider(Func provider) + { + this.projectedFileCountProvider = provider; + } + public void SetModifiedPathsProvider(Func> provider) { ArgumentNullException.ThrowIfNull(provider); @@ -566,7 +576,8 @@ internal virtual HydrationStatusCircuitBreaker CreateHydrationCircuitBreaker() internal virtual EnlistmentHydrationSummary CreateHydrationSummary(HydrationSummaryDiagnostics diagnostics) { return EnlistmentHydrationSummary.CreateSummary(this.context.Enlistment, this.context.FileSystem, this.context.Tracer, - this.projectedFolderCountProvider, new EnlistmentPathData(this.modifiedPathsProvider), this.shutdownTokenSource.Token, diagnostics); + this.projectedFolderCountProvider, new EnlistmentPathData(this.modifiedPathsProvider), this.shutdownTokenSource.Token, diagnostics, + this.projectedFileCountProvider); } private void RecordHydrationSkip(NamedPipeMessages.HydrationStatus.CacheState state) diff --git a/GVFS/GVFS.Common/HealthCalculator/EnlistmentHydrationSummary.cs b/GVFS/GVFS.Common/HealthCalculator/EnlistmentHydrationSummary.cs index 5d3ea16ea..5c4c41e9d 100644 --- a/GVFS/GVFS.Common/HealthCalculator/EnlistmentHydrationSummary.cs +++ b/GVFS/GVFS.Common/HealthCalculator/EnlistmentHydrationSummary.cs @@ -65,7 +65,8 @@ internal static EnlistmentHydrationSummary CreateSummary( Func projectedFolderCountProvider, EnlistmentPathData pathData, CancellationToken cancellationToken = default, - HydrationSummaryDiagnostics diagnostics = null) + HydrationSummaryDiagnostics diagnostics = null, + Func projectedFileCountProvider = null) { diagnostics = diagnostics ?? new HydrationSummaryDiagnostics(); EnlistmentHydrationSummary summary = new EnlistmentHydrationSummary { Diagnostics = diagnostics }; @@ -74,6 +75,15 @@ internal static EnlistmentHydrationSummary CreateSummary( { diagnostics.StartPhase(HydrationSummaryPhase.IndexRead); summary.TotalFileCount = GetIndexFileCount(enlistment, fileSystem, diagnostics); + + // A sparse index has one entry for each collapsed folder. The projection then + // knows the file count, and the index header does not. + int projectedFileCount = summary.TotalFileCount >= 0 && projectedFileCountProvider != null ? projectedFileCountProvider() : -1; + if (projectedFileCount >= 0) + { + summary.TotalFileCount = projectedFileCount; + } + diagnostics.TotalFileCount = summary.TotalFileCount >= 0 ? summary.TotalFileCount : null; diagnostics.FinishPhase(summary.TotalFileCount >= 0 ? HydrationDataState.Complete : HydrationDataState.Failed); cancellationToken.ThrowIfCancellationRequested(); diff --git a/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs new file mode 100644 index 000000000..2a233ccac --- /dev/null +++ b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs @@ -0,0 +1,281 @@ +using GVFS.Common.Sparse; +using System.Collections.Generic; + +namespace GVFS.Common.NamedPipes +{ + public static partial class NamedPipeMessages + { + /// + /// Messages for automatic sparse-index cone management. + /// + /// + /// The pre-command hook sends a before Git runs, so that the + /// mount can widen the sparse-index cone to cover the paths that the Git command names. + /// The post-command hook sends a with the same + /// CommandId after Git runs, so that the mount can remove the cone entries that + /// it added for that command. + /// + /// The hook treats every reply other than as "not applied" + /// and lets Git run. This includes and + /// , from an older mount that + /// does not handle these messages, , no reply within the + /// wait budget, and no mount. Git then expands the sparse index in memory. + /// + /// + /// A widen request carries only repo-relative git-form paths that the hook resolved + /// (see ). It carries no absolute path + /// and no file for the mount to read. Any local user can write to the mount pipe, so + /// rejects a body with any other path. + /// + /// + /// The mount owns the lifetime of the entries that it adds. A narrow can be missing + /// (the Git process was killed) or late (it timed out). Commands that do not take the + /// GVFS lock (for example git diff -- <path>) also send widen requests. The + /// mount applies a widen only for the Git process that holds the GVFS lock (see + /// AutoSparseIndexConeManager). The command id is the Git process id, so the mount + /// can count the commands that need an entry and remove the entries of a process that + /// no longer runs. + /// + /// + /// When a working-tree change needs a cone change that the index does not have yet, + /// the mount creates the file. The + /// pre-command hook then sends an before Git reads the index, + /// also for a command that names no paths. The requesting Git process must hold the + /// GVFS lock, as for a widen. + /// + /// + /// A body is a list of fields separated by NUL. The header and the body split on the + /// first '|' only, so a field can contain '|'. + /// + /// + public static class ConeManagement + { + public const string WidenRequest = "ConeWiden"; + public const string NarrowRequest = "ConeNarrow"; + public const string ApplyRequest = "ConeApply"; + + /// The mount applied the request. + public const string SuccessResult = "S"; + + /// The mount tried to apply the request and failed. + public const string FailureResult = "F"; + + /// The mount received the request, but automatic sparse index is not enabled. + public const string NotEnabledResult = "NE"; + + /// + /// The time that the pre-command hook allows to connect and send a widen request. If + /// the hook cannot send the request in this time, it lets Git run, and it does not + /// send the request. + /// + public const int WidenWaitBudgetMs = 1000; + + /// + /// The maximum time that the pre-command hook waits for the reply after it sent a + /// widen request. To apply a widen, the mount runs Git, which holds the index lock. + /// If the hook let Git run first, Git could fail because the index lock exists. Thus + /// the hook waits for the reply. The ceiling is far above the measured time of a + /// widen on a large repository (about 1.3 seconds at most, including the wait for + /// earlier requests), and it stops a mount that does not reply from blocking Git + /// without limit. + /// + public const int WidenReplyCeilingMs = 10000; + + /// + /// The time in which the mount applies a pending working-tree change. A slower apply + /// is a warning, and an apply that waited half of this time for earlier requests does + /// not run Git. The hook waits for the apply reply up to + /// , for the same reason as for a widen. + /// + public const int ApplyWaitBudgetMs = 5000; + + /// + /// The maximum time that the post-command hook waits for a narrow reply. Git has + /// already run, so this wait only delays the return to the user. + /// + public const int NarrowWaitBudgetMs = 100; + + /// + /// The maximum time that the hook waits to connect to the mount pipe. A live mount + /// accepts the connection quickly. Without a mount, the connect fails at this limit. + /// + public const int ConnectTimeoutMs = 50; + + private const char FieldSeparator = '\0'; + + /// + /// Return true when a command id is empty or has 1 to 10 ASCII digits (a Windows + /// process id fits in 10 digits). + /// + public static bool IsValidCommandId(string commandId) + { + if (commandId == null || commandId.Length > 10) + { + return false; + } + + foreach (char character in commandId) + { + if (character < '0' || character > '9') + { + return false; + } + } + + return true; + } + + /// + /// Parameters for a widen request: the Git command id and the repo-relative + /// git-form paths to cover. A path with a trailing slash is a folder, and the mount + /// covers its whole subtree. Any other path is a file, and the mount covers the + /// files in its parent directory. + /// + public class WidenParameters + { + public WidenParameters(string commandId, IReadOnlyList paths) + { + this.CommandId = commandId ?? string.Empty; + this.Paths = paths ?? new List(); + } + + /// + /// Identifies the Git command: the Git process id, as decimal digits, or empty. + /// The pre-command and post-command hooks of one Git command send the same value. + /// + public string CommandId { get; } + + /// The repo-relative git-form paths to cover. + public IReadOnlyList Paths { get; } + + /// + /// Return true when the command id is valid and there is at least one path, + /// and every path is valid. + /// + public bool IsValid() + { + if (!IsValidCommandId(this.CommandId) || this.Paths.Count == 0) + { + return false; + } + + foreach (string path in this.Paths) + { + if (!ConePathspecResolver.IsValidGitPath(path)) + { + return false; + } + } + + return true; + } + + public string ToBody() + { + List fields = new List(1 + this.Paths.Count) { this.CommandId }; + fields.AddRange(this.Paths); + return string.Join(FieldSeparator.ToString(), fields); + } + + /// + /// Parse a widen body. Return false when the body is not valid (see + /// ). + /// + public static bool TryParse(string body, out WidenParameters parameters) + { + parameters = null; + if (body == null) + { + return false; + } + + string[] fields = body.Split(FieldSeparator); + List paths = new List(fields.Length - 1); + for (int i = 1; i < fields.Length; i++) + { + paths.Add(fields[i]); + } + + WidenParameters candidate = new WidenParameters(fields[0], paths); + if (!candidate.IsValid()) + { + return false; + } + + parameters = candidate; + return true; + } + } + + /// + /// Parameters for a narrow request: the command id of the Git command whose widen + /// the mount removes. + /// + public class NarrowParameters + { + public NarrowParameters(string commandId) + { + this.CommandId = commandId ?? string.Empty; + } + + /// The Git process id, as decimal digits, or empty. + public string CommandId { get; } + + public string ToBody() + { + return this.CommandId; + } + + /// + /// Parse a narrow body. Return false when the command id is not valid. + /// + public static bool TryParse(string body, out NarrowParameters parameters) + { + parameters = null; + if (!IsValidCommandId(body)) + { + return false; + } + + parameters = new NarrowParameters(body); + return true; + } + } + + /// + /// Parameters for an apply request: the command id of the Git command that holds the + /// GVFS lock and waits for the mount to apply the pending cone change. + /// + public class ApplyParameters + { + public ApplyParameters(string commandId) + { + this.CommandId = commandId ?? string.Empty; + } + + /// The Git process id, as decimal digits, or empty. + public string CommandId { get; } + + public string ToBody() + { + return this.CommandId; + } + + /// + /// Parse an apply body. Return false when the command id is not valid. + /// + public static bool TryParse(string body, out ApplyParameters parameters) + { + parameters = null; + if (!IsValidCommandId(body)) + { + return false; + } + + parameters = new ApplyParameters(body); + return true; + } + } + } + } +} diff --git a/GVFS/GVFS.Common/ParsedGitCommand.cs b/GVFS/GVFS.Common/ParsedGitCommand.cs new file mode 100644 index 000000000..98b54688e --- /dev/null +++ b/GVFS/GVFS.Common/ParsedGitCommand.cs @@ -0,0 +1,78 @@ +using System.Collections.Generic; + +namespace GVFS.Common +{ + /// + /// The result of parsing a Git command line for the working-tree paths it + /// names. Produced by . + /// + public class ParsedGitCommand + { + private static readonly IReadOnlyList NoPathspecs = new List(); + + public ParsedGitCommand( + string command, + IReadOnlyList pathspecs, + string pathspecFromFile, + bool pathspecFileNul, + bool failed, + string changeDirectory, + string gitDir, + string workTree) + { + this.Command = command; + this.Pathspecs = pathspecs ?? NoPathspecs; + this.PathspecFromFile = pathspecFromFile; + this.PathspecFileNul = pathspecFileNul; + this.Failed = failed; + this.ChangeDirectory = changeDirectory; + this.GitDir = gitDir; + this.WorkTree = workTree; + } + + /// An empty result, returned when there is nothing to parse. + public static ParsedGitCommand Empty { get; } = + new ParsedGitCommand(null, NoPathspecs, null, false, false, null, null, null); + + /// The Git command (verb), lowercased and with any "git-" prefix removed. Null when absent. + public string Command { get; } + + /// The literal pathspecs the command names, in command-line order. + public IReadOnlyList Pathspecs { get; } + + /// The argument of --pathspec-from-file, if present; "-" means stdin. Null when absent. + public string PathspecFromFile { get; } + + /// True when --pathspec-file-nul was present. + public bool PathspecFileNul { get; } + + /// + /// True when the command's pathspecs cannot be resolved from the command + /// line alone, e.g. --pathspec-from-file=- reads them from stdin. Callers + /// must not treat an empty pathspec set as authoritative when this is set. + /// + public bool Failed { get; } + + /// The -C value (global change-directory), if present. Null when absent. + public string ChangeDirectory { get; } + + /// The --git-dir value, if present. Null when absent. + public string GitDir { get; } + + /// The --work-tree value, if present. Null when absent. + public string WorkTree { get; } + + /// + /// True when the command names at least one path (inline, or via + /// --pathspec-from-file), and the pathspecs were resolvable. + /// + public bool NamesPaths + { + get + { + return !this.Failed && + (this.Pathspecs.Count > 0 || !string.IsNullOrEmpty(this.PathspecFromFile)); + } + } + } +} diff --git a/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs new file mode 100644 index 000000000..851767623 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs @@ -0,0 +1,1460 @@ +using GVFS.Common.FileSystem; +using GVFS.Common.Git; +using GVFS.Common.NamedPipes; +using GVFS.Common.Tracing; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace GVFS.Common.Sparse +{ + /// + /// Applies the cone widen and narrow requests that the Git hooks send to the mount when + /// gvfs.auto-sparse-index is true. + /// + /// + /// The cone is computed from the modified paths that can differ from HEAD, plus the changed + /// paths that the modified paths do not have yet, plus the transient paths of every Git + /// command that widened and did not narrow yet (see ). + /// When the last command narrows, the cone is again the cone of the modified paths. + /// + /// Widen: write the new cone file, then run + /// so that the index has entries for the new directories before Git runs. If Git fails, + /// restore the previous cone file. Only the Git command that holds the GVFS lock can + /// widen: it waits in its pre-command hook, so no other Git command writes the index. + /// Unless Git changes only the index when the cone changes + /// (), the cone does not + /// include the directory of a deleted file that a sparse-directory entry hides (see + /// ). + /// + /// + /// Narrow: write the new cone file only, after the post-command hook of a command that + /// widened, or after a background check (see below). The mount cannot replace the index then + /// (see ). The index keeps the expanded + /// entries until the next widen collapses each directory outside the cone whose entries + /// are all skip-worktree. + /// + /// + /// Locks: a process-internal lock serializes all requests. Then the manager takes the lock + /// file of Git's own sparse-checkout writers, writes the cone file, and runs the + /// child Git process, which takes the index lock. The manager does not take the GVFS lock, + /// because the requesting Git command holds it. The manager does not take the projection + /// lock. A cone change only changes how the index represents a directory, so the projection + /// does not change, and the manager does not invalidate it. + /// + /// + /// Every failure lets Git run, because the hook treats any reply other than success as + /// "not applied". Git then expands the index in memory, which is slower but correct. + /// + /// + /// Working-tree changes: Git sees a change to a file only when the index has an entry for + /// it, and git add takes a path only when the cone includes it. The file system + /// callbacks report every created, written, renamed, or deleted path, and the unstage + /// preparation reports every staged file that it adds to the modified paths (see + /// ). When the applied cone does not include the + /// path, the manager creates the pending file (see + /// ). The callback does not + /// wait for a Git command. The pre-command hook of the next Git command that reads the + /// index sees the file and sends an apply request while that command holds the GVFS lock. + /// The apply widens the cone like a widen without request paths. If the apply fails, the + /// change stays pending for the next Git command. + /// + /// + /// Clean paths: the cone includes a modified path only while the path can differ from HEAD. + /// After a Git command releases the GVFS lock, and when changes inside the applied cone stop + /// for , a background check (see + /// ) asks Git which paths differ from HEAD. A modified + /// file that matches HEAD, the index, and the working tree is clean, and the manager writes + /// a cone file without it. Git cannot collapse its directory while the file is a modified + /// path, because the virtual file system hook clears its skip-worktree bit, so the index + /// keeps its entry. The next change to the file makes it a candidate again. + /// + /// + public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver + { + /// A widen with more paths is refused, and Git expands the index in memory. + public const int MaxWidenPaths = 1000; + + /// + /// The git version --build-options line of a Git that supports a sparse index under + /// a virtual file system. Without it, sparse-checkout reapply leaves a full index + /// full. + /// + public const string SparseIndexFeature = "feature: vfs-sparse-index"; + + /// + /// After a change inside the applied cone, the manager waits until no change came for + /// this long, and then checks which modified files match HEAD again. + /// + public const int DefaultChangeCheckDelayMs = 2000; + + private const string WidenEventName = "ConeWiden"; + private const string NarrowEventName = "ConeNarrow"; + private const string ApplyEventName = "ConeApply"; + private const string ReconcileEventName = "ConeReconcile"; + private const int MaxTracedPaths = 10; + + // A widen that waited longer than this for earlier requests does not start Git. Git then + // expands the index in memory. This keeps a widen far inside the hook's reply ceiling + // (WidenReplyCeilingMs), after which Git runs while the child Git process can still + // hold the index lock. + private const int MaxQueueWaitBeforeApplyMs = NamedPipeMessages.ConeManagement.WidenWaitBudgetMs / 2; + + // A check that cannot write the cone file tries again after the change-check delay, at + // most this many times in a row. The next Git command that ends tries again too. + private const int MaxReconcileWriteRetries = 5; + + private static readonly IReadOnlyList NoPaths = new List(); + + private readonly ITracer tracer; + private readonly PhysicalFileSystem fileSystem; + private readonly ConeFileWriter coneFileWriter; + private readonly string sparseCheckoutPath; + private readonly bool ignoreCase; + private readonly IConeManagerEnvironment environment; + private readonly TransientConeState transientState = new TransientConeState(); + private readonly Lock coneLock = new Lock(); + private readonly Lock pendingLock = new Lock(); + private readonly Lock reconcileScheduleLock = new Lock(); + private readonly StringComparer pathComparer; + private readonly int changeCheckDelayMs; + private readonly Timer changeCheckTimer; + + // The working-tree paths that changed since an apply or a check last used them. + private readonly ConcurrentDictionary changedPaths; + + // True when the index can have sparse-directory entries that do not match the cone + // file: before the first widen of this mount, after a narrow, and after a failure. + private bool indexMayDifferFromCone = true; + + // True when the cone file can differ from the cone of the current state: before the + // first request of this mount, and after a failed narrow. The next request then + // writes the cone file even when no command entry changed. + private bool coneFileMayBeStale = true; + + // The deleted files and modified folders that the last widen found inside a + // sparse-directory entry. The cone leaves them out, so that a narrow does not put them + // in the cone file either. + private HashSet hiddenModifiedPaths = new HashSet(StringComparer.Ordinal); + + // The modified files that the last check found equal to HEAD, the index, and the working + // tree. The cone leaves them out. Guarded by coneLock. + private HashSet cleanPaths; + + // Changed paths that an apply used before the modified paths had them (see + // ConsumeChanges). The cone includes them. Guarded by coneLock. + private HashSet unconfirmedPaths; + + // The directories that the cone file includes and the index expands, or null when that + // is not known. + private AppliedConeSnapshot appliedCone; + + private long changeSequence; + private bool isPending; + + // Changes when an apply or a widen uses the changed paths, so that a check that started + // before it does not use its result. Guarded by coneLock. + private long consumeEpoch; + + // The state that the last check saw. A check with the same state does not run Git again. + private (long ChangeSequence, long ConsumeEpoch, long RepositoryStamp)? lastReconcileState; + + private bool reconcileRunning; + private bool reconcileRequested; + private int reconcileWriteRetries; + private volatile bool isStopped; + + public AutoSparseIndexConeManager( + ITracer tracer, + PhysicalFileSystem fileSystem, + string sparseCheckoutPath, + bool ignoreCase, + IConeManagerEnvironment environment, + int changeCheckDelayMs = DefaultChangeCheckDelayMs) + { + ArgumentNullException.ThrowIfNull(tracer); + ArgumentNullException.ThrowIfNull(fileSystem); + ArgumentNullException.ThrowIfNull(sparseCheckoutPath); + ArgumentNullException.ThrowIfNull(environment); + + this.tracer = tracer; + this.fileSystem = fileSystem; + this.coneFileWriter = new ConeFileWriter(fileSystem); + this.sparseCheckoutPath = sparseCheckoutPath; + this.ignoreCase = ignoreCase; + this.environment = environment; + this.pathComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + this.changedPaths = new ConcurrentDictionary(this.pathComparer); + this.cleanPaths = new HashSet(this.pathComparer); + this.unconfirmedPaths = new HashSet(this.pathComparer); + this.changeCheckDelayMs = changeCheckDelayMs; + this.changeCheckTimer = new Timer(_ => this.ScheduleReconcile(), state: null, Timeout.Infinite, Timeout.Infinite); + } + + private enum ConeChange + { + Applied, + ConeUnchanged, + Narrowed, + NothingToNarrow, + NoCommandId, + InvalidRequest, + TooManyPaths, + NotLockHolder, + CommandEnded, + CommandAlreadyNarrowed, + InvalidPath, + QueueWaitTooLong, + ExpandsModifiedPath, + SparseDirectoriesUnknown, + ConeFileLocked, + WriteFailed, + ApplyFailed, + UnexpectedException, + ConeChangePending, + NothingChanged, + StateChanged, + CleanPathChanged, + DiffFailed, + Stopped, + } + + /// + /// Return true when , the result of + /// git version --build-options for the Git that the mount runs, shows + /// . + /// + public static bool GitSupportsSparseIndex(GitProcess.Result buildOptions) + { + ArgumentNullException.ThrowIfNull(buildOptions); + return !buildOptions.ExitCodeIsFailure && GitProcess.HasBuildOption(buildOptions.Output, SparseIndexFeature); + } + + /// + /// Handle a , + /// , or + /// and return the reply. + /// + /// The cone manager, or null when the feature is off. + /// Traces a request that is not valid. + /// The request. + public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer tracer, NamedPipeMessages.Message message) + { + ArgumentNullException.ThrowIfNull(tracer); + ArgumentNullException.ThrowIfNull(message); + + if (manager == null) + { + return NamedPipeMessages.ConeManagement.NotEnabledResult; + } + + bool succeeded; + switch (message.Header) + { + case NamedPipeMessages.ConeManagement.WidenRequest: + if (!NamedPipeMessages.ConeManagement.WidenParameters.TryParse(message.Body, out NamedPipeMessages.ConeManagement.WidenParameters widen)) + { + TraceInvalidRequest(tracer, message.Header); + return NamedPipeMessages.ConeManagement.FailureResult; + } + + succeeded = manager.TryWiden(widen); + break; + + case NamedPipeMessages.ConeManagement.NarrowRequest: + if (!NamedPipeMessages.ConeManagement.NarrowParameters.TryParse(message.Body, out NamedPipeMessages.ConeManagement.NarrowParameters narrow)) + { + TraceInvalidRequest(tracer, message.Header); + return NamedPipeMessages.ConeManagement.FailureResult; + } + + succeeded = manager.TryNarrow(narrow); + break; + + case NamedPipeMessages.ConeManagement.ApplyRequest: + if (!NamedPipeMessages.ConeManagement.ApplyParameters.TryParse(message.Body, out NamedPipeMessages.ConeManagement.ApplyParameters apply)) + { + TraceInvalidRequest(tracer, message.Header); + return NamedPipeMessages.ConeManagement.FailureResult; + } + + succeeded = manager.TryApply(apply); + break; + + default: + throw new ArgumentException($"'{message.Header}' is not a cone request.", nameof(message)); + } + + return succeeded ? NamedPipeMessages.ConeManagement.SuccessResult : NamedPipeMessages.ConeManagement.FailureResult; + } + + /// + /// Add the paths of a Git command to the cone and update the index. The hook waits for + /// the result before Git runs. The cone also gets every pending working-tree change. + /// + /// True when the cone and the index include the paths. + public bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + + Stopwatch stopwatch = Stopwatch.StartNew(); + EventMetadata metadata = this.CreateMetadata(parameters.CommandId); + metadata.Add("PathCount", parameters.Paths.Count); + + ApplyAttempt attempt = new ApplyAttempt(); + ConeChange change = this.RunAndCatch(() => this.Widen(parameters, attempt, stopwatch, metadata), metadata); + this.RearmPendingAfterAttempt(attempt, change, requestHasPaths: true, metadata); + bool succeeded = change == ConeChange.Applied || change == ConeChange.ConeUnchanged; + + // A widen slower than WidenWaitBudgetMs is a warning. The hook waits for the reply up + // to WidenReplyCeilingMs, so the user's Git command waits for the widen. + this.TraceResult(WidenEventName, change, stopwatch.ElapsedMilliseconds, NamedPipeMessages.ConeManagement.WidenWaitBudgetMs, metadata); + return succeeded; + } + + /// + /// Apply the pending working-tree changes to the cone and the index before a Git command + /// reads the index. The hook waits for the result before Git runs. + /// + /// True when the cone and the index include every pending change. + public bool TryApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + + Stopwatch stopwatch = Stopwatch.StartNew(); + EventMetadata metadata = this.CreateMetadata(parameters.CommandId); + + ApplyAttempt attempt = new ApplyAttempt(); + ConeChange change = this.RunAndCatch( + () => TryGetProcessId(parameters.CommandId, out int processId) + ? this.ApplyCone(processId, NoPaths, NamedPipeMessages.ConeManagement.ApplyWaitBudgetMs / 2, attempt, stopwatch, metadata) + : ConeChange.NoCommandId, + metadata); + this.RearmPendingAfterAttempt(attempt, change, requestHasPaths: false, metadata); + bool succeeded = change == ConeChange.Applied || change == ConeChange.ConeUnchanged; + + this.TraceResult(ApplyEventName, change, stopwatch.ElapsedMilliseconds, NamedPipeMessages.ConeManagement.ApplyWaitBudgetMs, metadata); + return succeeded; + } + + /// + /// Start to track working-tree changes. Changes made while no mount ran do not reach the + /// manager, so the first Git command applies the cone of every modified path. + /// + public void Start() + { + this.SetPending(); + } + + /// Stop the background checks. Requests and callbacks after this do nothing. + public void Stop() + { + this.isStopped = true; + this.changeCheckTimer.Dispose(); + } + + /// + public void OnWorkingDirectoryPathChanged(string relativePath, bool isFolder) + { + if (this.isStopped || string.IsNullOrEmpty(relativePath)) + { + return; + } + + try + { + string path = NormalizeModifiedPath(relativePath, isFolder); + if (path.Length == 0 || path == GVFSConstants.GitPathSeparatorString) + { + return; + } + + // Record the change before reading the cone. A cone change then either sees this + // record, or this method sees the new cone (see PublishCone). + long sequence = Interlocked.Increment(ref this.changeSequence); + PathChange uncovered = new PathChange(sequence, WasCovered: false); + this.changedPaths[path] = uncovered; + + AppliedConeSnapshot cone = Volatile.Read(ref this.appliedCone); + if (cone != null && cone.IsCovered(path)) + { + this.changedPaths.TryUpdate(path, new PathChange(sequence, WasCovered: true), uncovered); + + // The file can have the content of HEAD again. Check when the changes stop. + this.changeCheckTimer.Change(this.changeCheckDelayMs, Timeout.Infinite); + } + else + { + this.SetPending(); + } + } + catch (ObjectDisposedException) when (this.isStopped) + { + } + catch (Exception e) when (e is not OutOfMemoryException) + { + // The cone can miss this change. The next Git command that names the path, or the + // next mount, adds it. + EventMetadata metadata = this.CreateMetadata(commandId: null); + metadata.Add("Exception", e.ToString()); + this.tracer.RelatedWarning(metadata, nameof(this.OnWorkingDirectoryPathChanged) + " failed", Keywords.Telemetry); + } + } + + /// + /// A Git command released the GVFS lock. Start a background check for modified files + /// that match HEAD again (see ). Returns at once. + /// + public void OnGitCommandCompleted() + { + this.ScheduleReconcile(); + } + + /// + /// Ask Git which paths differ from HEAD, and write a cone file without the modified files + /// that match HEAD. A clean file that differs again goes back into the cone. Git does not + /// write the index, and the manager does not wait for the GVFS lock. + /// + /// True when the check ran or was not needed. + public bool TryReconcile() + { + Stopwatch stopwatch = Stopwatch.StartNew(); + EventMetadata metadata = this.CreateMetadata(commandId: null); + ConeChange change = this.RunAndCatch(() => this.Reconcile(metadata), metadata); + + bool succeeded; + switch (change) + { + case ConeChange.NothingChanged: + case ConeChange.ConeChangePending: + case ConeChange.StateChanged: + case ConeChange.Stopped: + // Nothing to report: the check did not change anything. + return true; + + case ConeChange.Narrowed: + case ConeChange.ConeUnchanged: + case ConeChange.CleanPathChanged: + Interlocked.Exchange(ref this.reconcileWriteRetries, 0); + succeeded = true; + break; + + case ConeChange.WriteFailed: + case ConeChange.ConeFileLocked: + // Another process can have the cone file open, or a Git sparse-checkout + // command can hold its lock. No Git command has to end before the next try. + if (Interlocked.Increment(ref this.reconcileWriteRetries) <= MaxReconcileWriteRetries) + { + metadata.Add("RetryAfterMs", this.changeCheckDelayMs); + this.changeCheckTimer.Change(this.changeCheckDelayMs, Timeout.Infinite); + } + + succeeded = false; + break; + + default: + succeeded = false; + break; + } + + this.TraceResult(ReconcileEventName, change, stopwatch.ElapsedMilliseconds, waitBudgetMs: int.MaxValue, metadata); + return succeeded; + } + + /// + /// Remove the paths of a Git command from the cone. Git has already run. + /// + /// True when the cone file no longer includes paths that only that command needed. + public bool TryNarrow(NamedPipeMessages.ConeManagement.NarrowParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + + Stopwatch stopwatch = Stopwatch.StartNew(); + EventMetadata metadata = this.CreateMetadata(parameters.CommandId); + + ConeChange change = this.RunAndCatch(() => this.Narrow(parameters, metadata), metadata); + bool succeeded = change == ConeChange.Narrowed || + change == ConeChange.ConeUnchanged || + change == ConeChange.NothingToNarrow || + change == ConeChange.NoCommandId; + + this.TraceResult(NarrowEventName, change, stopwatch.ElapsedMilliseconds, NamedPipeMessages.ConeManagement.NarrowWaitBudgetMs, metadata); + return succeeded; + } + + private static void TraceInvalidRequest(ITracer tracer, string header) + { + // Any local user can write to the mount pipe, so the body is not traced. + EventMetadata metadata = new EventMetadata(); + metadata.Add("Area", nameof(AutoSparseIndexConeManager)); + metadata.Add("Header", header); + tracer.RelatedWarning(metadata, "Cone request has a body that is not valid", Keywords.Telemetry); + } + + private static bool TryGetProcessId(string commandId, out int processId) + { + processId = 0; + return !string.IsNullOrEmpty(commandId) && + int.TryParse(commandId, NumberStyles.None, CultureInfo.InvariantCulture, out processId) && + processId > 0; + } + + private static bool IsFailure(ConeChange change) + { + switch (change) + { + case ConeChange.InvalidRequest: + case ConeChange.InvalidPath: + case ConeChange.QueueWaitTooLong: + case ConeChange.SparseDirectoriesUnknown: + case ConeChange.ConeFileLocked: + case ConeChange.WriteFailed: + case ConeChange.ApplyFailed: + case ConeChange.UnexpectedException: + case ConeChange.DiffFailed: + return true; + + default: + return false; + } + } + + private static string NormalizeModifiedPath(string path, bool isFolder) + { + // The same form as the modified-paths database: forward slashes, no leading or + // trailing slash, and a trailing slash for a folder. + string normalized = path.Replace('\\', GVFSConstants.GitPathSeparator).Trim(GVFSConstants.GitPathSeparator); + return isFolder ? normalized + GVFSConstants.GitPathSeparatorString : normalized; + } + + private static bool IsFolderPath(string modifiedPath) + { + return modifiedPath.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal); + } + + private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parameters, ApplyAttempt attempt, Stopwatch stopwatch, EventMetadata metadata) + { + if (!parameters.IsValid()) + { + return ConeChange.InvalidRequest; + } + + if (parameters.Paths.Count > MaxWidenPaths) + { + return ConeChange.TooManyPaths; + } + + // Without a process id, nothing can remove the entries when Git ends without a narrow. + if (!TryGetProcessId(parameters.CommandId, out int processId)) + { + return ConeChange.NoCommandId; + } + + if (parameters.Paths.Count <= MaxTracedPaths) + { + metadata.Add("Paths", string.Join(";", parameters.Paths)); + } + + return this.ApplyCone(processId, parameters.Paths, MaxQueueWaitBeforeApplyMs, attempt, stopwatch, metadata); + } + + /// + /// Write the cone of the modified paths, the transient paths, and + /// , and apply it to the index for the Git process that + /// holds the GVFS lock. + /// + private ConeChange ApplyCone(int processId, IReadOnlyList requestPaths, int maxQueueWaitMs, ApplyAttempt attempt, Stopwatch stopwatch, EventMetadata metadata) + { + // Refuse a command that does not hold the GVFS lock before it waits for other + // requests. The check runs again under the lock, because the holder can change. + if (!this.environment.CanWriteIndex(processId)) + { + return ConeChange.NotLockHolder; + } + + lock (this.coneLock) + { + if (!this.environment.CanWriteIndex(processId)) + { + return ConeChange.NotLockHolder; + } + + this.RemoveEndedCommands(metadata); + + if (!this.TryGetStartTime(processId, out long startTime)) + { + return ConeChange.CommandEnded; + } + + if (requestPaths.Count > 0 && this.transientState.IsNarrowed(processId, startTime)) + { + return ConeChange.CommandAlreadyNarrowed; + } + + if (stopwatch.ElapsedMilliseconds > maxQueueWaitMs) + { + return ConeChange.QueueWaitTooLong; + } + + // From here, this request applies every change that is pending now. A change + // after this point makes the pending file again (see OnWorkingDirectoryPathChanged). + attempt.ClearedPending = this.ClearPending(); + long consumedSequence = Interlocked.Read(ref this.changeSequence); + + List modifiedPaths = new List(this.environment.GetModifiedPaths()); + this.ConsumeChanges(consumedSequence, modifiedPaths, metadata); + + // A modified file that exists keeps its content when Git expands its directory. + // A deleted file, or a modified folder, does not, unless Git changes only the + // index. Only those need the list of sparse-directory entries, and only when the + // applied cone does not already expand them. A clean path has no index entry that + // differs from the working tree. + AppliedConeSnapshot applied = Volatile.Read(ref this.appliedCone); + List unsafePaths = new List(); + if (!this.environment.SparsityChangeIsIndexOnly) + { + foreach (string path in modifiedPaths.Concat(this.unconfirmedPaths)) + { + if ((IsFolderPath(path) || !this.environment.IsFileInWorkingDirectory(path)) && + !this.cleanPaths.Contains(path) && + (applied == null || !applied.IsCovered(path))) + { + unsafePaths.Add(path); + } + } + } + + List hidden = new List(); + if (unsafePaths.Count > 0) + { + Stopwatch listStopwatch = Stopwatch.StartNew(); + if (!this.environment.TryGetSparseDirectories(out IReadOnlyList sparseDirectories, out string sparseDirectoriesError)) + { + metadata.Add("SparseDirectoriesError", sparseDirectoriesError); + return ConeChange.SparseDirectoriesUnknown; + } + + metadata.Add("ListSparseDirectoriesMs", listStopwatch.ElapsedMilliseconds); + hidden = SparseDirectoryExpansionGuard.FindHiddenModifiedPaths(unsafePaths, sparseDirectories, this.ignoreCase); + } + + HashSet hiddenSet = new HashSet(hidden, StringComparer.Ordinal); + if (hidden.Count > 0) + { + metadata.Add("HiddenModifiedPathCount", hidden.Count); + } + + List conePaths = this.GetConePaths(modifiedPaths, hiddenSet); + conePaths.AddRange(requestPaths); + if (!this.TryBuildCone(conePaths, metadata, out ConePatternSet cone)) + { + return ConeChange.InvalidPath; + } + + string unsafePath = SparseDirectoryExpansionGuard.FindReachedPath(cone, hidden, this.ignoreCase); + if (unsafePath != null) + { + metadata.Add("UnsafeModifiedPath", unsafePath); + return ConeChange.ExpandsModifiedPath; + } + + if (!this.environment.TryLockConeFile(out IDisposable coneFileLock, out Exception lockError)) + { + metadata.Add("LockError", lockError?.ToString()); + return ConeChange.ConeFileLocked; + } + + using (coneFileLock) + { + bool coneFileExisted = this.fileSystem.FileExists(this.sparseCheckoutPath); + ConeFileWriteResult writeResult = this.coneFileWriter.Write(this.sparseCheckoutPath, cone, out string backupPath, out Exception writeError); + metadata.Add("WriteResult", writeResult.ToString()); + bool keepBackup = false; + try + { + if (writeResult == ConeFileWriteResult.Failed) + { + metadata.Add("WriteError", writeError?.ToString()); + return ConeChange.WriteFailed; + } + + this.hiddenModifiedPaths = hiddenSet; + this.coneFileMayBeStale = false; + if (writeResult == ConeFileWriteResult.Unchanged && !this.indexMayDifferFromCone) + { + this.AddTransientPaths(processId, startTime, requestPaths); + this.PublishCone(cone); + return ConeChange.ConeUnchanged; + } + + // Until Git succeeds, the index can differ from the cone file. + this.indexMayDifferFromCone = true; + if (!this.TryApplyConeToIndex(metadata)) + { + keepBackup = !this.TryRollBack(writeResult, coneFileExisted, backupPath, metadata); + this.coneFileMayBeStale = keepBackup; + if (keepBackup) + { + // The cone file now has directories that the index did not expand. + this.PublishCone(null); + } + + return ConeChange.ApplyFailed; + } + + this.indexMayDifferFromCone = false; + this.AddTransientPaths(processId, startTime, requestPaths); + this.PublishCone(cone); + return ConeChange.Applied; + } + finally + { + if (!keepBackup) + { + this.DeleteBackup(backupPath, metadata); + } + } + } + } + } + + private ConeChange Narrow(NamedPipeMessages.ConeManagement.NarrowParameters parameters, EventMetadata metadata) + { + if (!TryGetProcessId(parameters.CommandId, out int processId)) + { + return ConeChange.NoCommandId; + } + + lock (this.coneLock) + { + // A narrow from a process that already ended still removes its entries. Without + // a start time, the manager records no narrowed command: it cannot tell a later + // process with the same id from this one. + bool removed = this.TryGetStartTime(processId, out long startTime) + ? this.transientState.Remove(processId, startTime) + : this.transientState.Remove(processId, startTime: null); + int ended = this.RemoveEndedCommands(metadata); + if (!removed && ended == 0 && !this.coneFileMayBeStale) + { + return ConeChange.NothingToNarrow; + } + + ConeChange change = this.WriteNarrowerCone(metadata); + if (change == ConeChange.Narrowed) + { + // The index keeps the directories of the transient paths until the next widen. + this.indexMayDifferFromCone = true; + } + + return change; + } + } + + /// + /// Write the cone of the modified paths and the transient paths without running Git. + /// The caller holds , and the new cone does not include a directory + /// that the index does not expand. + /// + private ConeChange WriteNarrowerCone(EventMetadata metadata) + { + // Until the cone file is written, a later request must write it again. + this.coneFileMayBeStale = true; + + List modifiedPaths = new List(this.environment.GetModifiedPaths()); + List conePaths = this.GetConePaths(modifiedPaths, this.hiddenModifiedPaths); + if (!this.TryBuildCone(conePaths, metadata, out ConePatternSet cone)) + { + return ConeChange.InvalidPath; + } + + // A modified path that is newer than the last apply can be in a directory that the + // index does not expand. The cone file then has it, so the next apply must run Git + // even when the cone file does not change. + AppliedConeSnapshot applied = Volatile.Read(ref this.appliedCone); + bool hasUnappliedPaths = applied == null || conePaths.Exists(path => !applied.IsCovered(path)); + + if (!this.environment.TryLockConeFile(out IDisposable coneFileLock, out Exception lockError)) + { + metadata.Add("LockError", lockError?.ToString()); + return ConeChange.ConeFileLocked; + } + + using (coneFileLock) + { + ConeFileWriteResult writeResult = this.coneFileWriter.Write(this.sparseCheckoutPath, cone, out string backupPath, out Exception writeError); + metadata.Add("WriteResult", writeResult.ToString()); + + // A narrow does not run Git, so it never restores the previous file. + this.DeleteBackup(backupPath, metadata); + + switch (writeResult) + { + case ConeFileWriteResult.Failed: + metadata.Add("WriteError", writeError?.ToString()); + return ConeChange.WriteFailed; + + case ConeFileWriteResult.Unchanged: + this.coneFileMayBeStale = false; + this.PublishConeIfKnown(cone); + return ConeChange.ConeUnchanged; + + default: + this.coneFileMayBeStale = false; + if (hasUnappliedPaths) + { + metadata.Add("HasUnappliedPaths", true); + this.indexMayDifferFromCone = true; + } + + this.PublishConeIfKnown(cone); + return ConeChange.Narrowed; + } + } + } + + private ConeChange RunAndCatch(Func operation, EventMetadata metadata) + { + try + { + return operation(); + } + catch (Exception e) when (e is not OutOfMemoryException) + { + metadata.Add("Exception", e.ToString()); + return ConeChange.UnexpectedException; + } + } + + private bool TryApplyConeToIndex(EventMetadata metadata) + { + Stopwatch applyStopwatch = Stopwatch.StartNew(); + try + { + GitProcess.Result applyResult = this.environment.ApplyConeToIndex(); + metadata.Add("ApplyMs", applyStopwatch.ElapsedMilliseconds); + if (applyResult.ExitCodeIsFailure) + { + metadata.Add("ExitCode", applyResult.ExitCode); + metadata.Add("Errors", applyResult.Errors); + return false; + } + + return true; + } + catch (Exception e) when (e is not OutOfMemoryException) + { + metadata.Add("Exception", e.ToString()); + return false; + } + } + + /// + /// Put back the cone file that was there before the widen. Return false when the + /// previous file could not be restored. + /// + private bool TryRollBack(ConeFileWriteResult writeResult, bool coneFileExisted, string backupPath, EventMetadata metadata) + { + if (writeResult != ConeFileWriteResult.Written) + { + return true; + } + + bool restored; + Exception restoreError; + if (backupPath != null) + { + restored = this.coneFileWriter.TryRestoreBackup(this.sparseCheckoutPath, backupPath, out restoreError); + } + else if (!coneFileExisted) + { + // There was no cone file before. Without one, the hooks send no requests. + restored = this.fileSystem.TryDeleteFile(this.sparseCheckoutPath, out restoreError); + } + else + { + // The writer could not tell that a file was there and made no backup. + restored = false; + restoreError = null; + } + + metadata.Add("Restored", restored); + if (!restored) + { + // The cone file now includes directories that the index does not expand. Git + // expands them in memory when it needs them. The backup stays for diagnosis. + metadata.Add("RestoreError", restoreError?.ToString()); + } + + return restored; + } + + private List GetConePaths(List modifiedPaths, HashSet excludedModifiedPaths) + { + List paths = new List(modifiedPaths.Count); + foreach (string modifiedPath in modifiedPaths) + { + if (!excludedModifiedPaths.Contains(modifiedPath) && !this.cleanPaths.Contains(modifiedPath)) + { + paths.Add(modifiedPath); + } + } + + foreach (string unconfirmedPath in this.unconfirmedPaths) + { + if (!excludedModifiedPaths.Contains(unconfirmedPath)) + { + paths.Add(unconfirmedPath); + } + } + + paths.AddRange(this.transientState.GetAllPaths()); + return paths; + } + + private void AddTransientPaths(int processId, long startTime, IReadOnlyList requestPaths) + { + if (requestPaths.Count > 0) + { + this.transientState.Add(processId, startTime, requestPaths); + } + } + + /// + /// Use the working-tree changes up to : a clean file that + /// changed can differ from HEAD again. The caller holds . + /// + /// + /// The mount adds a changed path to the modified paths in a background task, and that + /// task waits while a Git command holds the GVFS lock. So a change can arrive before + /// its modified path. Such a path stays in the cone as an unconfirmed path until the + /// modified paths have it, or until a check finds it clean. + /// + private void ConsumeChanges(long sequence, List modifiedPaths, EventMetadata metadata) + { + HashSet modified = new HashSet(modifiedPaths, this.pathComparer); + int consumed = 0; + foreach (KeyValuePair change in this.changedPaths) + { + if (change.Value.Sequence <= sequence && + ((ICollection>)this.changedPaths).Remove(change)) + { + this.cleanPaths.Remove(change.Key); + if (!IsModifiedPathOrUnderModifiedFolder(change.Key, modified)) + { + this.unconfirmedPaths.Add(change.Key); + } + + consumed++; + } + } + + this.RemoveConfirmedAndStalePaths(modified); + this.consumeEpoch++; + metadata.Add("ConsumedChangeCount", consumed); + metadata.Add("CleanPathCount", this.cleanPaths.Count); + if (this.unconfirmedPaths.Count > 0) + { + metadata.Add("UnconfirmedPathCount", this.unconfirmedPaths.Count); + } + } + + private static bool IsModifiedPathOrUnderModifiedFolder(string path, HashSet modified) + { + if (modified.Contains(path)) + { + return true; + } + + // The modified paths do not list a file or folder inside a modified folder. + string trimmed = path.TrimEnd(GVFSConstants.GitPathSeparator); + for (int separator = trimmed.LastIndexOf(GVFSConstants.GitPathSeparator); separator > 0; separator = trimmed.LastIndexOf(GVFSConstants.GitPathSeparator, separator - 1)) + { + if (modified.Contains(trimmed.Substring(0, separator + 1))) + { + return true; + } + } + + return false; + } + + private void RemoveConfirmedAndStalePaths(HashSet modified) + { + // A dehydrated file leaves the modified paths. It is not clean or dirty any more. + this.cleanPaths.RemoveWhere(path => !modified.Contains(path)); + this.unconfirmedPaths.RemoveWhere(path => IsModifiedPathOrUnderModifiedFolder(path, modified)); + } + + /// + /// Record that the index has entries for every directory of , and + /// that the cone file is . Null means that this is not known. + /// + private void PublishCone(ConePatternSet cone) + { + this.PublishSnapshot(cone == null ? null : new AppliedConeSnapshot(new ConeCoverage(cone))); + } + + /// + /// Record a cone file that the manager wrote without running Git. The index can lack + /// entries for a directory that the new cone adds, so only the directories that both + /// cones include count as applied. + /// + private void PublishConeIfKnown(ConePatternSet cone) + { + AppliedConeSnapshot current = Volatile.Read(ref this.appliedCone); + this.PublishSnapshot(current?.Intersect(new ConeCoverage(cone))); + } + + private void PublishSnapshot(AppliedConeSnapshot snapshot) + { + Volatile.Write(ref this.appliedCone, snapshot); + Interlocked.MemoryBarrier(); + + // A change that read the previous cone may need the new one. See + // OnWorkingDirectoryPathChanged for the order of the two steps. + foreach (KeyValuePair change in this.changedPaths) + { + if (snapshot == null || !snapshot.IsCovered(change.Key)) + { + this.SetPending(); + return; + } + } + } + + private void SetPending() + { + if (Volatile.Read(ref this.isPending)) + { + return; + } + + lock (this.pendingLock) + { + if (this.isPending) + { + return; + } + + if (this.environment.TrySetConeChangePending(true, out Exception error)) + { + this.isPending = true; + return; + } + + // Without the file, the hook does not ask for the change. The next change, or + // the next Git command that names the path, tries again. + EventMetadata metadata = this.CreateMetadata(commandId: null); + metadata.Add("Exception", error?.ToString()); + this.tracer.RelatedWarning(metadata, "Could not create the cone change pending file", Keywords.Telemetry); + } + } + + /// Delete the pending file. Return true when a change was pending. + private bool ClearPending() + { + lock (this.pendingLock) + { + if (!this.isPending) + { + return false; + } + + if (!this.environment.TrySetConeChangePending(false, out Exception error)) + { + // The file stays, and so does the pending state: the next request deletes + // the file again. Until then, each Git command sends a request. + EventMetadata metadata = this.CreateMetadata(commandId: null); + metadata.Add("Exception", error?.ToString()); + this.tracer.RelatedWarning(metadata, "Could not delete the cone change pending file", Keywords.Telemetry); + return true; + } + + Volatile.Write(ref this.isPending, false); + return true; + } + } + + private void RearmPendingAfterAttempt(ApplyAttempt attempt, ConeChange change, bool requestHasPaths, EventMetadata metadata) + { + if (!attempt.ClearedPending) + { + return; + } + + bool rearm; + switch (change) + { + case ConeChange.Applied: + case ConeChange.ConeUnchanged: + return; + + case ConeChange.ExpandsModifiedPath: + case ConeChange.InvalidPath: + // The pending changes alone cannot make the same cone valid, so a retry + // fails again until the working tree changes. The request paths can be the + // cause, and an apply without them can succeed. + rearm = requestHasPaths; + break; + + default: + // Without the apply, Git does not see the change, and Git has no fallback + // for that. Every later Git command tries again. + rearm = true; + break; + } + + metadata.Add("PendingKept", rearm); + if (rearm) + { + this.SetPending(); + } + } + + /// Run in the background, at most one at a time. + private void ScheduleReconcile() + { + if (this.isStopped) + { + return; + } + + lock (this.reconcileScheduleLock) + { + if (this.reconcileRunning) + { + this.reconcileRequested = true; + return; + } + + this.reconcileRunning = true; + } + + // The check runs Git and can take seconds, so it gets its own thread. + Task.Factory.StartNew( + () => + { + while (true) + { + this.TryReconcile(); + lock (this.reconcileScheduleLock) + { + if (!this.reconcileRequested || this.isStopped) + { + this.reconcileRunning = false; + return; + } + + this.reconcileRequested = false; + } + } + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + } + + private ConeChange Reconcile(EventMetadata metadata) + { + if (this.isStopped) + { + return ConeChange.Stopped; + } + + long startSequence; + long epoch; + AppliedConeSnapshot cone; + List candidates; + (long, long, long) state; + lock (this.coneLock) + { + // A pending change can be in a directory that the index does not expand, so Git + // does not report it. Check after the next apply. + cone = Volatile.Read(ref this.appliedCone); + if (Volatile.Read(ref this.isPending) || cone == null) + { + return ConeChange.ConeChangePending; + } + + startSequence = Interlocked.Read(ref this.changeSequence); + epoch = this.consumeEpoch; + state = (startSequence, epoch, this.environment.GetRepositoryStamp()); + if (this.lastReconcileState == state) + { + // A failed write leaves the cone file stale. The clean paths are known, so + // write the file again without Git. + return this.coneFileMayBeStale ? this.WriteNarrowerCone(metadata) : ConeChange.NothingChanged; + } + + // Only a file that the index has an entry for can be clean: one in an applied + // directory, or one that an earlier check found clean while its directory was + // applied. Folders stay in the cone. + candidates = new List(); + HashSet seen = new HashSet(this.pathComparer); + foreach (string path in this.environment.GetModifiedPaths().Concat(this.unconfirmedPaths)) + { + if (!IsFolderPath(path) && + !this.hiddenModifiedPaths.Contains(path) && + (this.cleanPaths.Contains(path) || cone.IsCovered(path)) && + seen.Add(path)) + { + candidates.Add(path); + } + } + + if (candidates.Count == 0) + { + this.lastReconcileState = state; + return ConeChange.NothingChanged; + } + } + + metadata.Add("CandidateCount", candidates.Count); + Stopwatch diffStopwatch = Stopwatch.StartNew(); + if (!this.environment.TryGetPathsThatDifferFromHead(out ICollection differingPaths, out string diffError)) + { + metadata.Add("DiffError", diffError); + return ConeChange.DiffFailed; + } + + metadata.Add("DiffMs", diffStopwatch.ElapsedMilliseconds); + if (this.isStopped) + { + return ConeChange.Stopped; + } + + HashSet differing = new HashSet(differingPaths, this.pathComparer); + List untrackedFolders = differingPaths.Where(IsFolderPath).ToList(); + + // A file is clean when Git lists neither the file nor an untracked folder that + // contains it. Git lists an untracked file, and a deleted tracked file. It does not + // list an ignored file, or a created file that was deleted again. + Dictionary isClean = new Dictionary(candidates.Count, this.pathComparer); + foreach (string path in candidates) + { + isClean[path] = !differing.Contains(path) && + !untrackedFolders.Any(folder => path.StartsWith(folder, this.ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)); + } + + lock (this.coneLock) + { + if (this.consumeEpoch != epoch || this.isStopped) + { + // An apply changed the clean paths or the index while Git ran. + return ConeChange.StateChanged; + } + + int newlyClean = 0; + int newlyDirty = 0; + foreach (KeyValuePair result in isClean) + { + bool changedDuringCheck = this.changedPaths.TryGetValue(result.Key, out PathChange change) && + (change.Sequence > startSequence || !change.WasCovered); + if (result.Value && !changedDuringCheck) + { + // A clean unconfirmed path is not a modified path (for example, a file + // that Git wrote), so it leaves the cone without becoming a clean path. + if (this.unconfirmedPaths.Remove(result.Key) || this.cleanPaths.Add(result.Key)) + { + newlyClean++; + } + } + else if (this.cleanPaths.Remove(result.Key)) + { + newlyDirty++; + } + } + + // Git saw each change that came before the check in a directory that the index + // expands, so the result above already includes it. + foreach (KeyValuePair change in this.changedPaths) + { + if (change.Value.Sequence <= startSequence && change.Value.WasCovered) + { + ((ICollection>)this.changedPaths).Remove(change); + } + } + + this.lastReconcileState = state; + metadata.Add("NewlyCleanCount", newlyClean); + metadata.Add("NewlyDirtyCount", newlyDirty); + metadata.Add("CleanPathCount", this.cleanPaths.Count); + + if (newlyDirty > 0) + { + // The cone must include the file again. Its directory still has index + // entries, but only an apply writes a wider cone file. + this.SetPending(); + return ConeChange.CleanPathChanged; + } + + if (newlyClean == 0) + { + return ConeChange.ConeUnchanged; + } + + return this.WriteNarrowerCone(metadata); + } + } + + private bool TryBuildCone(List paths, EventMetadata metadata, out ConePatternSet cone) + { + try + { + cone = ConeBuilder.BuildFromModifiedPaths(paths, this.ignoreCase); + return true; + } + catch (ArgumentException e) + { + // A cone file cannot include this directory. Do not write a cone that leaves + // it out, because Git then hides the path. Keep the current cone file and index. + metadata.Add("InvalidPathException", e.ToString()); + cone = null; + return false; + } + } + + private int RemoveEndedCommands(EventMetadata metadata) + { + int ended = this.transientState.RemoveEnded(this.IsProcessRunning); + if (ended > 0) + { + metadata.Add("EndedCommandsRemoved", ended); + } + + return ended; + } + + /// + /// Read the start time of a Git process. Return false when the start time is not + /// available: the process ended, or the mount cannot open it. + /// + private bool TryGetStartTime(int processId, out long startTime) + { + return this.environment.TryGetProcessStartTime(processId, out startTime) == ProcessStartTimeResult.Success; + } + + private bool IsProcessRunning(int processId, long? startTime) + { + switch (this.environment.TryGetProcessStartTime(processId, out long currentStartTime)) + { + case ProcessStartTimeResult.Success: + return startTime == null || startTime == currentStartTime; + + case ProcessStartTimeResult.Indeterminate: + // Not known. Keep the entries: a cone that is too large is safe. + return true; + + default: + // ProcessNotFound: the process ended. Inaccessible: the mount opened this + // process before, so another process now has this id. + return false; + } + } + + private void DeleteBackup(string backupPath, EventMetadata metadata) + { + if (backupPath != null && !this.fileSystem.TryDeleteFile(backupPath, out Exception deleteError)) + { + metadata.Add("DeleteBackupError", deleteError?.ToString()); + } + } + + private EventMetadata CreateMetadata(string commandId) + { + EventMetadata metadata = new EventMetadata(); + metadata.Add("Area", nameof(AutoSparseIndexConeManager)); + metadata.Add("CommandId", commandId); + return metadata; + } + + private void TraceResult(string eventName, ConeChange change, long durationMs, int waitBudgetMs, EventMetadata metadata) + { + metadata.Add("Result", change.ToString()); + metadata.Add("DurationMs", durationMs); + metadata.Add("TransientCommandCount", this.GetTransientCommandCount()); + + bool exceededWaitBudget = durationMs > waitBudgetMs; + if (exceededWaitBudget) + { + metadata.Add("WaitBudgetMs", waitBudgetMs); + } + + // A hidden modified path stays invisible to Git, so it is a warning too. + if (IsFailure(change) || exceededWaitBudget || metadata.ContainsKey("DeleteBackupError") || metadata.ContainsKey("HiddenModifiedPathCount")) + { + this.tracer.RelatedEvent(EventLevel.Warning, eventName, metadata, Keywords.Telemetry); + } + else + { + this.tracer.RelatedEvent(EventLevel.Informational, eventName, metadata); + } + } + + private int GetTransientCommandCount() + { + lock (this.coneLock) + { + return this.transientState.CommandCount; + } + } + + /// A working-tree change: its order, and if the applied cone included the path then. + private readonly record struct PathChange(long Sequence, bool WasCovered); + + /// Records whether a request cleared the pending file. + private sealed class ApplyAttempt + { + public bool ClearedPending { get; set; } + } + + /// + /// The directories that the cone file includes and the index expands: those that every + /// cone in the list includes. + /// + private sealed class AppliedConeSnapshot + { + // More cones make every callback slower. Then the manager treats the state as + // unknown, and the next Git command applies the cone again. + private const int MaxCones = 4; + + private readonly ConeCoverage[] cones; + + public AppliedConeSnapshot(params ConeCoverage[] cones) + { + this.cones = cones; + } + + public bool IsCovered(string path) + { + foreach (ConeCoverage cone in this.cones) + { + if (!cone.IsCovered(path)) + { + return false; + } + } + + return true; + } + + public AppliedConeSnapshot Intersect(ConeCoverage cone) + { + if (this.cones.Length >= MaxCones) + { + return null; + } + + ConeCoverage[] combined = new ConeCoverage[this.cones.Length + 1]; + this.cones.CopyTo(combined, 0); + combined[this.cones.Length] = cone; + return new AppliedConeSnapshot(combined); + } + } + } +} 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/ConeCoverage.cs b/GVFS/GVFS.Common/Sparse/ConeCoverage.cs new file mode 100644 index 000000000..50448114f --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/ConeCoverage.cs @@ -0,0 +1,294 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace GVFS.Common.Sparse +{ + /// + /// Reads a cone-mode info/sparse-checkout file into a , + /// and finds the resolved paths that the cone does not cover. + /// + /// + /// A widen request for paths that the cone covers cannot change the cone. The pre-command + /// hook uses this type to find those requests and not send them, so that a command that + /// names only in-cone paths does not wait for the mount. + /// + /// The parse is strict and follows git's cone-mode reader (add_pattern_to_hashsets + /// in dir.c). Like git, it skips empty lines and comment lines. The file must start + /// with the /* and !/*/ header lines. + /// Each later line must be a positive directory pattern or a parent-only marker that + /// follows the positive pattern for the same directory, and no directory can repeat. + /// For any other file, fails, and the caller must not + /// trust the file. + /// + /// + public sealed class ConeCoverage + { + private const string HeaderInclude = "/*"; + private const string HeaderExclude = "!/*/"; + private const string ParentOnlySuffix = "/*/"; + + private static readonly UTF8Encoding Utf8WithoutBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + + private readonly ConePathMatcher matcher; + private readonly HashSet recursiveDirectories; + + public ConeCoverage(ConePatternSet cone) + { + ArgumentNullException.ThrowIfNull(cone); + + this.matcher = new ConePathMatcher(cone); + this.recursiveDirectories = new HashSet(cone.RecursiveDirectories, GitPathComparer.GetComparer(cone.IgnoreCase)); + } + + /// + /// Decode sparse-checkout file bytes as git reads them: skip a UTF-8 byte order mark and + /// read the rest as UTF-8. Git does not recognize other byte order marks, so a UTF-16 + /// file does not decode to cone patterns. A byte sequence that is not UTF-8 becomes + /// U+FFFD, and does not trust a directory with U+FFFD. + /// + public static string DecodeConeFile(byte[] bytes) + { + ArgumentNullException.ThrowIfNull(bytes); + + int start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0; + return Utf8WithoutBom.GetString(bytes, start, bytes.Length - start); + } + + /// + /// Return true when the content starts with the cone-mode header lines /* and + /// !/*/. Git cannot use a sparse index without cone mode, so content without + /// the header cannot need a widen. + /// + public static bool HasConeHeader(string content) + { + if (content == null) + { + return false; + } + + int position = 0; + return TryReadLine(content, ref position, out string first) && first == HeaderInclude && + TryReadLine(content, ref position, out string second) && second == HeaderExclude; + } + + /// + /// Parse cone-mode sparse-checkout file content. Return false when the content is not + /// a cone file that git and GVFS read with the same meaning. + /// + /// The file content. + /// The repository's core.ignoreCase value. + /// The cone, when the method returns true. Otherwise null. + public static bool TryParseConeFile(string content, bool ignoreCase, out ConePatternSet cone) + { + cone = null; + if (!HasConeHeader(content)) + { + return false; + } + + GitPathComparer comparer = GitPathComparer.GetComparer(ignoreCase); + List positiveDirectories = new List(); + HashSet positives = new HashSet(comparer); + HashSet parentOnly = new HashSet(comparer); + + int position = 0; + TryReadLine(content, ref position, out _); + TryReadLine(content, ref position, out _); + while (TryReadLine(content, ref position, out string line)) + { + if (line[0] == '!') + { + // Git requires the positive pattern before its parent-only marker. + if (!TryParseParentOnly(line, out string directory) || + !positives.Contains(directory) || + !parentOnly.Add(directory)) + { + return false; + } + } + else + { + if (!TryParsePositive(line, out string directory) || !positives.Add(directory)) + { + return false; + } + + positiveDirectories.Add(directory); + } + } + + List parentOnlyDirectories = new List(); + List recursiveDirectories = new List(); + foreach (string directory in positiveDirectories) + { + if (parentOnly.Contains(directory)) + { + parentOnlyDirectories.Add(directory); + } + else + { + recursiveDirectories.Add(directory); + } + } + + try + { + cone = new ConePatternSet(parentOnlyDirectories, recursiveDirectories, ignoreCase); + } + catch (ArgumentException) + { + return false; + } + + return true; + } + + /// + /// Return true when a resolved git-form path is in the cone. A file path is covered + /// when git includes it (see ). A folder path, which + /// ends with a slash, is covered only when its whole subtree is in the cone: the folder + /// or one of its ancestors is a recursive directory. + /// + public bool IsCovered(string resolvedGitPath) + { + ArgumentNullException.ThrowIfNull(resolvedGitPath); + + string path = ConePath.Normalize(resolvedGitPath, out bool isFolder); + if (!isFolder) + { + return this.matcher.IsInCone(path); + } + + for (string directory = path; directory.Length != 0; directory = ConePath.GetParent(directory)) + { + if (this.recursiveDirectories.Contains(directory)) + { + return true; + } + } + + return false; + } + + /// + /// Return the resolved git-form paths that the cone does not cover, in their input order. + /// + public IReadOnlyList GetUncoveredPaths(IEnumerable resolvedGitPaths) + { + ArgumentNullException.ThrowIfNull(resolvedGitPaths); + + List uncovered = new List(); + foreach (string path in resolvedGitPaths) + { + if (!this.IsCovered(path)) + { + uncovered.Add(path); + } + } + + return uncovered; + } + + private static bool TryParsePositive(string line, out string directory) + { + directory = null; + + // A positive directory pattern is "//". + if (line.Length < 3 || + line[0] != GVFSConstants.GitPathSeparator || + line[line.Length - 1] != GVFSConstants.GitPathSeparator) + { + return false; + } + + return TryUnescapeDirectory(line.Substring(1, line.Length - 2), out directory); + } + + private static bool TryParseParentOnly(string line, out string directory) + { + directory = null; + + // A parent-only marker is "!//*/". + if (line.Length < 2 + 1 + ParentOnlySuffix.Length || + line[1] != GVFSConstants.GitPathSeparator || + !line.EndsWith(ParentOnlySuffix, StringComparison.Ordinal)) + { + return false; + } + + return TryUnescapeDirectory(line.Substring(2, line.Length - 2 - ParentOnlySuffix.Length), out directory); + } + + /// + /// Reverse . Fail on an unescaped wildcard + /// character or on a backslash that does not escape one, because git does not read + /// either as a literal cone directory. + /// + private static bool TryUnescapeDirectory(string escaped, out string directory) + { + directory = null; + + StringBuilder builder = new StringBuilder(escaped.Length); + for (int i = 0; i < escaped.Length; i++) + { + char character = escaped[i]; + if (character == '\\') + { + if (i + 1 >= escaped.Length || !IsGlobSpecial(escaped[i + 1])) + { + return false; + } + + i++; + builder.Append(escaped[i]); + } + else if (IsGlobSpecial(character)) + { + return false; + } + else + { + builder.Append(character); + } + } + + directory = builder.ToString(); + + // DecodeConeFile replaces bytes that are not UTF-8 with U+FFFD, and git compares + // the original bytes. Such a directory cannot be compared, so do not trust the file. + return directory.IndexOf('\uFFFD') < 0 && ConePatternSet.IsValidDirectory(directory); + } + + /// + /// Read the next line that is not empty and not a comment, without its line ending, and + /// move past it. Git's reader skips the same lines. + /// + private static bool TryReadLine(string content, ref int position, out string line) + { + while (position < content.Length) + { + int end = content.IndexOf('\n', position); + if (end < 0) + { + end = content.Length; + } + + line = content.Substring(position, end - position).TrimEnd('\r'); + position = end + 1; + if (line.Length != 0 && line[0] != '#') + { + return true; + } + } + + line = null; + return false; + } + + private static bool IsGlobSpecial(char character) + { + return character == '*' || character == '?' || character == '[' || character == '\\'; + } + } +} 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/ConePathspecResolver.cs b/GVFS/GVFS.Common/Sparse/ConePathspecResolver.cs new file mode 100644 index 000000000..4fc52ba76 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/ConePathspecResolver.cs @@ -0,0 +1,355 @@ +using System; +using System.Collections.Generic; + +namespace GVFS.Common.Sparse +{ + /// + /// Resolves the literal pathspecs that a Git command names into repo-relative git-form + /// paths, which and accept. + /// + /// + /// This type does no I/O. + /// + /// Only a trailing slash gives a pathspec the shape of a folder. A folder resolves to a + /// recursive entry, and any other pathspec resolves to a file, which puts only its parent + /// directory in the cone. Thus an ambiguous dir/subdir is under-widened, not + /// over-widened. An over-wide recursive entry makes the index larger. An under-wide + /// entry only makes Git expand the index in memory. + /// + /// + /// The resolver skips a pathspec that it cannot map to one cone entry, so the result can + /// only under-widen. It skips a magic pathspec (a leading :), a path outside the + /// worktree, the worktree root, a pathspec with a wildcard character in a directory + /// segment, and a path that rejects. A wildcard only in the + /// last segment of a file pathspec is kept: the file's parent directory is still the + /// right cone entry for it. + /// + /// + public static class ConePathspecResolver + { + private static readonly char[] WildcardCharacters = new[] { '*', '?', '[' }; + private static readonly string[] ReservedDeviceNames = new[] { "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$" }; + + /// + /// Return the directory that relative pathspecs resolve against. + /// + /// + /// Before Git runs the pre-command hook for a command that uses a repository, Git + /// changes to the top of the worktree and puts the user's subdirectory in the + /// GIT_PREFIX environment variable. Thus when the hook runs at the worktree + /// root and is a relative path inside the worktree, the + /// base directory is the root plus the prefix. In all other cases, the hook's current + /// directory is the base directory. + /// + /// The current directory of the hook process (absolute). + /// The root of the worktree (absolute). + /// The value of GIT_PREFIX, or null when it is not set. + public static string GetPathspecBaseDirectory(string hookCurrentDirectory, string workingDirectoryRoot, string gitPrefix) + { + ArgumentNullException.ThrowIfNull(hookCurrentDirectory); + ArgumentNullException.ThrowIfNull(workingDirectoryRoot); + + if (string.IsNullOrEmpty(gitPrefix)) + { + return hookCurrentDirectory; + } + + string current = TrimTrailingSeparators(ToForwardSlashes(hookCurrentDirectory)); + string root = TrimTrailingSeparators(ToForwardSlashes(workingDirectoryRoot)); + if (!current.Equals(root, StringComparison.OrdinalIgnoreCase)) + { + // Git did not change to the worktree root, so the prefix does not apply. + return hookCurrentDirectory; + } + + // Git writes the prefix as a relative path with a trailing slash. Ignore any other + // value, so that the base directory cannot leave the worktree. + string prefix = TrimTrailingSeparators(ToForwardSlashes(gitPrefix)); + if (prefix.Length == 0 || !IsValidGitPath(prefix)) + { + return hookCurrentDirectory; + } + + return root + GVFSConstants.GitPathSeparatorString + prefix; + } + + /// + /// Resolve pathspecs to distinct repo-relative git-form paths. A file entry has no + /// trailing slash. A folder entry keeps its trailing slash. Every result passes + /// . + /// + /// + /// The directory that relative pathspecs resolve against (absolute). See + /// . + /// + /// The root of the worktree (absolute). + /// The literal pathspecs, as the user typed them. + public static IReadOnlyList ResolveToGitPaths( + string pathspecBaseDirectory, + string workingDirectoryRoot, + IEnumerable pathspecs) + { + ArgumentNullException.ThrowIfNull(workingDirectoryRoot); + + List resolved = new List(); + if (pathspecs == null) + { + return resolved; + } + + string rootAbsolute = TrimTrailingSeparators(ToForwardSlashes(workingDirectoryRoot)); + string baseAbsolute = TrimTrailingSeparators(ToForwardSlashes(pathspecBaseDirectory ?? string.Empty)); + + HashSet seen = new HashSet(StringComparer.Ordinal); + foreach (string rawPathspec in pathspecs) + { + if (TryResolveOne(rawPathspec, rootAbsolute, baseAbsolute, out string gitPath) && + seen.Add(gitPath)) + { + resolved.Add(gitPath); + } + } + + return resolved; + } + + /// + /// Return true when a path is a repo-relative git-form path that a cone can contain and + /// that stays inside the worktree on Windows. + /// + /// + /// The path uses forward slashes, has no leading slash, and has an optional trailing + /// slash for a folder. Its directory part (the folder, or the parent of a file) must + /// pass and must not contain a wildcard. + /// No segment can be empty, ., .., or .git, end with a dot or a + /// space, or be a Windows device name such as CON or COM1. Git for Windows + /// does not check out such paths. The path must not contain a backslash, a colon, a + /// control character, or an unpaired surrogate. + /// + public static bool IsValidGitPath(string path) + { + if (string.IsNullOrEmpty(path) || path[0] == GVFSConstants.GitPathSeparator) + { + return false; + } + + for (int i = 0; i < path.Length; i++) + { + char character = path[i]; + if (character < ' ' || character == '\\' || character == ':') + { + return false; + } + + if (char.IsHighSurrogate(character) && i + 1 < path.Length && char.IsLowSurrogate(path[i + 1])) + { + i++; + } + else if (char.IsSurrogate(character)) + { + return false; + } + } + + bool isFolder = path[path.Length - 1] == GVFSConstants.GitPathSeparator; + string trimmed = isFolder ? path.Substring(0, path.Length - 1) : path; + foreach (string segment in trimmed.Split(GVFSConstants.GitPathSeparator)) + { + if (!IsValidSegment(segment)) + { + return false; + } + } + + int lastSeparator = trimmed.LastIndexOf(GVFSConstants.GitPathSeparator); + string directory = isFolder ? trimmed : (lastSeparator < 0 ? string.Empty : trimmed.Substring(0, lastSeparator)); + return directory.Length == 0 || + (directory.IndexOfAny(WildcardCharacters) < 0 && ConePatternSet.IsValidDirectory(directory)); + } + + private static bool IsValidSegment(string segment) + { + if (segment.Length == 0 || + segment == "." || + segment == ".." || + segment.Equals(GVFSConstants.DotGit.Root, StringComparison.OrdinalIgnoreCase) || + segment[segment.Length - 1] == '.' || + segment[segment.Length - 1] == ' ') + { + return false; + } + + // Windows opens a device for a reserved name, with or without an extension. + int dot = segment.IndexOf('.'); + string name = (dot < 0 ? segment : segment.Substring(0, dot)).TrimEnd(' '); + foreach (string reserved in ReservedDeviceNames) + { + if (name.Equals(reserved, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + } + + if (name.Length == 4 && + (name.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || name.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)) && + name[3] >= '1' && name[3] <= '9') + { + return false; + } + + return true; + } + private static bool TryResolveOne(string rawPathspec, string rootAbsolute, string baseAbsolute, out string gitPath) + { + gitPath = null; + + // A leading ':' starts a magic pathspec (:/, :(glob), :!, ...). Git expands the + // index for every magic pathspec, so no cone entry can help. + if (string.IsNullOrEmpty(rawPathspec) || rawPathspec[0] == ':') + { + return false; + } + + string normalized = ToForwardSlashes(rawPathspec); + bool isFolder = normalized.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal); + + string absolute; + if (IsAbsolute(normalized)) + { + absolute = normalized; + } + else + { + absolute = baseAbsolute.Length == 0 + ? normalized + : baseAbsolute + GVFSConstants.GitPathSeparatorString + normalized; + } + + if (!TryCanonicalize(absolute, out string canonical) || + !TryMakeRepoRelative(canonical, rootAbsolute, out string relative)) + { + return false; + } + + // An empty result is the worktree root. The cone always includes the files at the + // root, and a recursive root entry is not a cone entry. + if (relative.Length == 0 || HasWildcardInDirectorySegment(relative, isFolder)) + { + return false; + } + + string candidate = isFolder ? relative + GVFSConstants.GitPathSeparatorString : relative; + if (!IsValidGitPath(candidate)) + { + return false; + } + + gitPath = candidate; + return true; + } + + private static bool HasWildcardInDirectorySegment(string relative, bool isFolder) + { + int directoryLength = isFolder ? relative.Length : relative.LastIndexOf(GVFSConstants.GitPathSeparator); + return directoryLength > 0 && relative.IndexOfAny(WildcardCharacters, 0, directoryLength) >= 0; + } + + private static bool TryCanonicalize(string path, out string canonical) + { + canonical = null; + + string[] parts = path.Split(GVFSConstants.GitPathSeparator); + List segments = new List(parts.Length); + foreach (string part in parts) + { + if (part.Length == 0 || part == ".") + { + continue; + } + + if (part == "..") + { + // A ".." that goes above the start of a relative path, or above a drive, + // cannot map to a path in the worktree. + if (segments.Count == 0 || IsDriveSegment(segments[segments.Count - 1])) + { + return false; + } + + segments.RemoveAt(segments.Count - 1); + continue; + } + + segments.Add(part); + } + + canonical = string.Join(GVFSConstants.GitPathSeparatorString, segments); + return true; + } + + private static bool TryMakeRepoRelative(string canonicalAbsolute, string rootAbsolute, out string relative) + { + relative = null; + + if (rootAbsolute.Length == 0) + { + relative = canonicalAbsolute; + return true; + } + + // Windows paths are not case-sensitive, so compare the root without case. Keep the + // caller's case in the result, because the cone compares it with index entries. + if (canonicalAbsolute.Length == rootAbsolute.Length) + { + if (canonicalAbsolute.Equals(rootAbsolute, StringComparison.OrdinalIgnoreCase)) + { + relative = string.Empty; + return true; + } + + return false; + } + + if (canonicalAbsolute.Length > rootAbsolute.Length && + canonicalAbsolute[rootAbsolute.Length] == GVFSConstants.GitPathSeparator && + canonicalAbsolute.StartsWith(rootAbsolute, StringComparison.OrdinalIgnoreCase)) + { + relative = canonicalAbsolute.Substring(rootAbsolute.Length + 1); + return true; + } + + return false; + } + + private static bool IsAbsolute(string forwardSlashedPath) + { + // A drive-rooted path (C:/...) or a path with a leading separator (UNC or rooted). + // A drive-relative "C:relative" path keeps its colon and IsValidGitPath rejects it. + if (forwardSlashedPath.StartsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal)) + { + return true; + } + + return forwardSlashedPath.Length >= 3 && + IsDriveSegment(forwardSlashedPath.Substring(0, 2)) && + forwardSlashedPath[2] == GVFSConstants.GitPathSeparator; + } + + private static bool IsDriveSegment(string segment) + { + return segment.Length == 2 && + char.IsLetter(segment[0]) && + segment[1] == ':'; + } + + private static string ToForwardSlashes(string path) + { + return path.Replace('\\', GVFSConstants.GitPathSeparator); + } + + private static string TrimTrailingSeparators(string path) + { + return path.TrimEnd(GVFSConstants.GitPathSeparator); + } + } +} 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/IConeManagerEnvironment.cs b/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs new file mode 100644 index 000000000..867ed212e --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs @@ -0,0 +1,78 @@ +using GVFS.Common.Git; +using System; +using System.Collections.Generic; + +namespace GVFS.Common.Sparse +{ + /// + /// The mount services that uses. The mount + /// implements them; unit tests replace them, so that no test starts Git or needs a mount. + /// + public interface IConeManagerEnvironment + { + /// The modified-path entries of the worktree (folders end with a slash). + IEnumerable GetModifiedPaths(); + + /// + /// Return true when the Git process holds the GVFS lock. + /// Only then can a Git process that the mount starts replace the index: the holder + /// waits in its pre-command hook, and no other Git command writes the index. + /// + bool CanWriteIndex(int processId); + + /// + /// Get the sparse-directory entries of the index (each ends with a slash). + /// + bool TryGetSparseDirectories(out IReadOnlyList sparseDirectories, out string error); + + /// + /// Return true when the working directory has a file at the modified path + /// . A modified file is a full file or is deleted, so the + /// check does not hydrate anything. + /// + bool IsFileInWorkingDirectory(string gitPath); + + /// + /// Take the lock file that Git's own sparse-checkout writers take + /// (info/sparse-checkout.lock). Dispose the result to release it. + /// + bool TryLockConeFile(out IDisposable coneFileLock, out Exception error); + + /// + /// Run Git to make the sparse-directory entries of the index match the cone file. A + /// result with a success exit code means that Git replaced the index. + /// + GitProcess.Result ApplyConeToIndex(); + + /// Read the start time of a process, to tell it apart from a later process with the same id. + ProcessStartTimeResult TryGetProcessStartTime(int processId, out long startTime); + + /// + /// True when Git changes only the index when the cone changes, and never writes or deletes + /// a working-tree file. Then a widen can expand the directory of a deleted file, and the + /// manager does not need . + /// + bool SparsityChangeIsIndexOnly { get; } + + /// + /// Create ( true) or delete the file that tells the pre-command + /// hook that a cone change is pending (see ). + /// This runs in file system callbacks, so it must be fast and must not throw. + /// + bool TrySetConeChangePending(bool pending, out Exception error); + + /// + /// Get the paths that differ between HEAD and the index or the working tree, as Git + /// reports them: changed and unmerged tracked paths, and untracked files and folders (a + /// folder ends with '/'). Git compares the content of a file whose stat data changed, and + /// it does not write the index. + /// + bool TryGetPathsThatDifferFromHead(out ICollection paths, out string error); + + /// + /// Return a value that changes when Git writes the index or moves HEAD, so that the + /// manager can skip a check when nothing changed. + /// + long GetRepositoryStamp(); + } +} diff --git a/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs b/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs new file mode 100644 index 000000000..216f6c275 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs @@ -0,0 +1,18 @@ +namespace GVFS.Common.Sparse +{ + /// + /// Receives the working-tree changes that the file system callbacks of the mount see, and + /// the staged files that the mount adds to the modified paths before an unstage. + /// + public interface IWorkingDirectoryChangeObserver + { + /// + /// A file or folder was created, written, renamed, or deleted, or a staged file became a + /// modified path. This runs in a file system callback or a pipe request handler, so it + /// must be fast, it must not wait for a Git command, and it must not throw. + /// + /// The path relative to the working-tree root, with either separator. + /// True for a folder. + void OnWorkingDirectoryPathChanged(string relativePath, bool isFolder); + } +} 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.Common/Sparse/SparseDirectoryExpansionGuard.cs b/GVFS/GVFS.Common/Sparse/SparseDirectoryExpansionGuard.cs new file mode 100644 index 000000000..9bcdec427 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/SparseDirectoryExpansionGuard.cs @@ -0,0 +1,172 @@ +using System; +using System.Collections.Generic; + +namespace GVFS.Common.Sparse +{ + /// + /// Finds the deleted files and modified folders that a cone change must not reach. + /// + /// + /// git sparse-checkout reapply replaces a sparse-directory entry with the entries + /// of the directories that the cone now includes. Each new entry starts with the + /// skip-worktree bit. The virtual file system hook then clears that bit for each modified + /// path. Git takes that change as an entry that enters the sparse-checkout, and it checks + /// out each such file that is not in the working directory. For a file that the user + /// deleted, Git writes the file again. + /// + /// Thus the cone must not include the directory of a deleted file that is inside a + /// sparse-directory entry, or any directory in a modified folder that holds one. A modified + /// file that exists keeps its content. A modified path that already has its own index entry + /// is safe, because its skip-worktree bit does not change. A cone that includes only a + /// parent directory is also safe: the deeper directory stays a sparse-directory entry. + /// + /// + /// This type does no I/O. + /// + /// + public static class SparseDirectoryExpansionGuard + { + /// + /// Return the modified paths that are inside a sparse-directory entry, or that are a + /// folder that holds one. These paths have no index entry of their own. + /// + /// Modified-path entries. A folder entry ends with a slash. + /// The sparse-directory entries of the index, with or without a trailing slash. + /// The repository's core.ignoreCase value. + public static List FindHiddenModifiedPaths( + IEnumerable modifiedPaths, + IReadOnlyList sparseDirectories, + bool ignoreCase) + { + ArgumentNullException.ThrowIfNull(modifiedPaths); + ArgumentNullException.ThrowIfNull(sparseDirectories); + + GitPathComparer comparer = GitPathComparer.GetComparer(ignoreCase); + List directories = new List(sparseDirectories.Count); + foreach (string sparseDirectory in sparseDirectories) + { + string directory = sparseDirectory == null ? string.Empty : ConePath.Normalize(sparseDirectory, out _); + if (directory.Length != 0) + { + directories.Add(directory); + } + } + + List hidden = new List(); + if (directories.Count == 0) + { + return hidden; + } + + foreach (string modifiedPath in modifiedPaths) + { + string path = modifiedPath == null ? string.Empty : ConePath.Normalize(modifiedPath, out _); + if (path.Length == 0) + { + continue; + } + + foreach (string directory in directories) + { + if (comparer.Equals(path, directory) || + comparer.IsDescendantOf(path, directory) || + (modifiedPath.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal) && comparer.IsDescendantOf(directory, path))) + { + hidden.Add(modifiedPath); + break; + } + } + } + + return hidden; + } + + /// + /// Return the first path in that the cone reaches, or + /// null. The cone reaches a file when it includes the directory of the file. The cone + /// reaches a folder (a path that ends with a slash) when it includes the folder or a + /// directory in it. + /// + public static string FindReachedPath(ConePatternSet cone, IEnumerable unsafePaths, bool ignoreCase) + { + ArgumentNullException.ThrowIfNull(cone); + ArgumentNullException.ThrowIfNull(unsafePaths); + + GitPathComparer comparer = GitPathComparer.GetComparer(ignoreCase); + foreach (string unsafePath in unsafePaths) + { + if (unsafePath == null) + { + continue; + } + + string path = ConePath.Normalize(unsafePath, out bool isFolder); + if (path.Length == 0) + { + continue; + } + + bool reached = isFolder + ? IncludesDirectoryAtOrBelow(cone, path, comparer) + : IncludesDirectory(cone, ConePath.GetParent(path), comparer); + if (reached) + { + return unsafePath; + } + } + + return null; + } + + /// Return true when the cone includes the files directly in the directory. + private static bool IncludesDirectory(ConePatternSet cone, string directory, GitPathComparer comparer) + { + if (directory.Length == 0) + { + return true; + } + + foreach (string parentOnly in cone.ParentOnlyDirectories) + { + if (comparer.Equals(parentOnly, directory)) + { + return true; + } + } + + foreach (string recursive in cone.RecursiveDirectories) + { + if (comparer.Equals(recursive, directory) || comparer.IsDescendantOf(directory, recursive)) + { + return true; + } + } + + return false; + } + + /// Return true when the cone includes the folder, or any directory in it. + private static bool IncludesDirectoryAtOrBelow(ConePatternSet cone, string folder, GitPathComparer comparer) + { + foreach (string parentOnly in cone.ParentOnlyDirectories) + { + if (comparer.Equals(parentOnly, folder) || comparer.IsDescendantOf(parentOnly, folder)) + { + return true; + } + } + + foreach (string recursive in cone.RecursiveDirectories) + { + if (comparer.Equals(recursive, folder) || + comparer.IsDescendantOf(recursive, folder) || + comparer.IsDescendantOf(folder, recursive)) + { + return true; + } + } + + return false; + } + } +} diff --git a/GVFS/GVFS.Common/Sparse/TransientConeState.cs b/GVFS/GVFS.Common/Sparse/TransientConeState.cs new file mode 100644 index 000000000..efa057900 --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/TransientConeState.cs @@ -0,0 +1,168 @@ +using System; +using System.Collections.Generic; + +namespace GVFS.Common.Sparse +{ + /// + /// The transient cone entries that Git commands added with a widen request, keyed by the + /// process id of each Git command. + /// + /// + /// A widen adds the paths of one command. The narrow of the same command removes them. The + /// cone is the union of the modified paths and the paths of every command that is still + /// listed, so two commands that need the same directory do not remove it for each other. + /// + /// A narrow can be missing (Git was stopped) or arrive before the widen that it pairs with + /// (the hook stopped its wait, and Git ended first). For the first case, the owner removes + /// the entries of processes that ended (see ). For the second case, + /// a narrow for a command without entries records the command as narrowed, and + /// then refuses its late widen. + /// + /// + /// A process id identifies a command only together with the process start time, because + /// Windows reuses process ids. A null start time means that it was not available. + /// + /// + /// This type does no I/O and is not thread safe. The owner serializes all calls. + /// + /// + public class TransientConeState + { + private readonly Dictionary commands = new Dictionary(); + private readonly Dictionary narrowedCommands = new Dictionary(); + + /// Returns whether a process still runs: (process id, start time) -> running. + public delegate bool IsProcessRunning(int processId, long? startTime); + + /// The number of commands that have transient entries. + public int CommandCount => this.commands.Count; + + /// + /// Return true when the command already sent its narrow. A start time that differs from + /// the recorded one belongs to another process with the same id. + /// + public bool IsNarrowed(int processId, long? startTime) + { + return this.narrowedCommands.TryGetValue(processId, out long? narrowedStartTime) && + IsSameProcess(narrowedStartTime, startTime); + } + + /// + /// Add the paths of a command. A repeated widen of the same command keeps the paths of + /// both requests. An entry with the same process id and another start time belongs to a + /// process that ended, so the new command replaces it. + /// + public void Add(int processId, long? startTime, IEnumerable paths) + { + ArgumentNullException.ThrowIfNull(paths); + + if (!this.commands.TryGetValue(processId, out Command command) || + !IsSameProcess(command.StartTime, startTime)) + { + command = new Command(startTime); + this.commands[processId] = command; + } + + this.narrowedCommands.Remove(processId); + foreach (string path in paths) + { + if (!string.IsNullOrEmpty(path)) + { + command.Paths.Add(path); + } + } + } + + /// + /// Remove the paths of a command. When the command has no entries and its start time is + /// known, record it as narrowed so that a late widen does not add entries that no narrow + /// removes. Without a start time, a later process with the same id cannot be told apart, + /// so nothing is recorded. + /// + /// True when the command had entries. + public bool Remove(int processId, long? startTime) + { + if (this.commands.Remove(processId)) + { + return true; + } + + if (startTime != null) + { + this.narrowedCommands[processId] = startTime; + } + + return false; + } + + /// + /// Remove the entries and the narrowed records of every process that no longer runs. + /// + /// The number of commands whose entries were removed. + public int RemoveEnded(IsProcessRunning isRunning) + { + ArgumentNullException.ThrowIfNull(isRunning); + + List ended = new List(); + foreach (KeyValuePair command in this.commands) + { + if (!isRunning(command.Key, command.Value.StartTime)) + { + ended.Add(command.Key); + } + } + + foreach (int processId in ended) + { + this.commands.Remove(processId); + } + + List endedNarrowed = new List(); + foreach (KeyValuePair narrowed in this.narrowedCommands) + { + if (!isRunning(narrowed.Key, narrowed.Value)) + { + endedNarrowed.Add(narrowed.Key); + } + } + + foreach (int processId in endedNarrowed) + { + this.narrowedCommands.Remove(processId); + } + + return ended.Count; + } + + /// The union of the paths of all commands, in no specific order. + public IEnumerable GetAllPaths() + { + HashSet union = new HashSet(StringComparer.Ordinal); + foreach (Command command in this.commands.Values) + { + union.UnionWith(command.Paths); + } + + return union; + } + + private static bool IsSameProcess(long? recordedStartTime, long? startTime) + { + // Without both start times, only the process id is known. Treat it as the same + // process: the result is a refused widen or a kept entry, which is safe. + return recordedStartTime == null || startTime == null || recordedStartTime == startTime; + } + + private class Command + { + public Command(long? startTime) + { + this.StartTime = startTime; + } + + public long? StartTime { get; } + + public HashSet Paths { get; } = new HashSet(StringComparer.Ordinal); + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs new file mode 100644 index 000000000..3d168d364 --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs @@ -0,0 +1,176 @@ +using GVFS.FunctionalTests.FileSystemRunners; +using GVFS.FunctionalTests.Tools; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; + +namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture +{ + /// + /// Functional tests for the mount's handling of the cone requests that the hooks send when + /// gvfs.auto-sparse-index is true and the index is sparse. + /// + [TestFixture] + public class AutoSparseIndexConeTests : AutoSparseIndexTestsBase + { + private const string HookFailurePrefix = "gvfs cone-management: widen not applied"; + + // Files three or more levels deep, one for each different "first/second" directory + private List deepFiles; + + // Two files in one directory that no other test uses + private string deletedFile; + private string siblingOfDeletedFile; + + [OneTimeSetUp] + public void SelectFiles() + { + List> directories = this.GroupByTwoLevelDirectory(); + directories.Count.ShouldBeAtLeast(9, "HEAD has too few directories that are two levels deep"); + this.deepFiles = directories.Take(8).Select(group => group.First()).ToList(); + + List pair = directories + .Skip(8) + .SelectMany(group => group.GroupBy(path => ParentDirectory(path), StringComparer.OrdinalIgnoreCase)) + .First(group => group.Count() >= 2) + .Take(2) + .ToList(); + this.deletedFile = pair[0]; + this.siblingOfDeletedFile = pair[1]; + } + + [TestCase] + public void GitAddWidensTheConeWithoutExpandingTheIndexAndTheConeNarrowsAfterwards() + { + string modifiedFile = this.deepFiles[0]; + string unmodifiedFile = this.deepFiles[1]; + string laterFile = this.deepFiles[2]; + string unmodifiedDirectory = TwoLevelDirectory(unmodifiedFile); + File.WriteAllText(this.Enlistment.GetVirtualPathTo(modifiedFile), "modified by the test"); + + // The command names two files outside the cone. Only the first one is modified. + ProcessResult add = this.GitWithTrace($"add -- {modifiedFile} {unmodifiedFile}", out string trace); + + add.ExitCode.ShouldEqual(0, add.Errors); + add.Errors.ShouldNotContain(ignoreCase: false, HookFailurePrefix); + CountFullIndexExpansions(trace).ShouldEqual(0, "git expanded the whole index: " + add.Errors); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(modifiedFile); + + // The cone keeps the directory of the modified file, but not the directory that the + // command only named. The index is still sparse, and it still has the entries of + // that directory until the next widen. + string cone = this.ReadConeFile(); + ConeLines(cone).ShouldContain(line => IsConeLineFor(line, TwoLevelDirectory(modifiedFile))); + ConeLines(cone).ShouldNotContain(line => IsConeLineFor(line, unmodifiedDirectory)); + this.SparseDirectoryEntries().ShouldBeNonEmpty(); + this.SparseIndexEntries().ShouldContain(entry => entry.Equals(unmodifiedFile, StringComparison.OrdinalIgnoreCase)); + + // The next widen makes the index match the cone again, so the directory collapses. + ProcessResult laterAdd = this.GitWithTrace($"add -- {laterFile}", out string laterTrace); + + laterAdd.ExitCode.ShouldEqual(0, laterAdd.Errors); + laterAdd.Errors.ShouldNotContain(ignoreCase: false, HookFailurePrefix); + CountFullIndexExpansions(laterTrace).ShouldEqual(0, "git expanded the whole index: " + laterAdd.Errors); + this.SparseIndexEntries().ShouldNotContain(entry => entry.StartsWith(unmodifiedDirectory + "/", StringComparison.OrdinalIgnoreCase) && !entry.EndsWith("/")); + this.ReadConeFile().ShouldEqual(cone); + + // Applying the cone to the index wrote no working-tree file and deleted nothing. + // GVFS records any such write or delete in the modified paths. + GVFSHelpers.ModifiedPathsShouldNotContain(this.Enlistment, FileSystemRunner.DefaultRunner, unmodifiedFile, unmodifiedDirectory + "/", laterFile); + this.GitShouldSucceed($"hash-object -- {unmodifiedFile}").Trim() + .ShouldEqual(this.GitShouldSucceed($"rev-parse HEAD:{unmodifiedFile}").Trim()); + } + + [TestCase] + public void ConcurrentGitCommandsThatNameOutOfConePathsSucceed() + { + string firstFile = this.deepFiles[3]; + string secondFile = this.deepFiles[4]; + string readOnlyFile = this.deepFiles[5]; + File.WriteAllText(this.Enlistment.GetVirtualPathTo(firstFile), "first"); + File.WriteAllText(this.Enlistment.GetVirtualPathTo(secondFile), "second"); + + // The two adds take the GVFS lock one after the other. The diff does not take the + // lock, so it can run while an add holds it. + Task firstAdd = Task.Run(() => this.GitWithTrace($"add -- {firstFile}", out _)); + Task secondAdd = Task.Run(() => this.GitWithTrace($"add -- {secondFile}", out _)); + Task diff = Task.Run(() => this.GitWithTrace($"diff --stat -- {readOnlyFile}", out _)); + Task.WaitAll(firstAdd, secondAdd, diff); + + firstAdd.Result.ExitCode.ShouldEqual(0, firstAdd.Result.Errors); + secondAdd.Result.ExitCode.ShouldEqual(0, secondAdd.Result.Errors); + diff.Result.ExitCode.ShouldEqual(0, diff.Result.Errors); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(firstFile, secondFile); + + // When all commands are done, the cone has only the modified directories. A narrow + // can reach the mount after its command ended, so the test waits for it. + string[] coneLines = this.WaitForConeFile(lines => !lines.Any(line => IsConeLineFor(line, TwoLevelDirectory(readOnlyFile)))); + coneLines.ShouldContain(line => IsConeLineFor(line, TwoLevelDirectory(firstFile))); + coneLines.ShouldContain(line => IsConeLineFor(line, TwoLevelDirectory(secondFile))); + coneLines.ShouldNotContain(line => IsConeLineFor(line, TwoLevelDirectory(readOnlyFile))); + this.SparseDirectoryEntries().ShouldBeNonEmpty(); + } + + [TestCase] + public void UnlockedCommandDoesNotChangeTheCone() + { + string file = this.deepFiles[6]; + string coneBefore = this.ReadConeFile(); + + // git diff does not take the GVFS lock, so the mount must not replace the index for it. + ProcessResult diff = this.GitWithTrace($"diff --stat -- {file}", out _); + + diff.ExitCode.ShouldEqual(0, diff.Errors); + diff.Errors.ShouldContain(HookFailurePrefix + ": Rejected"); + this.ReadConeFile().ShouldEqual(coneBefore); + } + + [TestCase] + public void WidenOfAFullIndexCollapsesTheIndex() + { + string modifiedFile = this.deepFiles[7]; + int fullEntryCount = this.GitShouldSucceed("ls-tree -r --name-only HEAD") + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Length; + + // A clone writes a full index with skip-worktree bits. Git also writes a full index when + // index.sparse is false. + this.GitShouldSucceed("-c index.sparse=false update-index --force-write-index"); + this.IndexHeaderEntryCount().ShouldEqual(fullEntryCount, "The index is not full"); + + File.WriteAllText(this.Enlistment.GetVirtualPathTo(modifiedFile), "modified by the test"); + ProcessResult add = this.GitWithTrace($"add -- {modifiedFile}", out _); + + // The mount applies the cone with its own Git process, which must write a sparse + // index. Otherwise the index stays full until a user command writes it. + add.ExitCode.ShouldEqual(0, add.Errors); + add.Errors.ShouldNotContain(ignoreCase: false, HookFailurePrefix); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(modifiedFile); + int sparseEntryCount = this.IndexHeaderEntryCount(); + (sparseEntryCount < fullEntryCount).ShouldBeTrue($"The widen did not collapse the full index: {sparseEntryCount} of {fullEntryCount} entries"); + + // The full index has an entry for the file that an earlier test deleted, so the widen + // does not expand a directory to reach it, and Git does not check it out again. + File.Exists(this.Enlistment.GetVirtualPathTo(this.deletedFile)).ShouldBeFalse("The widen restored the deleted file"); + } + + [TestCase] + public void WidenDoesNotRestoreADeletedFile() + { + File.Delete(this.Enlistment.GetVirtualPathTo(this.deletedFile)); + + ProcessResult add = this.GitWithTrace($"add -- {this.siblingOfDeletedFile}", out _); + + add.ExitCode.ShouldEqual(0, add.Errors); + + // Git expands the directory of the deleted file without a checkout. + add.Errors.ShouldNotContain(ignoreCase: false, HookFailurePrefix); + this.GitShouldSucceed("status --porcelain").ShouldContain(" D " + this.deletedFile); + File.Exists(this.Enlistment.GetVirtualPathTo(this.deletedFile)).ShouldBeFalse("The widen restored the deleted file"); + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs new file mode 100644 index 000000000..c38fd4210 --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs @@ -0,0 +1,196 @@ +using GVFS.FunctionalTests.Tools; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture +{ + /// + /// Mounts the fixture's enlistment with gvfs.auto-sparse-index on, a root-only cone, + /// and a collapsed sparse index, and has helpers for the tests of the sparse-index cone. + /// + public abstract class AutoSparseIndexTestsBase : TestsWithEnlistmentPerFixture + { + protected const string BypassGVFS = "-c core.virtualfilesystem= -c core.hookspath="; + protected const string RootOnlyCone = "/*\n!/*/\n"; + + private static readonly UTF8Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + + private int traceCount; + + /// The files of HEAD that are three or more levels deep and have no space in the path. + protected List DeepHeadFiles { get; private set; } + + protected string SparseCheckoutPath => this.Enlistment.GetDotGitPath("info", "sparse-checkout"); + + [OneTimeSetUp] + public void MountWithASparseIndex() + { + // A Git with this feature also changes only the index when the cone changes. + string buildOptions = GitProcess.Invoke(this.Enlistment.RepoRoot, "version --build-options"); + if (!buildOptions.Contains("feature: vfs-sparse-index")) + { + Assert.Ignore("This git does not support a sparse index with VFS (git version --build-options has no 'feature: vfs-sparse-index')"); + } + + this.DeepHeadFiles = this.GitShouldSucceed("-c core.quotepath=false ls-tree -r --name-only HEAD") + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Select(path => path.Trim()) + .Where(path => path.Count(character => character == '/') >= 2 && !path.Contains(' ')) + .ToList(); + + // Mount with the feature on, a root-only cone, and a collapsed index. The persisted + // projection gets the same index, as it does when git collapses the index while the + // repository is mounted. + this.Enlistment.UnmountGVFS(); + this.GitShouldSucceed("-c core.hookspath= config gvfs.auto-sparse-index true"); + this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckout true"); + this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckoutCone true"); + this.GitShouldSucceed("-c core.hookspath= config index.sparse true"); + File.WriteAllText(this.SparseCheckoutPath, RootOnlyCone, Utf8NoBom); + this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true update-index --force-write-index"); + this.SparseDirectoryEntries().ShouldBeNonEmpty(); + File.Copy(this.Enlistment.GetDotGitPath("index"), Path.Combine(this.Enlistment.DotGVFSRoot, "GVFS_projection"), overwrite: true); + this.Enlistment.MountGVFS(); + } + + protected static string[] ConeLines(string cone) + { + return cone.Split('\n'); + } + + protected static bool IsConeLineFor(string line, string directory) + { + return line.Equals("/" + directory + "/", StringComparison.OrdinalIgnoreCase); + } + + protected static string TwoLevelDirectory(string path) + { + string[] segments = path.Split('/'); + return segments[0] + "/" + segments[1]; + } + + protected static string ParentDirectory(string path) + { + return path.Substring(0, path.LastIndexOf('/')); + } + + protected static int CountFullIndexExpansions(string trace2EventFile) + { + File.Exists(trace2EventFile).ShouldBeTrue("git did not write the trace2 file " + trace2EventFile); + return File.ReadLines(trace2EventFile) + .Count(line => line.Contains("\"event\":\"region_enter\"") && line.Contains("\"label\":\"ensure_full_index\"")); + } + + /// + /// Return the entry count in the header of the index file on disk. + /// + protected int IndexHeaderEntryCount() + { + // Bytes 8 to 11 of the index file are its entry count (big-endian). A sparse-directory + // entry counts as one entry. ls-files cannot show the count on disk, because Git + // collapses a full index in memory when it reads it with index.sparse true. + byte[] header = new byte[12]; + using (FileStream stream = new FileStream(this.Enlistment.GetDotGitPath("index"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + { + stream.ReadExactly(header, 0, header.Length); + } + + return (header[8] << 24) | (header[9] << 16) | (header[10] << 8) | header[11]; + } + + /// + /// Return the files of HEAD that are three or more levels deep, grouped by their + /// two-level directory. Files of different groups are in different directories outside a + /// root-only cone. + /// + protected List> GroupByTwoLevelDirectory() + { + return this.DeepHeadFiles + .GroupBy(path => TwoLevelDirectory(path), StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + protected string[] WaitForConeFile(Func isExpected) + { + string[] lines = ConeLines(this.ReadConeFile()); + for (int attempt = 0; attempt < 100 && !isExpected(lines); attempt++) + { + System.Threading.Thread.Sleep(100); + lines = ConeLines(this.ReadConeFile()); + } + + return lines; + } + + /// + /// Read the cone file. The read lets the mount replace the file, as a read by Git does. + /// + protected string ReadConeFile() + { + for (int attempt = 0; ; attempt++) + { + try + { + using (FileStream stream = new FileStream(this.SparseCheckoutPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + using (StreamReader reader = new StreamReader(stream)) + { + return reader.ReadToEnd(); + } + } + catch (IOException) when (attempt < 10) + { + // The mount replaced the file between the lookup and the open. + System.Threading.Thread.Sleep(50); + } + } + } + + protected ProcessResult GitWithTrace(string command, out string trace2EventFile, bool takeOptionalLocks = false) + { + string traceFile = Path.Combine(this.Enlistment.EnlistmentRoot, $"cone-trace2-{System.Threading.Interlocked.Increment(ref this.traceCount)}.json"); + trace2EventFile = traceFile; + Dictionary environment = new Dictionary + { + { "GIT_TRACE", "1" }, + { "GIT_TRACE2_EVENT", traceFile }, + }; + + // The test runner turns optional locks off, so "git status" does not take the GVFS + // lock unless the test turns them on again. + if (takeOptionalLocks) + { + environment.Add("GIT_OPTIONAL_LOCKS", "1"); + } + + return GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command, environment); + } + + protected string GitShouldSucceed(string command) + { + ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command); + result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); + return result.Output; + } + + protected List SparseDirectoryEntries() + { + return this.SparseIndexEntries().Where(line => line.EndsWith("/")).ToList(); + } + + protected List SparseIndexEntries() + { + // Without the virtual file system, git sees the projected folders outside the cone. By + // default it then clears their skip-worktree bits and expands the index in memory. + return this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true -c core.quotepath=false ls-files --sparse") + .Split('\n') + .Select(line => line.Trim()) + .Where(line => line.Length > 0) + .ToList(); + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexUnstageTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexUnstageTests.cs new file mode 100644 index 000000000..350171cd3 --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexUnstageTests.cs @@ -0,0 +1,178 @@ +using GVFS.FunctionalTests.Tools; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture +{ + /// + /// Functional tests for files that "git reset --soft" stages outside the sparse-index cone. + /// No file system write stages them, so only the unstage preparation of the hook can bring + /// them into the cone before Git unstages them. + /// + [TestFixture] + public class AutoSparseIndexUnstageTests : AutoSparseIndexTestsBase + { + private const string ConeManagementPrefix = "gvfs cone-management:"; + private const string ChangedLine = "changed by a commit"; + + // Files of HEAD, each in a different two-level directory outside the root-only cone + private Queue unusedFiles; + private int headFileCount; + private int branchCount; + + [OneTimeSetUp] + public void SelectFiles() + { + this.unusedFiles = new Queue(this.GroupByTwoLevelDirectory().Select(group => group.First())); + this.unusedFiles.Count.ShouldBeAtLeast(4, "HEAD has too few directories that are two levels deep"); + this.headFileCount = this.GitShouldSucceed("ls-tree -r --name-only HEAD").Split('\n', StringSplitOptions.RemoveEmptyEntries).Length; + } + + [TestCase] + public void RestoreStagedPathKeepsTheChangeVisible() + { + this.UnstageAfterSoftResetShouldKeepTheChange(file => "restore --staged -- " + file); + } + + [TestCase] + public void RestoreStagedDotKeepsTheChangeVisible() + { + this.UnstageAfterSoftResetShouldKeepTheChange(file => "restore --staged ."); + } + + [TestCase] + public void ResetPathKeepsTheChangeVisible() + { + this.UnstageAfterSoftResetShouldKeepTheChange(file => "reset --quiet -- " + file); + } + + [TestCase] + public void ResetKeepsTheChangeVisible() + { + this.UnstageAfterSoftResetShouldKeepTheChange(file => "reset --quiet"); + } + + [TestCase("restore --staged -- ")] + [TestCase("reset --quiet -- ")] + public void UnstageKeepsUnstagedEditsOfANewFile(string unstageCommand) + { + // The unstage preparation writes the staged content of an added file that has no + // placeholder. It must not overwrite a file that the user created and edited again. + string file = $"unstage-new-file-{this.branchCount++}.txt"; + string path = this.Enlistment.GetVirtualPathTo(file); + try + { + File.WriteAllText(path, "staged\n"); + this.GitShouldSucceed("add -- " + file); + File.AppendAllText(path, "not staged\n"); + + this.GitShouldSucceed(unstageCommand + file); + + File.ReadAllText(path).ShouldEqual("staged\nnot staged\n"); + this.GitShouldSucceed("status --porcelain -- " + file).ShouldContain("?? " + file); + } + finally + { + GitProcess.InvokeProcess(this.Enlistment.RepoRoot, "reset --quiet -- " + file); + File.Delete(path); + } + } + + /// + /// Check out a commit that changes a file outside the cone, without a write to that file + /// in the working tree. Then "git reset --soft HEAD~1" stages the change, and + /// unstages it. The change must stay in the working + /// tree, and Git must report it. + /// + private void UnstageAfterSoftResetShouldKeepTheChange(Func getUnstageCommand) + { + string file = this.unusedFiles.Dequeue(); + try + { + this.UnstageAfterSoftResetShouldKeepTheChange(file, getUnstageCommand(file)); + } + finally + { + // Leave a clean working tree and index for the next test, also after a failure. + GitProcess.InvokeProcess(this.Enlistment.RepoRoot, "reset --hard --quiet"); + } + + this.GitShouldSucceed("status --porcelain").ShouldNotContain(ignoreCase: true, file); + } + + private void UnstageAfterSoftResetShouldKeepTheChange(string file, string unstageCommand) + { + this.CheckOutACommitThatChanges(file); + this.IndexOnDiskShouldBeSparse(); + ConeLines(this.ReadConeFile()) + .ShouldNotContain(line => line.StartsWith("/" + TwoLevelDirectory(file) + "/", StringComparison.OrdinalIgnoreCase)); + + ProcessResult softReset = this.GitWithTrace("reset --soft HEAD~1", out string softResetTrace); + softReset.ExitCode.ShouldEqual(0, softReset.Errors); + CountFullIndexExpansions(softResetTrace).ShouldEqual(0, "reset --soft expanded the whole index"); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(file); + + ProcessResult unstage = this.GitWithTrace(unstageCommand, out string unstageTrace); + unstage.ExitCode.ShouldEqual(0, $"git {unstageCommand} failed: {unstage.Errors}"); + unstage.Errors.ShouldNotContain(ignoreCase: false, ConeManagementPrefix + " widen not applied", ConeManagementPrefix + " apply"); + CountFullIndexExpansions(unstageTrace).ShouldEqual(0, $"git {unstageCommand} expanded the whole index: {unstage.Errors}"); + + this.GitShouldSucceed("diff --cached --name-only").ShouldNotContain(ignoreCase: true, file); + ProcessResult status = this.GitWithTrace("status --porcelain", out string statusTrace); + status.ExitCode.ShouldEqual(0, status.Errors); + status.Output.ShouldContain(" M " + file); + CountFullIndexExpansions(statusTrace).ShouldEqual(0, "status expanded the whole index"); + this.GitShouldSucceed("ls-files -v -- " + file).ShouldContain("H " + file); + File.ReadAllText(this.Enlistment.GetVirtualPathTo(file)).ShouldContain(ChangedLine); + this.IndexOnDiskShouldBeSparse(); + } + + /// + /// Create a commit on top of HEAD that adds to + /// , and check it out. The commit is made in a temporary index, so + /// the working tree and the modified paths do not see the change before the checkout. + /// + private void CheckOutACommitThatChanges(string file) + { + string changedContent = this.GitShouldSucceed("cat-file blob HEAD:" + file) + ChangedLine + "\n"; + ProcessResult hash = GitProcess.InvokeProcess( + this.Enlistment.RepoRoot, + "hash-object -w --stdin", + inputStream: new MemoryStream(Encoding.UTF8.GetBytes(changedContent))); + hash.ExitCode.ShouldEqual(0, hash.Errors); + string blob = hash.Output.Trim(); + + string temporaryIndex = Path.Combine(this.Enlistment.EnlistmentRoot, $"unstage-test-index-{this.branchCount}"); + Dictionary environment = new Dictionary { { "GIT_INDEX_FILE", temporaryIndex } }; + string plainIndex = $"{BypassGVFS} -c index.sparse=false -c core.sparseCheckout=false"; + this.GitShouldSucceed(environment, $"{plainIndex} read-tree HEAD"); + this.GitShouldSucceed(environment, $"{plainIndex} update-index --cacheinfo 100644,{blob},{file}"); + string tree = this.GitShouldSucceed(environment, $"{plainIndex} write-tree").Trim(); + File.Delete(temporaryIndex); + + string commit = this.GitShouldSucceed($"commit-tree {tree} -p HEAD -m \"Change {file}\"").Trim(); + string branch = $"tests/functional/unstage-{this.branchCount++}"; + this.GitShouldSucceed($"branch {branch} {commit}"); + this.GitShouldSucceed("checkout " + branch); + this.GitShouldSucceed("status --porcelain").ShouldNotContain(ignoreCase: true, file); + } + + private void IndexOnDiskShouldBeSparse() + { + int entryCount = this.IndexHeaderEntryCount(); + (entryCount < this.headFileCount).ShouldBeTrue($"The index on disk is full: {entryCount} of {this.headFileCount} entries"); + } + + private string GitShouldSucceed(Dictionary environment, string command) + { + ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command, environment); + result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); + return result.Output; + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexWorkingTreeTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexWorkingTreeTests.cs new file mode 100644 index 000000000..934d61a16 --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexWorkingTreeTests.cs @@ -0,0 +1,374 @@ +using GVFS.FunctionalTests.Tools; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; + +namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture +{ + /// + /// Functional tests for working-tree changes outside the sparse-index cone that no Git + /// command names: Git must see them before it reads the index. + /// + [TestFixture] + public class AutoSparseIndexWorkingTreeTests : AutoSparseIndexTestsBase + { + private const string ConeManagementPrefix = "gvfs cone-management:"; + + private static readonly Func SamePath = (first, second) => first.Equals(second, StringComparison.OrdinalIgnoreCase); + + // Files of HEAD, each in a different two-level directory outside the root-only cone + private Queue unusedFiles; + + [OneTimeSetUp] + public void SelectFiles() + { + this.unusedFiles = new Queue(this.GroupByTwoLevelDirectory().Select(group => group.First())); + this.unusedFiles.Count.ShouldBeAtLeast(18, "HEAD has too few directories that are two levels deep"); + } + + [TestCase] + public void StatusAndAddSeeFilesThatWereEditedOutsideTheCone() + { + List files = this.TakeFiles(3); + foreach (string file in files) + { + this.AppendTo(file); + } + + // This status takes the GVFS lock. The other tests run "git status" without it, as + // an editor does. + ProcessResult status = this.GitWithTrace("status --porcelain", out string statusTrace, takeOptionalLocks: true); + status.ExitCode.ShouldEqual(0, status.Errors); + ModifiedFilesIn(status.Output).ShouldContain(files, SamePath); + this.ShouldNotExpandTheIndex(status, statusTrace); + + ProcessResult add = this.GitWithTrace("add .", out string addTrace); + add.ExitCode.ShouldEqual(0, add.Errors); + this.ShouldNotExpandTheIndex(add, addTrace); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(files.ToArray()); + + this.SparseDirectoryEntries().ShouldBeNonEmpty(); + this.CommitAndCheckThatTheConeNarrows(files, "commit -m \"Edited outside the cone\""); + } + + [TestCase] + public void CommitAllIncludesFilesThatWereEditedOutsideTheCone() + { + List files = this.TakeFiles(3); + foreach (string file in files) + { + this.AppendTo(file); + } + + this.CommitAndCheckThatTheConeNarrows(files, "commit -a -m \"Edited outside the cone\""); + } + + [TestCase] + public void ConeNarrowsAfterResetHardDiscardsAnEdit() + { + string file = this.TakeFiles(1).Single(); + string directory = ParentDirectory(file); + this.AppendTo(file); + ModifiedFilesIn(this.Status()).ShouldContain(new[] { file }, SamePath); + this.ConeShouldInclude(directory); + + // The reset rebuilds the projection. The file has the content of HEAD again. + this.GitShouldSucceed("reset --hard --quiet"); + + this.WaitForConeFile(lines => !lines.Any(line => IsConeLineFor(line, directory))) + .ShouldNotContain(line => IsConeLineFor(line, directory)); + } + + [TestCase] + public void ConeNarrowsWhenACreatedFileIsIgnored() + { + string directory = ParentDirectory(this.TakeFiles(1).Single()); + string ignoredFile = directory + "/created.vfs-cone-ignored"; + File.AppendAllText(this.Enlistment.GetDotGitPath("info", "exclude"), "\n*.vfs-cone-ignored\n"); + File.WriteAllText(this.Enlistment.GetVirtualPathTo(ignoredFile), "ignored"); + + // The status applies the change. Git does not list an ignored file, so the + // check finds it clean, and the cone leaves its directory out. + this.Status().ShouldNotContain(ignoreCase: true, ignoredFile); + this.WaitForConeFile(lines => !lines.Any(line => IsConeLineFor(line, directory))) + .ShouldNotContain(line => IsConeLineFor(line, directory)); + } + + [TestCase] + public void ConeNarrowsWhenAFileHasTheContentOfHeadAgainAndWidensAtTheNextEdit() + { + string file = this.TakeFiles(1).Single(); + string directory = ParentDirectory(file); + string path = this.Enlistment.GetVirtualPathTo(file); + byte[] headContent = File.ReadAllBytes(path); + + this.AppendTo(file); + ModifiedFilesIn(this.Status()).ShouldContain(new[] { file }, SamePath); + this.ConeShouldInclude(directory); + + // The change is inside the applied cone, so no request is pending. When changes stop + // for a short time, the mount checks which modified files match HEAD. + File.WriteAllBytes(path, headContent); + ModifiedFilesIn(this.Status()).ShouldNotContain(new[] { file }, SamePath); + this.WaitForConeFile(lines => !lines.Any(line => IsConeLineFor(line, directory))) + .ShouldNotContain(line => IsConeLineFor(line, directory)); + + this.AppendTo(file); + ProcessResult status = this.GitWithTrace("status --porcelain", out string trace); + ModifiedFilesIn(status.Output).ShouldContain(new[] { file }, SamePath); + this.ShouldNotExpandTheIndex(status, trace); + this.ConeShouldInclude(directory); + } + + [TestCase] + public void UnlockedDiffSeesAFileThatWasEditedOutsideTheCone() + { + string file = this.TakeFiles(1).Single(); + this.AppendTo(file); + + // git diff does not take the GVFS lock. The hook takes it to apply the pending change. + ProcessResult diff = this.GitWithTrace("diff --name-only", out string trace); + + diff.ExitCode.ShouldEqual(0, diff.Errors); + diff.Output.Split('\n').Select(line => line.Trim()).ShouldContain(line => line.Equals(file, StringComparison.OrdinalIgnoreCase)); + this.ShouldNotExpandTheIndex(diff, trace); + this.ConeShouldInclude(ParentDirectory(file)); + } + + [TestCase] + public void AddSeesANewFileOutsideTheCone() + { + string directory = ParentDirectory(this.TakeFiles(1).Single()); + string newFile = directory + "/new-file-outside-the-cone.txt"; + File.WriteAllText(this.Enlistment.GetVirtualPathTo(newFile), "new"); + + ProcessResult add = this.GitWithTrace("add .", out string trace); + + add.ExitCode.ShouldEqual(0, add.Errors); + this.ShouldNotExpandTheIndex(add, trace); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(newFile); + this.GitShouldSucceed("reset --quiet -- " + newFile); + File.Delete(this.Enlistment.GetVirtualPathTo(newFile)); + } + + [TestCase] + public void AddSeesARenameOverSaveAfterAFolderDehydrate() + { + // An earlier change, then a folder dehydrate, which rewrites the index and the cone. + string earlierFile = this.TakeFiles(1).Single(); + this.AppendTo(earlierFile); + this.GitShouldSucceed("add -- " + earlierFile); + this.GitShouldSucceed("restore --staged --worktree -- " + earlierFile); + this.DehydrateFolder(ParentDirectory(earlierFile)); + + // An editor writes a temporary file and renames it over the file. + string file = this.TakeFiles(1).Single(); + string path = this.Enlistment.GetVirtualPathTo(file); + string temporaryPath = path + ".tmp~"; + File.WriteAllText(temporaryPath, File.ReadAllText(path) + "edited outside the cone\n"); + File.Move(temporaryPath, path, overwrite: true); + + ProcessResult add = this.GitWithTrace("add -- " + file, out string trace); + + add.ExitCode.ShouldEqual(0, add.Errors); + this.ShouldNotExpandTheIndex(add, trace); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(file); + this.GitShouldSucceed("restore --staged --worktree -- " + file); + } + + [TestCase] + public void StatusAndCommitAllSeeAFileThatWasDeletedOutsideTheCone() + { + string file = this.TakeFiles(1).Single(); + File.Delete(this.Enlistment.GetVirtualPathTo(file)); + + ProcessResult status = this.GitWithTrace("status --porcelain", out string trace); + status.ExitCode.ShouldEqual(0, status.Errors); + status.Output.ShouldContain(" D " + file); + this.ShouldNotExpandTheIndex(status, trace); + + this.GitShouldSucceed("commit -a -m \"Deleted outside the cone\""); + this.GitShouldSucceed("show --name-status --format= HEAD").ShouldContain("D\t" + file); + File.Exists(this.Enlistment.GetVirtualPathTo(file)).ShouldBeFalse("Git restored the deleted file"); + } + + [TestCase("checkout --detach")] + [TestCase("reset --merge")] + public void SwitchingCommitsKeepsOrRefusesToOverwriteChangesOutsideTheCone(string switchCommand) + { + List files = this.TakeFiles(2); + string editedFile = files[0]; + string deletedFile = files[1]; + string editedPath = this.Enlistment.GetVirtualPathTo(editedFile); + string deletedPath = this.Enlistment.GetVirtualPathTo(deletedFile); + string addedFile = ParentDirectory(editedFile) + "/added-next-to-an-edit.txt"; + string startCommit = this.GitShouldSucceed("rev-parse HEAD").Trim(); + string branch = this.GitShouldSucceed("symbolic-ref --short HEAD").Trim(); + + // The sibling commit changes the directories of both files, but not the files. The + // other commit changes the edited file. + string siblingCommit = this.CommitWithoutTheWorkingTree( + startCommit, + (addedFile, "added"), + (ParentDirectory(deletedFile) + "/added-next-to-a-delete.txt", "added")); + string overwriteCommit = this.CommitWithoutTheWorkingTree(startCommit, (editedFile, "changed by a commit")); + + this.GitShouldSucceed("checkout --detach"); + try + { + this.AppendTo(editedFile); + string editedContent = File.ReadAllText(editedPath); + File.Delete(deletedPath); + string status = this.Status(); + status.ShouldContain(" M " + editedFile, " D " + deletedFile); + + // Git keeps both changes, as it does with a full index. + ProcessResult keep = this.GitWithTrace($"{switchCommand} {siblingCommit}", out _); + keep.ExitCode.ShouldEqual(0, keep.Errors); + keep.Errors.ShouldNotContain(ignoreCase: false, ConeManagementPrefix); + this.GitShouldSucceed("rev-parse HEAD").Trim().ShouldEqual(siblingCommit); + File.Exists(this.Enlistment.GetVirtualPathTo(addedFile)).ShouldBeTrue("Git did not check out the new file of the commit"); + File.ReadAllText(editedPath).ShouldEqual(editedContent, "Git lost the edit"); + File.Exists(deletedPath).ShouldBeFalse("Git restored the deleted file"); + this.Status().ShouldContain(" M " + editedFile, " D " + deletedFile); + + // Git refuses to overwrite the edit. + ProcessResult refuse = this.GitWithTrace($"{switchCommand} {overwriteCommit}", out _); + refuse.ExitCode.ShouldNotEqual(0, "Git overwrote a file that was edited outside the cone"); + refuse.Errors.ShouldContain(editedFile); + this.GitShouldSucceed("rev-parse HEAD").Trim().ShouldEqual(siblingCommit); + File.ReadAllText(editedPath).ShouldEqual(editedContent, "Git lost the edit"); + File.Exists(deletedPath).ShouldBeFalse("Git restored the deleted file"); + } + finally + { + GitProcess.InvokeProcess(this.Enlistment.RepoRoot, $"{switchCommand} {startCommit}"); + GitProcess.InvokeProcess(this.Enlistment.RepoRoot, $"checkout {startCommit} -- {editedFile} {deletedFile}"); + GitProcess.InvokeProcess(this.Enlistment.RepoRoot, $"checkout {branch}"); + } + + this.GitShouldSucceed("status --porcelain").ShouldNotContain(ignoreCase: true, editedFile, deletedFile); + } + + private static List ModifiedFilesIn(string porcelainStatus) + { + return porcelainStatus + .Split('\n') + .Where(line => line.Length > 3) + .Select(line => line.Substring(3).Trim()) + .ToList(); + } + + private string Status() + { + ProcessResult status = this.GitWithTrace("status --porcelain", out string trace); + status.ExitCode.ShouldEqual(0, status.Errors); + this.ShouldNotExpandTheIndex(status, trace); + return status.Output; + } + + private List TakeFiles(int count) + { + List files = new List(); + for (int i = 0; i < count; i++) + { + files.Add(this.unusedFiles.Dequeue()); + } + + return files; + } + + private void AppendTo(string file) + { + File.AppendAllText(this.Enlistment.GetVirtualPathTo(file), Environment.NewLine + "edited outside the cone" + Environment.NewLine); + } + + private void DehydrateFolder(string directory) + { + ProcessStartInfo processInfo = new ProcessStartInfo(GVFSTestConfig.PathToGVFS); + processInfo.Arguments = $"dehydrate --confirm --no-status --folders {directory} {TestConstants.InternalUseOnlyFlag} {GVFSHelpers.GetInternalParameter()}"; + processInfo.WorkingDirectory = this.Enlistment.EnlistmentRoot; + processInfo.UseShellExecute = false; + processInfo.RedirectStandardOutput = true; + ProcessResult dehydrate = ProcessHelper.Run(processInfo); + dehydrate.ExitCode.ShouldEqual(0, dehydrate.Output + dehydrate.Errors); + } + + /// + /// Commit on top of with a separate + /// index and without the virtual file system, so that the working tree, the index, and the + /// cone do not change. + /// + private string CommitWithoutTheWorkingTree(string parent, params (string Path, string Content)[] files) + { + string indexFile = Path.Combine(this.Enlistment.EnlistmentRoot, "commit-" + Guid.NewGuid().ToString("N") + ".index"); + string plainGit = BypassGVFS + " -c core.sparseCheckout=false -c index.sparse=false"; + Dictionary environment = new Dictionary { { "GIT_INDEX_FILE", indexFile } }; + try + { + this.PlainGitShouldSucceed($"{plainGit} read-tree {parent}", environment); + foreach ((string path, string content) in files) + { + string blob; + using (MemoryStream input = new MemoryStream(Encoding.UTF8.GetBytes(content + "\n"))) + { + // hash-object rejects the empty paths of the other options, and it does + // not read the index. + blob = this.PlainGitShouldSucceed("hash-object -w --no-filters --stdin", environment, input).Trim(); + } + + this.PlainGitShouldSucceed($"{plainGit} update-index --add --cacheinfo 100644,{blob},{path}", environment); + } + + string tree = this.PlainGitShouldSucceed($"{plainGit} write-tree", environment).Trim(); + return this.PlainGitShouldSucceed($"{plainGit} commit-tree {tree} -p {parent} -m \"Commit beside the working tree\"", environment).Trim(); + } + finally + { + File.Delete(indexFile); + } + } + + private string PlainGitShouldSucceed(string command, Dictionary environment, Stream input = null) + { + ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command, environment, input); + result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); + return result.Output; + } + + private void ShouldNotExpandTheIndex(ProcessResult result, string trace) + { + result.Errors.ShouldNotContain(ignoreCase: false, ConeManagementPrefix + " widen not applied", ConeManagementPrefix + " apply"); + CountFullIndexExpansions(trace).ShouldEqual(0, "git expanded the whole index: " + result.Errors); + } + + private void ConeShouldInclude(string directory) + { + ConeLines(this.ReadConeFile()).ShouldContain(line => IsConeLineFor(line, directory)); + } + + private void CommitAndCheckThatTheConeNarrows(List files, string commitCommand) + { + ProcessResult commit = this.GitWithTrace(commitCommand, out string trace); + commit.ExitCode.ShouldEqual(0, commit.Errors); + this.ShouldNotExpandTheIndex(commit, trace); + List committed = this.GitShouldSucceed("show --name-only --format= HEAD") + .Split('\n') + .Select(line => line.Trim()) + .ToList(); + committed.ShouldContain(files, SamePath); + + // The committed files match HEAD, so the cone no longer needs their directories. + List directories = files.Select(ParentDirectory).ToList(); + string[] coneLines = this.WaitForConeFile(lines => !lines.Any(line => directories.Any(directory => IsConeLineFor(line, directory)))); + coneLines.ShouldNotContain(line => directories.Any(directory => IsConeLineFor(line, directory))); + this.SparseDirectoryEntries().ShouldBeNonEmpty(); + ModifiedFilesIn(this.Status()).ShouldNotContain(files, SamePath); + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs new file mode 100644 index 000000000..4812d57e3 --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs @@ -0,0 +1,85 @@ +using GVFS.FunctionalTests.Tools; +using GVFS.Tests.Should; +using NUnit.Framework; +using System.Collections.Generic; +using System.IO; +using System.Text; + +namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture +{ + /// + /// Functional tests for the cone requests that the hooks send when + /// gvfs.auto-sparse-index is true. The test turns the flag on after the mount + /// started, so the mount answers NotEnabled, and the tests check that Git still runs. + /// + [TestFixture] + public class ConeManagementHookTests : TestsWithEnlistmentPerFixture + { + private const string AutoSparseIndexConfig = "gvfs.auto-sparse-index"; + + // The parent-only directory GVFS puts the files directly in GVFS/ in the cone, but + // not the files in GVFS/GVFS.Hooks/. GVFS does not set core.sparseCheckout, so Git + // itself ignores this file. + private const string ConeWithParentOnlyGVFS = "/*\n!/*/\n/GVFS/\n!/GVFS/*/\n"; + + private const string InConeFile = "GVFS/cone-request-in-cone.txt"; + private const string OutOfConeFile = "GVFS/GVFS.Hooks/cone-request-out-of-cone.txt"; + + private static readonly Dictionary TraceEnvironment = new Dictionary + { + { "GIT_TRACE", "1" }, + }; + + [TestCase] + public void GitRunsWhenTheMountRepliesNotEnabled() + { + string sparseCheckoutPath = Path.Combine(this.Enlistment.RepoRoot, ".git", "info", "sparse-checkout"); + string originalSparseCheckout = File.Exists(sparseCheckoutPath) ? File.ReadAllText(sparseCheckoutPath) : null; + + try + { + File.WriteAllText(sparseCheckoutPath, ConeWithParentOnlyGVFS, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + GitProcess.Invoke(this.Enlistment.RepoRoot, "config --local " + AutoSparseIndexConfig + " true"); + File.WriteAllText(this.Enlistment.GetVirtualPathTo(InConeFile), "in cone"); + File.WriteAllText(this.Enlistment.GetVirtualPathTo(OutOfConeFile), "out of cone"); + + // The test runs each command in a subdirectory, so the hook must resolve the + // relative path through GIT_PREFIX to find the right cone answer. + ProcessResult inCone = GitProcess.InvokeProcess( + Path.Combine(this.Enlistment.RepoRoot, "GVFS"), + "add " + Path.GetFileName(InConeFile), + TraceEnvironment); + inCone.ExitCode.ShouldEqual(0, inCone.Errors); + inCone.Errors.ShouldContain("gvfs cone-management: widen skipped: SkippedInCone"); + + ProcessResult outOfCone = GitProcess.InvokeProcess( + Path.Combine(this.Enlistment.RepoRoot, "GVFS", "GVFS.Hooks"), + "add " + Path.GetFileName(OutOfConeFile), + TraceEnvironment); + outOfCone.ExitCode.ShouldEqual(0, outOfCone.Errors); + outOfCone.Errors.ShouldContain( + "gvfs cone-management: widen not applied: Rejected", + "gvfs cone-management: narrow not applied: Rejected"); + + GitProcess.Invoke(this.Enlistment.RepoRoot, "diff --cached --name-only") + .ShouldContain(InConeFile, OutOfConeFile); + } + finally + { + GitProcess.Invoke(this.Enlistment.RepoRoot, "config --local --unset " + AutoSparseIndexConfig); + GitProcess.Invoke(this.Enlistment.RepoRoot, "reset -q -- " + InConeFile + " " + OutOfConeFile); + File.Delete(this.Enlistment.GetVirtualPathTo(InConeFile)); + File.Delete(this.Enlistment.GetVirtualPathTo(OutOfConeFile)); + + if (originalSparseCheckout == null) + { + File.Delete(sparseCheckoutPath); + } + else + { + File.WriteAllText(sparseCheckoutPath, originalSparseCheckout); + } + } + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerTestCase/SparseIndexMountTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerTestCase/SparseIndexMountTests.cs index 626695552..35fb7a1a2 100644 --- a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerTestCase/SparseIndexMountTests.cs +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerTestCase/SparseIndexMountTests.cs @@ -1,8 +1,12 @@ using GVFS.FunctionalTests.Tools; using GVFS.Tests.Should; using NUnit.Framework; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; +using System.Security.Cryptography; +using System.Text; using System.Text.RegularExpressions; namespace GVFS.FunctionalTests.Tests.EnlistmentPerTestCase @@ -73,11 +77,103 @@ public void MountRejectsSparseIndexAndRecoveryStepsWork() File.Exists(this.Enlistment.GetVirtualPathTo(fileInCollapsedFolder)).ShouldBeTrue("Projection is missing " + fileInCollapsedFolder); } + [TestCase] + public void MountExpandsSparseIndexWhenSparseIndexSupportIsOn() + { + // A git without sparse-index support for VFS expands a sparse index when it reads it, or + // reports files under a collapsed folder as changed. + string buildOptions = GitProcess.Invoke(this.Enlistment.RepoRoot, "version --build-options"); + if (!buildOptions.Contains("feature: vfs-sparse-index")) + { + Assert.Ignore("This git does not support a sparse index with VFS (git version --build-options has no 'feature: vfs-sparse-index')"); + } + + // The expected files come from the HEAD tree, not from the working directory, so that + // the test does not create placeholders before the index collapses. + Dictionary headFiles = this.GitShouldSucceed("-c core.quotepath=false ls-tree -r HEAD") + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Select(line => line.Split('\t')) + .Where(parts => parts[0].Split(' ')[1] == "blob") + .ToDictionary(parts => parts[1].Trim(), parts => parts[0].Split(' ')[2], StringComparer.OrdinalIgnoreCase); + headFiles.Count.ShouldBeAtLeast(100, "HEAD has too few files"); + + this.Enlistment.UnmountGVFS(); + + // Turn on sparse-index support and the sparse index. The cone keeps only the files at the + // root, so git collapses every top-level folder into a sparse-directory entry when it + // writes the index. The persisted projection gets the same index, as it does when git + // collapses the index while the repository is mounted. + this.GitShouldSucceed("-c core.hookspath= config gvfs.auto-sparse-index true"); + this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckout true"); + this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckoutCone true"); + this.GitShouldSucceed("-c core.hookspath= config index.sparse true"); + File.WriteAllText(this.Enlistment.GetDotGitPath("info", "sparse-checkout"), "/*\n!/*/\n"); + this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true update-index --force-write-index"); + List collapsedFolders = this.SparseDirectoryEntries(); + collapsedFolders.ShouldBeNonEmpty(); + File.Copy(this.Enlistment.GetDotGitPath("index"), Path.Combine(this.Enlistment.DotGVFSRoot, "GVFS_projection"), overwrite: true); + + this.Enlistment.MountGVFS(); + + // Every file of HEAD is visible, and no other file is + string workingDirectory = this.Enlistment.RepoRoot; + string dotGit = Path.Combine(workingDirectory, ".git") + Path.DirectorySeparatorChar; + List projectedFiles = Directory.EnumerateFiles(workingDirectory, "*", SearchOption.AllDirectories) + .Where(path => !path.StartsWith(dotGit, StringComparison.OrdinalIgnoreCase)) + .Select(path => path.Substring(workingDirectory.Length + 1).Replace(Path.DirectorySeparatorChar, '/')) + .ToList(); + List missing = headFiles.Keys.Except(projectedFiles, StringComparer.OrdinalIgnoreCase).OrderBy(path => path, StringComparer.Ordinal).ToList(); + List extra = projectedFiles.Except(headFiles.Keys, StringComparer.OrdinalIgnoreCase).OrderBy(path => path, StringComparer.Ordinal).ToList(); + missing.ShouldBeEmpty("Files of HEAD that the mount does not project: " + string.Join(", ", missing.Take(20))); + extra.ShouldBeEmpty("Files that the mount projects, but HEAD does not have: " + string.Join(", ", extra.Take(20))); + + // Every regular file hydrates to the content of its blob in HEAD + HashSet regularFiles = new HashSet( + this.GitShouldSucceed("-c core.quotepath=false ls-tree -r HEAD") + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Where(line => line.StartsWith("100")) + .Select(line => line.Split('\t')[1].Trim()), + StringComparer.OrdinalIgnoreCase); + List wrongContent = headFiles + .Where(file => regularFiles.Contains(file.Key)) + .Where(file => BlobSha(File.ReadAllBytes(this.Enlistment.GetVirtualPathTo(file.Key))) != file.Value) + .Select(file => file.Key) + .ToList(); + wrongContent.ShouldBeEmpty("Files whose content is not the blob in HEAD: " + string.Join(", ", wrongContent.Take(20))); + + this.GitShouldSucceed("status --porcelain").ShouldEqual(string.Empty); + + // The index is still sparse, so the projection came from the sparse-directory entries + this.SparseDirectoryEntries().ShouldMatchInOrder(collapsedFolders); + } + private string GitShouldSucceed(string command, string workingDirectory = null) { ProcessResult result = GitProcess.InvokeProcess(workingDirectory ?? this.Enlistment.RepoRoot, command); result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); return result.Output; } + + private static string BlobSha(byte[] content) + { + byte[] header = Encoding.ASCII.GetBytes($"blob {content.Length}\0"); + using (SHA1 sha1 = SHA1.Create()) + { + sha1.TransformBlock(header, 0, header.Length, null, 0); + sha1.TransformFinalBlock(content, 0, content.Length); + return BitConverter.ToString(sha1.Hash).Replace("-", string.Empty).ToLowerInvariant(); + } + } + + private List SparseDirectoryEntries() + { + // Without the virtual file system, git sees the projected folders outside the cone. By + // default it then clears their skip-worktree bits and expands the index in memory. + return this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true ls-files --sparse") + .Split('\n') + .Select(line => line.Trim()) + .Where(line => line.EndsWith("/")) + .ToList(); + } } } diff --git a/GVFS/GVFS.FunctionalTests/Tests/LibGit2TreeEnumerationTests.cs b/GVFS/GVFS.FunctionalTests/Tests/LibGit2TreeEnumerationTests.cs new file mode 100644 index 000000000..6ad0c4de8 --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/LibGit2TreeEnumerationTests.cs @@ -0,0 +1,114 @@ +using GVFS.Common; +using GVFS.Common.Git; +using GVFS.Common.Tracing; +using GVFS.FunctionalTests.Tools; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using GitProcess = GVFS.FunctionalTests.Tools.GitProcess; +using ProcessResult = GVFS.FunctionalTests.Tools.ProcessResult; + +namespace GVFS.FunctionalTests.Tests +{ + /// + /// Tests with the real libgit2 (git2.dll). The + /// projection uses it to read the trees behind the sparse-directory entries of a sparse index. + /// + [TestFixture] + public class LibGit2TreeEnumerationTests + { + // "café.txt", from a \u escape so that the test does not depend on the encoding of this file + private const string NonAsciiName = "caf\u00e9.txt"; + + private string repoRoot; + private string rootTree; + private string blob; + private string emptyTree; + + [OneTimeSetUp] + public void CreateRepo() + { + this.repoRoot = Path.Combine(Path.GetTempPath(), "GVFS.LibGit2TreeEnumerationTests_" + Path.GetRandomFileName()); + Directory.CreateDirectory(this.repoRoot); + GitProcess.Invoke(this.repoRoot, "init"); + + this.blob = this.GitWithInput("hash-object -w --stdin", "hello\n"); + string script = this.GitWithInput("hash-object -w --stdin", "#!/bin/sh\n"); + this.emptyTree = this.GitWithInput("hash-object -t tree -w --stdin", string.Empty); + string subtree = this.GitWithInput("mktree", $"100644 blob {this.blob}\tb.txt\n"); + this.rootTree = this.GitWithInput( + "mktree", + $"100644 blob {this.blob}\ta.txt\n" + + $"100755 blob {script}\trun.sh\n" + + $"120000 blob {this.blob}\tlink\n" + + $"160000 commit {new string('1', 40)}\tmodule\n" + + $"040000 tree {subtree}\tsub\n" + + $"040000 tree {this.emptyTree}\tempty\n" + + $"100644 blob {this.blob}\t{NonAsciiName}\n"); + } + + [OneTimeTearDown] + public void DeleteRepo() + { + if (this.repoRoot != null) + { + RepositoryHelpers.DeleteTestDirectory(this.repoRoot); + } + } + + [TestCase] + public void EnumerateTreeReturnsEveryEntryInTreeOrder() + { + List expected = GitProcess.Invoke(this.repoRoot, "-c core.quotepath=false ls-tree " + this.rootTree) + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Select(line => line.Split('\t')) + .Select(parts => parts[0].Split(' ')[0] + " " + parts[0].Split(' ')[2] + " " + parts[1]) + .ToList(); + expected.Count.ShouldEqual(7); + + List actual = new List(); + using (LibGit2Repo repo = new LibGit2Repo(NullTracer.Instance, this.repoRoot)) + { + repo.EnumerateTree(SHA1Util.BytesFromHexString(this.rootTree), (name, objectId, fileMode) => + { + actual.Add( + Convert.ToString(fileMode, 8).PadLeft(6, '0') + " " + + SHA1Util.HexStringFromBytes(objectId.ToArray()).ToLowerInvariant() + " " + + Encoding.UTF8.GetString(name)); + }).ShouldEqual(TreeEnumerationResult.Success); + } + + actual.ShouldMatchInOrder(expected); + actual.ShouldContain(line => line.EndsWith(" " + NonAsciiName)); + } + + [TestCase] + public void EnumerateTreeReportsMissingTreeAndNonTree() + { + using (LibGit2Repo repo = new LibGit2Repo(NullTracer.Instance, this.repoRoot)) + { + int calls = 0; + TreeEntryVisitor visitor = (name, objectId, fileMode) => calls++; + + repo.EnumerateTree(SHA1Util.BytesFromHexString(new string('2', 40)), visitor).ShouldEqual(TreeEnumerationResult.MissingTree); + repo.EnumerateTree(SHA1Util.BytesFromHexString(this.blob), visitor).ShouldEqual(TreeEnumerationResult.NotTree); + repo.EnumerateTree(SHA1Util.BytesFromHexString(this.emptyTree), visitor).ShouldEqual(TreeEnumerationResult.Success); + calls.ShouldEqual(0); + } + } + + private string GitWithInput(string command, string input) + { + using (MemoryStream stream = new MemoryStream(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(input))) + { + ProcessResult result = GitProcess.InvokeProcess(this.repoRoot, command, inputStream: stream); + result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); + return result.Output.Trim(); + } + } + } +} 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.Hooks/ConeManagementHook.cs b/GVFS/GVFS.Hooks/ConeManagementHook.cs new file mode 100644 index 000000000..46545aa6b --- /dev/null +++ b/GVFS/GVFS.Hooks/ConeManagementHook.cs @@ -0,0 +1,410 @@ +using GVFS.Common; +using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading.Tasks; + +namespace GVFS.Hooks +{ + /// + /// Sends automatic sparse-index cone requests from the pre-command and post-command hooks. + /// + /// + /// When gvfs.auto-sparse-index is true and a Git command names paths outside the + /// sparse-index cone, the pre-command hook asks the mount to widen the cone before Git + /// runs. Otherwise Git expands the whole sparse index in memory to find those paths. + /// The post-command hook asks the mount to narrow the cone again. + /// + /// Cone management must never fail a Git command. Every failure, including no mount, a + /// mount that does not know the request, a slow mount, and an exception, lets Git run. + /// Git is then slower, but correct. The hook waits at most + /// to connect and send + /// a widen. After it sent a widen, it waits for the reply, at most + /// : the mount applies + /// the widen with a Git process that holds the index lock, and the user's Git must not + /// start before that process ends. + /// + /// + /// The hook knows only the paths on the command line. It does not read a + /// --pathspec-from-file file. A rebase or merge can stop on a conflict in a file + /// outside the cone, and those paths come from the commits. For these commands Git + /// expands the index, and the hook widens the cone when the user later names the path + /// (for example with git add). + /// + /// + /// All dependencies are delegates, so that unit tests can run every path without a mount, + /// a repository, or a working tree. + /// + /// + internal sealed class ConeManagementHook + { + private const string StashCommand = "stash"; + + private readonly ReadSparseIndexConfig readConfig; + private readonly Func readConeFile; + private readonly Func createPipeClient; + private readonly string hookCurrentDirectory; + private readonly Func getWorkingDirectoryRoot; + private readonly string gitPrefix; + private readonly Action trace; + + /// Reads the feature flag and core.ignoreCase. + /// + /// Returns the decoded content of the worktree's info/sparse-checkout file (see + /// ), or null when the hook cannot read it. + /// + /// Creates an unconnected client for the mount pipe. + /// The current directory of the hook process. + /// + /// Returns the root of the worktree that Git runs in, in the same form as + /// . + /// + /// The value of GIT_PREFIX, or null. + /// Writes a diagnostic message. + public ConeManagementHook( + ReadSparseIndexConfig readConfig, + Func readConeFile, + Func createPipeClient, + string hookCurrentDirectory, + Func getWorkingDirectoryRoot, + string gitPrefix, + Action trace) + { + this.readConfig = readConfig ?? throw new ArgumentNullException(nameof(readConfig)); + this.readConeFile = readConeFile ?? throw new ArgumentNullException(nameof(readConeFile)); + this.createPipeClient = createPipeClient ?? throw new ArgumentNullException(nameof(createPipeClient)); + this.hookCurrentDirectory = hookCurrentDirectory ?? throw new ArgumentNullException(nameof(hookCurrentDirectory)); + this.getWorkingDirectoryRoot = getWorkingDirectoryRoot ?? throw new ArgumentNullException(nameof(getWorkingDirectoryRoot)); + this.gitPrefix = gitPrefix; + this.trace = trace ?? (message => { }); + } + + /// + /// Reads the gvfs.auto-sparse-index flag. When it is true, also reads + /// core.ignoreCase. + /// + /// The value of the feature flag. + internal delegate bool ReadSparseIndexConfig(out bool ignoreCase); + + /// + /// If the command names paths outside the cone, ask the mount to widen the cone. Never + /// throws. + /// + /// The hook arguments. + /// + /// The maximum time to connect and send the request. If this time ends first, the hook + /// does not send the request. + /// + /// + /// The maximum time to wait for the reply after the hook sent the request. The mount + /// runs Git to apply the widen, and that Git holds the index lock. Thus the hook waits + /// for the reply, so that the user's Git does not find the index lock. + /// + public ConeRequestOutcome TrySendWiden( + string[] args, + int waitBudgetMs = NamedPipeMessages.ConeManagement.WidenWaitBudgetMs, + int replyCeilingMs = NamedPipeMessages.ConeManagement.WidenReplyCeilingMs) + { + ConeRequestOutcome outcome; + try + { + outcome = this.Widen(args, waitBudgetMs, replyCeilingMs); + } + catch (Exception e) + { + this.trace($"widen failed: {e.Message}"); + return ConeRequestOutcome.Failed; + } + + this.TraceOutcome("widen", outcome); + return outcome; + } + + /// + /// If the command names paths, ask the mount to remove the cone entries that it added + /// for this command, and wait for the reply, at most + /// in total. Never throws. + /// + /// + /// The post-command hook does not repeat the in-cone check of the pre-command hook: + /// the cone can change while Git runs, so the result could differ. A narrow for a + /// command that did not widen does nothing. A narrow only writes the cone file and does + /// not run Git, so the short budget does not let the user's Git find the index lock. + /// + public ConeRequestOutcome TrySendNarrow(string[] args, int waitBudgetMs = NamedPipeMessages.ConeManagement.NarrowWaitBudgetMs) + { + ConeRequestOutcome outcome; + try + { + outcome = this.Narrow(args, waitBudgetMs); + } + catch (Exception e) + { + this.trace($"narrow failed: {e.Message}"); + return ConeRequestOutcome.Failed; + } + + this.TraceOutcome("narrow", outcome); + return outcome; + } + + /// + /// Return the id that pairs the widen and narrow requests of one Git command: the Git + /// process id from the last --git-pid= argument, which Git appends after the + /// user's arguments. Return an empty string when it is absent or not a number. + /// + internal static string GetCommandId(string[] args) + { + if (args != null) + { + for (int i = args.Length - 1; i >= 0; i--) + { + string arg = args[i]; + if (arg != null && arg.StartsWith(GitPathspecParser.GitPidArgPrefix, StringComparison.Ordinal)) + { + string value = arg.Substring(GitPathspecParser.GitPidArgPrefix.Length); + return value.Length != 0 && NamedPipeMessages.ConeManagement.IsValidCommandId(value) + ? value + : string.Empty; + } + } + } + + return string.Empty; + } + + /// + /// Return true when GVFS manages a sparse-index cone for this worktree: the cone file is in + /// cone mode, and gvfs.auto-sparse-index is true. A widen and a narrow use the same + /// checks. + /// + public bool IsSparseIndexConeManaged() + { + return this.GetUnmanagedOutcome(out _, out _) == null; + } + + private static bool IsStash(ParsedGitCommand parsed) + { + return string.Equals(parsed.Command, StashCommand, StringComparison.Ordinal); + } + + /// + /// Return null when GVFS manages a sparse-index cone, or the outcome that ends a request + /// when it does not. + /// + private ConeRequestOutcome? GetUnmanagedOutcome(out string coneFileContent, out bool ignoreCase) + { + ignoreCase = false; + + // Check the cone file before the config. Git can use a sparse index only in cone + // mode, and a file read costs much less than the repository open that a config + // read needs. GVFS does not write a cone-mode file unless the feature is on. + coneFileContent = this.readConeFile(); + if (!ConeCoverage.HasConeHeader(coneFileContent)) + { + return ConeRequestOutcome.NoConeFile; + } + + if (!this.readConfig(out ignoreCase)) + { + return ConeRequestOutcome.FeatureDisabled; + } + + return null; + } + + private ConeRequestOutcome Widen(string[] args, int waitBudgetMs, int replyCeilingMs) + { + ParsedGitCommand parsed = GitPathspecParser.ParseHookArgs(args); + if (!parsed.NamesPaths) + { + return ConeRequestOutcome.NoPathsNamed; + } + + ConeRequestOutcome? unmanaged = this.GetUnmanagedOutcome(out string coneFileContent, out bool ignoreCase); + if (unmanaged != null) + { + return unmanaged.Value; + } + + // Measured on a large repository: git stash push with a pathspec still expanded the + // whole index after a widen, and the widen made the command slower. + if (IsStash(parsed)) + { + return ConeRequestOutcome.SkippedStash; + } + + // Git applies -C, --git-dir, and --work-tree before it runs the hook, so the hook + // does not see them. If they are present anyway, the paths belong to another + // directory or repository. + if (!string.IsNullOrEmpty(parsed.ChangeDirectory) || + !string.IsNullOrEmpty(parsed.GitDir) || + !string.IsNullOrEmpty(parsed.WorkTree)) + { + return ConeRequestOutcome.NoResolvablePaths; + } + + string workingDirectoryRoot = this.getWorkingDirectoryRoot(); + string pathspecBaseDirectory = ConePathspecResolver.GetPathspecBaseDirectory( + this.hookCurrentDirectory, + workingDirectoryRoot, + this.gitPrefix); + + IReadOnlyList paths = ConePathspecResolver.ResolveToGitPaths( + pathspecBaseDirectory, + workingDirectoryRoot, + parsed.Pathspecs); + + if (paths.Count == 0) + { + return ConeRequestOutcome.NoResolvablePaths; + } + + // When the hook cannot trust the cone file, it sends every path and the mount + // decides. + if (ConeCoverage.TryParseConeFile(coneFileContent, ignoreCase, out ConePatternSet cone)) + { + paths = new ConeCoverage(cone).GetUncoveredPaths(paths); + if (paths.Count == 0) + { + return ConeRequestOutcome.SkippedInCone; + } + } + + NamedPipeMessages.ConeManagement.WidenParameters parameters = + new NamedPipeMessages.ConeManagement.WidenParameters(GetCommandId(args), paths); + + return this.SendBounded( + NamedPipeMessages.ConeManagement.WidenRequest, + parameters.ToBody(), + waitBudgetMs, + replyCeilingMs); + } + + private ConeRequestOutcome Narrow(string[] args, int waitBudgetMs) + { + ParsedGitCommand parsed = GitPathspecParser.ParseHookArgs(args); + if (!parsed.NamesPaths) + { + return ConeRequestOutcome.NoPathsNamed; + } + + ConeRequestOutcome? unmanaged = this.GetUnmanagedOutcome(out _, out _); + if (unmanaged != null) + { + return unmanaged.Value; + } + + if (IsStash(parsed)) + { + return ConeRequestOutcome.SkippedStash; + } + + NamedPipeMessages.ConeManagement.NarrowParameters parameters = + new NamedPipeMessages.ConeManagement.NarrowParameters(GetCommandId(args)); + + return this.SendBounded( + NamedPipeMessages.ConeManagement.NarrowRequest, + parameters.ToBody(), + waitBudgetMs, + replyCeilingMs: null); + } + + private void TraceOutcome(string request, ConeRequestOutcome outcome) + { + switch (outcome) + { + case ConeRequestOutcome.NoPathsNamed: + case ConeRequestOutcome.NoConeFile: + case ConeRequestOutcome.FeatureDisabled: + case ConeRequestOutcome.Applied: + break; + + case ConeRequestOutcome.SkippedStash: + case ConeRequestOutcome.SkippedInCone: + case ConeRequestOutcome.NoResolvablePaths: + this.trace($"{request} skipped: {outcome}"); + break; + + default: + this.trace($"{request} not applied: {outcome}"); + break; + } + } + + /// + /// Connect, send the request, and read the reply on a worker task. + /// + /// The request header. + /// The request body. + /// + /// The maximum time to connect and send. If is null, + /// it also bounds the reply: the full request then takes at most this time. + /// + /// + /// If not null, the maximum time to wait for the reply after the request was sent. + /// + private ConeRequestOutcome SendBounded(string header, string body, int waitBudgetMs, int? replyCeilingMs) + { + Stopwatch stopwatch = Stopwatch.StartNew(); + object sendGate = new object(); + bool sendAbandoned = false; + bool requestSent = false; + TaskCompletionSource sending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + Task task = Task.Run(() => + { + using (NamedPipeClient pipeClient = this.createPipeClient()) + { + if (!pipeClient.Connect(NamedPipeMessages.ConeManagement.ConnectTimeoutMs, out _)) + { + return ConeRequestOutcome.MountUnavailable; + } + + // After the budget ends, the hook lets Git run. A request sent after that + // could make the mount run Git while the user's Git runs. + lock (sendGate) + { + if (sendAbandoned) + { + return ConeRequestOutcome.TimedOut; + } + + requestSent = true; + } + + sending.TrySetResult(true); + pipeClient.SendRequest(new NamedPipeMessages.Message(header, body)); + NamedPipeMessages.Message response = pipeClient.ReadResponse(); + return response.Header == NamedPipeMessages.ConeManagement.SuccessResult + ? ConeRequestOutcome.Applied + : ConeRequestOutcome.Rejected; + } + }); + + // If the hook cannot send in time, or the mount does not reply in time, abandon the + // task. The hook process exits soon after this method returns, which ends the task. + if (Task.WaitAny(new Task[] { task, sending.Task }, waitBudgetMs) < 0) + { + lock (sendGate) + { + if (!requestSent) + { + sendAbandoned = true; + return ConeRequestOutcome.TimedOut; + } + } + } + + int replyWaitMs = replyCeilingMs ?? Math.Max(0, waitBudgetMs - (int)stopwatch.ElapsedMilliseconds); + if (!task.Wait(replyWaitMs)) + { + return replyCeilingMs.HasValue ? ConeRequestOutcome.ReplyTimedOut : ConeRequestOutcome.TimedOut; + } + + return task.Result; + } + } +} diff --git a/GVFS/GVFS.Hooks/ConeRequestOutcome.cs b/GVFS/GVFS.Hooks/ConeRequestOutcome.cs new file mode 100644 index 000000000..e06ada95d --- /dev/null +++ b/GVFS/GVFS.Hooks/ConeRequestOutcome.cs @@ -0,0 +1,59 @@ +namespace GVFS.Hooks +{ + /// + /// The result of one cone-management request attempt from a hook. + /// + internal enum ConeRequestOutcome + { + /// The command names no paths, so the hook did nothing. + NoPathsNamed, + + /// The worktree has no cone-mode sparse-checkout file, so the index cannot be sparse and the hook did nothing. + NoConeFile, + + /// The gvfs.auto-sparse-index feature flag is off, so the hook did nothing. + FeatureDisabled, + + /// The command is git stash, which expands the index for any pathspec. + SkippedStash, + + /// The cone covers every named path, so a widen cannot change it. + SkippedInCone, + + /// No named path maps to a cone entry inside the worktree, so the hook did not send a widen. + NoResolvablePaths, + + /// The mount replied that it applied the request. + Applied, + + /// The hook could not connect to the mount. + MountUnavailable, + + /// The mount replied with a result other than success (for example an unknown request). + Rejected, + + /// + /// The hook could not connect and send within the wait budget, so it did not send the + /// request. For a narrow, the mount also did not reply within that budget. + /// + TimedOut, + + /// + /// The hook sent a widen or an apply, but the mount did not reply within the reply + /// ceiling. Git can then find the index lock that the mount's Git process holds. + /// + ReplyTimedOut, + + /// The request failed with an exception. + Failed, + + /// No working-tree change waits for a cone change, so the hook did nothing. + NothingPending, + + /// The command does not read the index and does not take the GVFS lock, so the hook did nothing. + NotAnIndexReader, + + /// The hook could not take the GVFS lock for a command that does not take it, so it did not send the request. + LockUnavailable, + } +} diff --git a/GVFS/GVFS.Hooks/PendingConeChangeHook.cs b/GVFS/GVFS.Hooks/PendingConeChangeHook.cs new file mode 100644 index 000000000..60d0ec3fe --- /dev/null +++ b/GVFS/GVFS.Hooks/PendingConeChangeHook.cs @@ -0,0 +1,281 @@ +using GVFS.Common.NamedPipes; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; + +namespace GVFS.Hooks +{ + /// + /// Asks the mount to apply a pending sparse-index cone change before Git reads the index. + /// + /// + /// When a working-tree change needs a directory that the index does not expand, the mount + /// creates a pending file. The file system callback that sees the change does not wait for a + /// Git command. The hook checks that file with one file-system query, so a command pays + /// nothing more when no change is pending. + /// + /// Only the Git process that holds the GVFS lock can apply a cone change. A command that + /// takes the lock holds it when this hook runs. A command that reads the index without the + /// lock (for example git diff) takes the lock for the apply, and releases it before + /// Git runs. If another Git command holds the lock, the hook does not wait, because that + /// command can be the parent of this one. The reader can then miss a change that is not + /// applied yet, as it can miss any change that a concurrent command makes. + /// + /// + /// As for the other cone requests, every failure lets Git run. When the mount replies that + /// the feature is off, or does not know the request, the hook deletes the pending file, + /// because that mount never applies the change. + /// + /// + internal sealed class PendingConeChangeHook + { + // How long the hook waits before it asks for the GVFS lock again. + private const int LockRetryDelayMs = 25; + + // The release must reach the mount, or the lock stays with the Git process until it ends. + private const int ReleaseConnectTimeoutMs = 5000; + + // After a timeout, the hook of a command without the lock still waits this long for the + // mount to finish, so that it does not release the lock while the mount changes the index. + private const int ApplyCompletionWaitMs = 60000; + + // Built-in commands that read the index or the working tree through the index and do not + // take the GVFS lock. "status" is here for "--no-optional-locks", which only checks the + // lock. A "git-" prefix means an alias or a program, which is not in this list: the Git + // commands that it runs have their own hooks. + private static readonly HashSet UnlockedIndexReaders = new HashSet(StringComparer.Ordinal) + { + "annotate", + "blame", + "cat-file", + "check-attr", + "check-ignore", + "diff", + "diff-files", + "diff-index", + "difftool", + "ls-files", + "rev-parse", + "show", + "status", + }; + + private readonly Func isPending; + private readonly Action deletePendingFile; + private readonly Func createPipeClient; + private readonly Action trace; + + /// Returns true when the mount's pending file exists. + /// Deletes the mount's pending file. + /// Creates an unconnected client for the mount pipe. + /// Writes a diagnostic message. + public PendingConeChangeHook(Func isPending, Action deletePendingFile, Func createPipeClient, Action trace) + { + this.isPending = isPending ?? throw new ArgumentNullException(nameof(isPending)); + this.deletePendingFile = deletePendingFile ?? throw new ArgumentNullException(nameof(deletePendingFile)); + this.createPipeClient = createPipeClient ?? throw new ArgumentNullException(nameof(createPipeClient)); + this.trace = trace ?? (message => { }); + } + + /// + /// If a cone change is pending, ask the mount to apply it, and wait for the reply. Never throws. + /// + /// The hook arguments. + /// True when this hook took the GVFS lock for the Git command. + /// Creates the GVFS lock request for a Git process id. + /// The longest wait for the reply. + /// The longest wait for the GVFS lock. + public ConeRequestOutcome TryApply( + string[] args, + bool holdsLock, + Func createLockRequest, + int waitBudgetMs = NamedPipeMessages.ConeManagement.WidenReplyCeilingMs, + int lockWaitBudgetMs = NamedPipeMessages.ConeManagement.WidenWaitBudgetMs) + { + ConeRequestOutcome outcome; + try + { + outcome = this.Apply(args, holdsLock, createLockRequest, waitBudgetMs, lockWaitBudgetMs); + } + catch (Exception e) + { + this.trace($"apply failed: {e.Message}"); + return ConeRequestOutcome.Failed; + } + + switch (outcome) + { + case ConeRequestOutcome.NothingPending: + case ConeRequestOutcome.NotAnIndexReader: + case ConeRequestOutcome.Applied: + break; + + default: + this.trace($"apply not applied: {outcome}"); + break; + } + + return outcome; + } + + internal static bool IsUnlockedIndexReader(string[] args) + { + return args != null && args.Length > 1 && args[1] != null && UnlockedIndexReaders.Contains(args[1]); + } + + private ConeRequestOutcome Apply(string[] args, bool holdsLock, Func createLockRequest, int waitBudgetMs, int lockWaitBudgetMs) + { + if (!this.isPending()) + { + return ConeRequestOutcome.NothingPending; + } + + string commandId = ConeManagementHook.GetCommandId(args); + if (holdsLock) + { + return this.WaitForApply(this.StartApply(commandId), waitBudgetMs); + } + + if (!IsUnlockedIndexReader(args)) + { + return ConeRequestOutcome.NotAnIndexReader; + } + + // Use the same process id as the apply request. The mount accepts the apply only + // from the process that holds the lock. + if (!int.TryParse(commandId, out int processId) || processId <= 0) + { + return ConeRequestOutcome.Failed; + } + + NamedPipeMessages.LockRequest lockRequest = createLockRequest(processId); + if (!this.TryAcquireLock(lockRequest, lockWaitBudgetMs)) + { + return ConeRequestOutcome.LockUnavailable; + } + + Task apply = null; + try + { + apply = this.StartApply(commandId); + return this.WaitForApply(apply, waitBudgetMs); + } + finally + { + // The mount can still run Git for this request. Another command must not get the + // lock until it is done, so wait for it, but not forever. + if (apply != null && !apply.IsCompleted && !apply.Wait(ApplyCompletionWaitMs)) + { + this.trace("apply still running; releasing the GVFS lock"); + } + + this.ReleaseLock(lockRequest); + } + } + + private bool TryAcquireLock(NamedPipeMessages.LockRequest lockRequest, int lockWaitBudgetMs) + { + NamedPipeMessages.Message request = lockRequest.CreateMessage(NamedPipeMessages.AcquireLock.AcquireRequest); + Stopwatch stopwatch = Stopwatch.StartNew(); + using (NamedPipeClient pipeClient = this.createPipeClient()) + { + if (!pipeClient.Connect(NamedPipeMessages.ConeManagement.ConnectTimeoutMs, out _)) + { + return false; + } + + while (true) + { + pipeClient.SendRequest(request); + NamedPipeMessages.Message reply = pipeClient.ReadResponse(); + if (reply == null) + { + return false; + } + + NamedPipeMessages.AcquireLock.Response response = new NamedPipeMessages.AcquireLock.Response(reply); + switch (response.Result) + { + case NamedPipeMessages.AcquireLock.AcceptResult: + return true; + + case NamedPipeMessages.AcquireLock.DenyGVFSResult: + // The mount is still processing working-tree changes, which can be + // the change that this command must see. Wait for it. + if (stopwatch.ElapsedMilliseconds + LockRetryDelayMs > lockWaitBudgetMs) + { + this.trace($"apply skipped: GVFS lock result {response.Result}"); + return false; + } + + Thread.Sleep(LockRetryDelayMs); + break; + + default: + this.trace($"apply skipped: GVFS lock result {response.Result}"); + return false; + } + } + } + } + + private void ReleaseLock(NamedPipeMessages.LockRequest lockRequest) + { + using (NamedPipeClient pipeClient = this.createPipeClient()) + { + if (!pipeClient.Connect(ReleaseConnectTimeoutMs, out Exception error)) + { + this.trace($"apply could not release the GVFS lock: {error?.Message}"); + return; + } + + pipeClient.SendRequest(lockRequest.CreateMessage(NamedPipeMessages.ReleaseLock.Request)); + NamedPipeMessages.Message reply = pipeClient.ReadResponse(); + if (reply?.Header != NamedPipeMessages.ReleaseLock.SuccessResult) + { + this.trace($"apply could not release the GVFS lock: {reply?.Header}"); + } + } + } + + private Task StartApply(string commandId) + { + string body = new NamedPipeMessages.ConeManagement.ApplyParameters(commandId).ToBody(); + return Task.Run(() => + { + using (NamedPipeClient pipeClient = this.createPipeClient()) + { + if (!pipeClient.Connect(NamedPipeMessages.ConeManagement.ConnectTimeoutMs, out _)) + { + return ConeRequestOutcome.MountUnavailable; + } + + pipeClient.SendRequest(new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.ApplyRequest, body)); + string result = pipeClient.ReadResponse()?.Header; + switch (result) + { + case NamedPipeMessages.ConeManagement.SuccessResult: + return ConeRequestOutcome.Applied; + + case NamedPipeMessages.ConeManagement.NotEnabledResult: + case NamedPipeMessages.UnknownRequest: + // This mount never applies the change, so the file is stale. + this.deletePendingFile(); + return result == NamedPipeMessages.UnknownRequest ? ConeRequestOutcome.Rejected : ConeRequestOutcome.FeatureDisabled; + + default: + return ConeRequestOutcome.Rejected; + } + } + }); + } + + private ConeRequestOutcome WaitForApply(Task apply, int waitBudgetMs) + { + // If the mount does not reply in time, Git runs, as after the widen reply ceiling. + return apply.Wait(waitBudgetMs) ? apply.Result : ConeRequestOutcome.ReplyTimedOut; + } + } +} diff --git a/GVFS/GVFS.Hooks/PreCommandConeRequests.cs b/GVFS/GVFS.Hooks/PreCommandConeRequests.cs new file mode 100644 index 000000000..be52aa7a9 --- /dev/null +++ b/GVFS/GVFS.Hooks/PreCommandConeRequests.cs @@ -0,0 +1,101 @@ +using System; + +namespace GVFS.Hooks +{ + /// + /// Sends the requests of the pre-command hook that prepare the index before Git reads it: + /// the cone widen, the unstage preparation, and the apply of a pending cone change. + /// + /// + /// + /// The order matters for an unstage command (for example git restore --staged or + /// git reset). The mount finds the staged files with git diff --cached. Git + /// does not match a pathspec with a path inside a sparse-directory entry, so before the + /// widen that query finds no staged file for a named path outside the cone. Thus the widen + /// comes first. + /// + /// + /// The unstage preparation adds the staged files to the modified paths. When the cone does + /// not include one of them (for example for git restore --staged ., which names no + /// path that the widen can use), the mount makes a cone change pending. The apply then + /// expands its directory before Git runs. Otherwise Git keeps the file inside a + /// sparse-directory entry, the file keeps skip-worktree, and Git does not report the + /// unstaged change. + /// + /// + /// For other commands, a failed request only makes Git slower, so Git always runs. For an + /// unstage command, a widen that timed out or an apply that failed can hide the unstaged + /// change, so the hook must stop the command (see ). + /// + /// + /// All dependencies are delegates, so that unit tests can check the order without a mount. + /// + /// + internal static class PreCommandConeRequests + { + /// True when the command unstages files. + /// Returns true when the mount's pending file exists. + /// Asks the mount to widen the cone for the named paths. + /// Asks the mount to add the staged files to the modified paths. + /// Asks the mount to apply the pending cone change. + /// + /// The request that makes an unstage command unsafe, or null when Git can run. Always + /// null for other commands. + /// + public static string Send( + bool isUnstage, + Func isConeChangePending, + Func sendWiden, + Action sendPrepareForUnstage, + Func applyPendingConeChange) + { + ArgumentNullException.ThrowIfNull(isConeChangePending); + ArgumentNullException.ThrowIfNull(sendWiden); + ArgumentNullException.ThrowIfNull(sendPrepareForUnstage); + ArgumentNullException.ThrowIfNull(applyPendingConeChange); + + // Check before the widen: a widen that the mount applied also applied the pending change. + bool pending = isConeChangePending(); + ConeRequestOutcome widenOutcome = sendWiden(); + + if (!isUnstage) + { + if (pending && widenOutcome != ConeRequestOutcome.Applied) + { + applyPendingConeChange(); + } + + return null; + } + + // After a timeout, the mount can still change the cone and the index. The staged-file + // query and Git can then see an index that does not have the named paths yet. + if (widenOutcome == ConeRequestOutcome.TimedOut) + { + return "widen: " + widenOutcome; + } + + sendPrepareForUnstage(); + + // The preparation can make a cone change pending. The mount deletes the pending file + // when it applies a change, so after an applied widen the file exists only for a + // change that the preparation made. + if (!isConeChangePending()) + { + return null; + } + + ConeRequestOutcome applyOutcome = applyPendingConeChange(); + switch (applyOutcome) + { + case ConeRequestOutcome.Applied: + case ConeRequestOutcome.NothingPending: + case ConeRequestOutcome.FeatureDisabled: + return null; + + default: + return "apply: " + applyOutcome; + } + } + } +} diff --git a/GVFS/GVFS.Hooks/Program.ConeManagement.cs b/GVFS/GVFS.Hooks/Program.ConeManagement.cs new file mode 100644 index 000000000..334570bf9 --- /dev/null +++ b/GVFS/GVFS.Hooks/Program.ConeManagement.cs @@ -0,0 +1,255 @@ +using GVFS.Common; +using GVFS.Common.Git; +using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; +using GVFS.Common.Tracing; +using GVFS.Hooks.HooksPlatform; +using GVFS.Platform.Windows; +using System; +using System.IO; + +namespace GVFS.Hooks +{ + /// + /// Automatic sparse-index cone management. See . + /// + public partial class Program + { + private const string GitPrefixEnvironmentVariable = "GIT_PREFIX"; + + // A cone file larger than this is not read. The hook then does not widen, and Git + // expands the index for the command. + private const long MaxConeFileBytes = 16 * 1024 * 1024; + + // True when the pre-command hook took the GVFS lock for the Git command. + private static bool commandHoldsGVFSLock; + + private static ConeRequestOutcome TrySendConeWiden(string[] args) + { + try + { + return CreateConeManagementHook().TrySendWiden(args); + } + catch (Exception e) + { + TraceConeDiagnostic($"widen failed: {e.Message}"); + return ConeRequestOutcome.Failed; + } + } + + /// + /// Before Git reads the index, make sure that the cone includes every working-tree change + /// that the mount saw. See for when the hook calls this. + /// + private static ConeRequestOutcome TryApplyPendingConeChange(string[] args) + { + try + { + return new PendingConeChangeHook(IsConeChangePending, DeleteConeChangePendingFile, () => new NamedPipeClient(enlistmentPipename), TraceConeDiagnostic) + .TryApply( + args, + commandHoldsGVFSLock, + processId => new NamedPipeMessages.LockRequest( + processId, + GVFSHooksPlatform.IsElevated(), + checkAvailabilityOnly: false, + GenerateFullCommand(args), + GetGitCommandSessionId())); + } + catch (Exception e) + { + TraceConeDiagnostic($"apply failed: {e.Message}"); + return ConeRequestOutcome.Failed; + } + } + + /// + /// Return true when the mount's pending file exists (see + /// ). When nothing is pending, this + /// is the only cost that cone management adds to a command that names no paths. + /// + private static bool IsConeChangePending() + { + try + { + return File.Exists(GetConeChangePendingPath()); + } + catch (Exception e) + { + TraceConeDiagnostic($"cannot check for a pending cone change: {e.Message}"); + return false; + } + } + + private static void DeleteConeChangePendingFile() + { + try + { + File.Delete(GetConeChangePendingPath()); + } + catch (Exception e) + { + TraceConeDiagnostic($"cannot delete the pending cone change file: {e.Message}"); + } + } + + private static string GetConeChangePendingPath() + { + string dotGVFSRoot = currentWorktreeInfo != null + ? Path.Combine(currentWorktreeInfo.WorktreeGitDir, WindowsPlatform.DotGVFSRoot) + : Path.Combine(enlistmentRoot, WindowsPlatform.DotGVFSRoot); + return Path.Combine(dotGVFSRoot, GVFSConstants.DotGVFS.ConeChangePending); + } + + private static void TrySendConeNarrow(string[] args) + { + try + { + CreateConeManagementHook().TrySendNarrow(args); + } + catch (Exception e) + { + TraceConeDiagnostic($"narrow failed: {e.Message}"); + } + } + + /// + /// Return true when GVFS manages a sparse-index cone for this worktree. See + /// . + /// + private static bool IsSparseIndexConeManaged() + { + try + { + return CreateConeManagementHook().IsSparseIndexConeManaged(); + } + catch (Exception e) + { + TraceConeDiagnostic($"cannot check for a sparse-index cone: {e.Message}"); + return false; + } + } + + private static ConeManagementHook CreateConeManagementHook() + { + return new ConeManagementHook( + ReadAutoSparseIndexConfig, + ReadConeFile, + () => new NamedPipeClient(enlistmentPipename), + normalizedCurrentDirectory, + GetConeWorkingDirectoryRoot, + Environment.GetEnvironmentVariable(GitPrefixEnvironmentVariable), + TraceConeDiagnostic); + } + + private static bool ReadAutoSparseIndexConfig(out bool ignoreCase) + { + ignoreCase = false; + try + { + using (LibGit2Repo repo = new LibGit2Repo(NullTracer.Instance, normalizedCurrentDirectory, GitConfigReadRetry.Delay, ConfigReadMaxAttempts)) + { + // GetConfigBool throws for an unreadable or non-boolean value, so that the + // catch below can trace it. + if (!(repo.GetConfigBool(GVFSConstants.GitConfig.AutoSparseIndex) ?? GVFSConstants.GitConfig.AutoSparseIndexDefault)) + { + return false; + } + + ignoreCase = repo.GetConfigBool(GitConfigSetting.CoreIgnoreCaseName) ?? false; + return true; + } + } + catch (Exception e) + { + TraceConeDiagnostic($"cannot read {GVFSConstants.GitConfig.AutoSparseIndex}: {e.Message}"); + return GVFSConstants.GitConfig.AutoSparseIndexDefault; + } + } + + /// + /// Return the worktree root in the same form as , + /// so that the pathspec resolver can compare the two. + /// + private static string GetConeWorkingDirectoryRoot() + { + string root = currentWorktreeInfo != null + ? currentWorktreeInfo.WorktreePath + : Path.Combine(enlistmentRoot, GVFSConstants.WorkingDirectoryRootName); + + return GVFSHooksPlatform.TryGetNormalizedPath(root, out string normalizedRoot, out _) ? normalizedRoot : root; + } + + private static string ReadConeFile() + { + string sparseCheckoutPath = SparseCheckoutPathResolver.GetSparseCheckoutFilePath( + isWorktree: currentWorktreeInfo != null, + dotGitRoot: Path.Combine(enlistmentRoot, GVFSConstants.WorkingDirectoryRootName, GVFSConstants.DotGit.Root), + worktreeGitDir: currentWorktreeInfo?.WorktreeGitDir); + + try + { + // Open the file once, and read at most one byte more than the limit, so that a + // file that changes after the attribute check cannot make the read unbounded. + FileInfo file = new FileInfo(sparseCheckoutPath); + if (!file.Exists) + { + return null; + } + + if ((file.Attributes & (FileAttributes.ReparsePoint | FileAttributes.Device)) != 0) + { + TraceConeDiagnostic($"cone file not read: {sparseCheckoutPath} is not a regular file"); + return null; + } + + using (FileStream stream = new FileStream(sparseCheckoutPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + using (MemoryStream content = new MemoryStream()) + { + byte[] buffer = new byte[64 * 1024]; + int read; + while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) + { + content.Write(buffer, 0, read); + if (content.Length > MaxConeFileBytes) + { + TraceConeDiagnostic($"cone file not read: {sparseCheckoutPath} is larger than {MaxConeFileBytes} bytes"); + return null; + } + } + + return ConeCoverage.DecodeConeFile(content.ToArray()); + } + } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) + { + TraceConeDiagnostic($"cone file not read: {e.Message}"); + return null; + } + } + + /// + /// Write a cone-management diagnostic to stderr, but only when GIT_TRACE sends Git's own + /// trace output to stderr (1, 2, or true). Then a skipped request is distinct from a + /// failed one, and the hook writes nothing in normal use. + /// + private static void TraceConeDiagnostic(string message) + { + string gitTrace = Environment.GetEnvironmentVariable("GIT_TRACE"); + if (!string.Equals(gitTrace, "1", StringComparison.Ordinal) && + !string.Equals(gitTrace, "2", StringComparison.Ordinal) && + !string.Equals(gitTrace, "true", StringComparison.OrdinalIgnoreCase)) + { + return; + } + + try + { + Console.Error.WriteLine($"gvfs cone-management: {message}"); + } + catch (IOException) + { + } + } + } +} diff --git a/GVFS/GVFS.Hooks/Program.Unstage.cs b/GVFS/GVFS.Hooks/Program.Unstage.cs index bebe9b9a9..60818cd53 100644 --- a/GVFS/GVFS.Hooks/Program.Unstage.cs +++ b/GVFS/GVFS.Hooks/Program.Unstage.cs @@ -5,7 +5,7 @@ namespace GVFS.Hooks { /// /// Partial class for unstage-related pre-command handling. - /// Detects "restore --staged" and "checkout HEAD --" operations and sends + /// Detects "restore --staged", "checkout HEAD --", and mixed "reset" operations, and sends /// a PrepareForUnstage message to the GVFS mount process so it can add /// staged files to ModifiedPaths before git clears skip-worktree. /// @@ -98,7 +98,7 @@ private static void SendPrepareForUnstageMessage(string command, string[] args) "", "To resolve:", " 1. Run 'gvfs unmount' and 'gvfs mount' to reset the GVFS state", - " 2. Retry the restore --staged command", + " 2. Retry the unstage command", "If the problem persists, run 'gvfs repair' or re-clone the enlistment."); } } diff --git a/GVFS/GVFS.Hooks/Program.cs b/GVFS/GVFS.Hooks/Program.cs index 339e73e69..773a1c56f 100644 --- a/GVFS/GVFS.Hooks/Program.cs +++ b/GVFS/GVFS.Hooks/Program.cs @@ -25,6 +25,7 @@ public partial class Program private static string enlistmentRoot; private static string enlistmentPipename; private static string normalizedCurrentDirectory; + private static GVFSEnlistment.WorktreeInfo currentWorktreeInfo; private static Random random = new Random(); private delegate void LockRequestDelegate(bool unattended, string[] args, int pid, NamedPipeClient pipeClient); @@ -70,7 +71,8 @@ public static void Main(string[] args) // If running inside a worktree, append a worktree-specific // suffix to the pipe name so hooks communicate with the // correct GVFS mount instance. - string worktreeSuffix = GVFSEnlistment.GetWorktreePipeSuffix(normalizedCurrentDirectory); + currentWorktreeInfo = GVFSEnlistment.TryGetWorktreeInfo(normalizedCurrentDirectory); + string worktreeSuffix = currentWorktreeInfo?.PipeSuffix; if (worktreeSuffix != null) { enlistmentPipename += worktreeSuffix; @@ -109,6 +111,7 @@ public static void Main(string[] args) private static void RunPreCommands(string[] args) { string command = GetGitCommand(args); + bool isUnstage = false; switch (command) { case "fetch": @@ -125,15 +128,29 @@ private static void RunPreCommands(string[] args) break; case "restore": case "checkout": - if (UnstageCommandParser.IsUnstageOperation(command, args)) - { - SendPrepareForUnstageMessage(command, args); - } + case "reset": + isUnstage = UnstageCommandParser.ShouldPrepareForUnstage(command, args, IsSparseIndexConeManaged); break; case "worktree": RunWorktreePreCommand(args); break; } + + string unsafeRequest = PreCommandConeRequests.Send( + isUnstage, + IsConeChangePending, + () => TrySendConeWiden(args), + () => SendPrepareForUnstageMessage(command, args), + () => TryApplyPendingConeChange(args)); + + if (unsafeRequest != null) + { + ExitWithError( + "VFS for Git could not add the staged files to the sparse-index cone (" + unsafeRequest + ").", + "Without them in the cone, Git would not show the changes that this command unstages.", + "", + "Run the command again. If it fails again, run 'gvfs unmount' and 'gvfs mount', and then run it again."); + } } private static bool ArgsBlockHydrationStatus(string[] args) @@ -154,6 +171,8 @@ private static void RunPostCommands(string[] args) RunWorktreePostCommand(args); break; } + + TrySendConeNarrow(args); } private static string ResolvePath(string path) @@ -395,6 +414,8 @@ private static void AcquireGVFSLockForProcess(bool unattended, string[] args, in { ExitWithError(result); } + + commandHoldsGVFSLock = !checkGvfsLockAvailabilityOnly; } private static void ReleaseGVFSLock(bool unattended, string[] args, int pid, NamedPipeClient pipeClient) diff --git a/GVFS/GVFS.Hooks/UnstageCommandParser.cs b/GVFS/GVFS.Hooks/UnstageCommandParser.cs index d03761821..746082582 100644 --- a/GVFS/GVFS.Hooks/UnstageCommandParser.cs +++ b/GVFS/GVFS.Hooks/UnstageCommandParser.cs @@ -30,13 +30,52 @@ public class PathspecResult public bool Failed { get; set; } } + /// + /// Return true when the pre-command hook must send PrepareForUnstage for this command. + /// + /// + /// With a full index, Git prepares the files of a mixed reset itself (it clears + /// skip-worktree and writes missing files under a virtual file system). With a sparse + /// index, Git can do that only for a path that has its own index entry, so the cone must + /// include the staged files first. Thus a reset needs the preparation only when GVFS + /// manages a sparse-index cone. A reset whose pathspecs the hook cannot read (for example + /// --pathspec-from-file=-) runs without the preparation, as before. + /// + /// Returns true when GVFS manages a sparse-index cone. + public static bool ShouldPrepareForUnstage(string command, string[] args, Func isSparseIndexConeManaged) + { + if (!IsUnstageOperation(command, args)) + { + return false; + } + + if (command != "reset") + { + return true; + } + + return !GetRestorePathspec(command, args).Failed && isSparseIndexConeManaged(); + } + /// /// Detects whether the git command is an unstage operation that may need /// special handling for VFS projections. - /// Matches: "restore --staged", "restore -S", "checkout HEAD --" + /// Matches: "restore --staged", "restore -S", "checkout HEAD --", and a mixed + /// "reset" (not --soft, --hard, --merge, --keep, or the interactive --patch) /// public static bool IsUnstageOperation(string command, string[] args) { + if (command == "reset") + { + return !args.Any(arg => + arg == "--soft" || + arg == "--hard" || + arg == "--merge" || + arg == "--keep" || + arg == "--patch" || + arg == "-p"); + } + if (command == "restore") { return args.Any(arg => @@ -63,13 +102,17 @@ public static bool IsUnstageOperation(string command, string[] args) } /// - /// Extracts pathspec arguments from a restore/checkout unstage command. + /// Extracts pathspec arguments from a restore/checkout/reset unstage command. /// Returns a containing either inline pathspecs, /// a --pathspec-from-file reference, or a failure indicator. /// /// When --pathspec-from-file is specified, the file path is returned so the /// caller can forward it through IPC to the mount process, which passes it /// to git diff --cached --pathspec-from-file. + /// + /// For reset, the argument before "--" is the tree-ish. Without "--", only + /// "HEAD" is taken as the tree-ish, and any other argument is a pathspec. An + /// extra pathspec only adds staged files to ModifiedPaths. /// public static PathspecResult GetRestorePathspec(string command, string[] args) { @@ -78,6 +121,8 @@ public static PathspecResult GetRestorePathspec(string command, string[] args) bool pastDashDash = false; bool skipNext = false; bool isCheckout = command == "checkout"; + bool isReset = command == "reset"; + bool resetHasDashDash = isReset && args.Skip(2).Contains("--"); // For checkout, the first non-option arg before -- is the tree-ish (e.g. HEAD), // not a pathspec. Track whether we've consumed it. @@ -136,7 +181,7 @@ public static PathspecResult GetRestorePathspec(string command, string[] args) if (!pastDashDash && arg.StartsWith("-")) { // For restore: --source and -s take a following argument - if (!isCheckout && + if (command == "restore" && (arg == "--source" || arg == "-s")) { skipNext = true; @@ -152,6 +197,13 @@ public static PathspecResult GetRestorePathspec(string command, string[] args) continue; } + if (isReset && !pastDashDash && !treeishConsumed && + (resetHasDashDash || arg == "HEAD")) + { + treeishConsumed = true; + continue; + } + paths.Add(arg); } diff --git a/GVFS/GVFS.Mount/InProcessMount.cs b/GVFS/GVFS.Mount/InProcessMount.cs index 0f6c1d096..41f9cb0db 100644 --- a/GVFS/GVFS.Mount/InProcessMount.cs +++ b/GVFS/GVFS.Mount/InProcessMount.cs @@ -6,6 +6,7 @@ using GVFS.Common.Maintenance; using GVFS.Common.NamedPipes; using GVFS.Common.Prefetch; +using GVFS.Common.Sparse; using GVFS.Common.Tracing; using GVFS.PlatformLoader; using GVFS.Virtualization; @@ -52,6 +53,10 @@ public class InProcessMount private readonly string primaryEnlistmentId; private FileSystemCallbacks fileSystemCallbacks; + + // Handles cone widen and narrow requests. Null when gvfs.auto-sparse-index was false + // when the projection was created. + private AutoSparseIndexConeManager coneManager; private GVFSDatabase gvfsDatabase; private GVFSEnlistment enlistment; private ITracer tracer; @@ -944,6 +949,12 @@ private void HandleRequest(ITracer tracer, string request, NamedPipeServer.Conne this.HandleGetHydrationStatusRequest(connection); break; + case NamedPipeMessages.ConeManagement.WidenRequest: + case NamedPipeMessages.ConeManagement.NarrowRequest: + case NamedPipeMessages.ConeManagement.ApplyRequest: + this.HandleConeRequest(message, connection); + break; + default: EventMetadata metadata = new EventMetadata(); metadata.Add("Area", "Mount"); @@ -986,6 +997,15 @@ private void HandleGetHydrationStatusRequest(NamedPipeServer.Connection connecti new NamedPipeMessages.Message(NamedPipeMessages.HydrationStatus.SuccessResult, response.ToBody(info))); } + private void HandleConeRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection) + { + string result = this.currentState == MountState.Ready + ? AutoSparseIndexConeManager.HandleRequest(this.coneManager, this.tracer, message) + : NamedPipeMessages.MountNotReadyResult; + + connection.TrySendResponse(result); + } + private void HandleDehydrateFolders(NamedPipeMessages.Message message, NamedPipeServer.Connection connection) { NamedPipeMessages.DehydrateFolders.Request request = NamedPipeMessages.DehydrateFolders.Request.FromMessage(message); @@ -1167,6 +1187,9 @@ private void HandleReleaseLockRequest(string messageBody, NamedPipeServer.Connec if (response.Result == NamedPipeMessages.ReleaseLock.SuccessResult) { this.tracer.SetGitCommandSessionId(string.Empty); + + // The command can have committed or restored modified files. + this.coneManager?.OnGitCommandCompleted(); } connection.TrySendResponse(response.CreateMessage()); @@ -1208,9 +1231,10 @@ private void HandlePostIndexChangedRequest(NamedPipeMessages.Message message, Na /// /// Handles a request to prepare for an unstage operation (e.g., restore --staged). - /// Finds index entries that are staged (not in HEAD) with skip-worktree set and adds - /// them to ModifiedPaths so that git will clear skip-worktree and process them. - /// Also forces a projection update to fix stale placeholders for modified/deleted files. + /// Runs git diff --cached for the request's pathspecs and adds the staged files to + /// ModifiedPaths so that git will clear skip-worktree and process them. With a + /// sparse index, a staged file that the cone does not include makes a cone change + /// pending, which the hook applies before git runs. /// private void HandlePrepareForUnstageRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection) { @@ -1760,15 +1784,93 @@ private void MountAndStartWorkingDirectoryCallbacks(CacheServerInfo cache, bool // The message tells the user how to recover. GitIndexProjection already logged the stack trace. this.FailMountAndExit("Error: {0}", e.Message); } + catch (SparseIndexExpansionException e) + { + // The message tells the user what to do next. GitIndexProjection already logged the stack trace. + this.FailMountAndExit("Error: {0}", e.Message); + } catch (Exception e) { this.FailMountAndExit("Failed to initialize src folder callbacks. {0}", e.ToString()); } + this.coneManager = this.CreateConeManagerIfEnabled(); + if (this.coneManager != null) + { + this.fileSystemCallbacks.SetWorkingDirectoryChangeObserver(this.coneManager); + this.coneManager.Start(); + } + else + { + // A pending file from an earlier mount with the feature on would make every hook + // send a request that this mount does not apply. + this.DeleteConeChangePendingFile(); + } + this.heartbeat = new HeartbeatThread(this.tracer, this.fileSystemCallbacks); this.heartbeat.Start(); } + private void DeleteConeChangePendingFile() + { + string pendingFilePath = MountConeManagerEnvironment.GetPendingFilePath(this.enlistment); + if (!this.context.FileSystem.TryDeleteFile(pendingFilePath, out Exception error) && error != null) + { + EventMetadata metadata = new EventMetadata(); + metadata.Add("Area", "Mount"); + metadata.Add("Exception", error.ToString()); + this.tracer.RelatedWarning(metadata, nameof(this.DeleteConeChangePendingFile) + " failed"); + } + } + + private AutoSparseIndexConeManager CreateConeManagerIfEnabled() + { + // Use the value that the projection read, so that the mount never makes the index + // sparser than the projection can parse. + if (!this.fileSystemCallbacks.GitIndexProjection.IsSparseIndexSupportEnabled) + { + return null; + } + + // Without these settings, "git sparse-checkout reapply" fails or writes a full index. + if (!this.context.Repository.GetConfigBoolOrDefault(GitConfigSetting.CoreSparseCheckoutName, defaultValue: false) || + !this.context.Repository.GetConfigBoolOrDefault(GitConfigSetting.IndexSparseName, defaultValue: false)) + { + EventMetadata metadata = new EventMetadata(); + metadata.Add("Area", "Mount"); + metadata.Add( + TracingConstants.MessageKey.WarningMessage, + $"{GVFSConstants.GitConfig.AutoSparseIndex} is true, but {GitConfigSetting.CoreSparseCheckoutName} or {GitConfigSetting.IndexSparseName} is not true. The mount does not change the sparse-checkout cone."); + this.tracer.RelatedEvent(EventLevel.Warning, nameof(this.CreateConeManagerIfEnabled), metadata, Keywords.Telemetry); + return null; + } + + // A Git without the feature runs "git sparse-checkout reapply" but leaves a full index + // full, so the cone change would not make the index smaller. + GitProcess.Result buildOptions = new GitProcess(this.enlistment).VersionBuildOptions(); + if (!AutoSparseIndexConeManager.GitSupportsSparseIndex(buildOptions)) + { + EventMetadata metadata = new EventMetadata(); + metadata.Add("Area", "Mount"); + metadata.Add("GitBinPath", this.enlistment.GitBinPath); + metadata.Add("ExitCode", buildOptions.ExitCode); + metadata.Add( + TracingConstants.MessageKey.WarningMessage, + $"{GVFSConstants.GitConfig.AutoSparseIndex} is true, but 'git version --build-options' does not show '{AutoSparseIndexConeManager.SparseIndexFeature}'. The mount does not change the sparse-checkout cone."); + this.tracer.RelatedEvent(EventLevel.Warning, nameof(this.CreateConeManagerIfEnabled), metadata, Keywords.Telemetry); + return null; + } + + string sparseCheckoutPath = SparseCheckoutPathResolver.GetSparseCheckoutFilePath(this.enlistment); + bool ignoreCase = this.context.Repository.GetConfigBoolOrDefault(GitConfigSetting.CoreIgnoreCaseName, defaultValue: false); + return new AutoSparseIndexConeManager( + this.tracer, + this.context.FileSystem, + sparseCheckoutPath, + ignoreCase, + new MountConeManagerEnvironment(this.context, this.fileSystemCallbacks, sparseCheckoutPath)); + } + private void ValidateGitVersion() { GitVersion gitVersion = null; @@ -2197,6 +2299,13 @@ private void UnmountAndStopWorkingDirectoryCallbacks(bool willRemountInSameProce this.heartbeat = null; } + if (this.coneManager != null) + { + this.fileSystemCallbacks?.SetWorkingDirectoryChangeObserver(null); + this.coneManager.Stop(); + this.coneManager = null; + } + if (this.fileSystemCallbacks != null) { this.fileSystemCallbacks.Stop(); diff --git a/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs b/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs new file mode 100644 index 000000000..d6f200fcb --- /dev/null +++ b/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs @@ -0,0 +1,197 @@ +using GVFS.Common; +using GVFS.Common.Git; +using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; +using GVFS.Virtualization; +using System; +using System.Collections.Generic; +using System.IO; + +namespace GVFS.Mount +{ + /// + /// The mount services that uses. + /// + internal class MountConeManagerEnvironment : IConeManagerEnvironment + { + // The background check stops Git after this long. The cone then keeps the files. + private const int ListPathsTimeoutMs = 2 * 60 * 1000; + + private readonly GVFSContext context; + private readonly FileSystemCallbacks fileSystemCallbacks; + private readonly string coneFileLockPath; + private readonly string pendingFilePath; + + public MountConeManagerEnvironment(GVFSContext context, FileSystemCallbacks fileSystemCallbacks, string sparseCheckoutPath) + { + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(fileSystemCallbacks); + ArgumentNullException.ThrowIfNull(sparseCheckoutPath); + + this.context = context; + this.fileSystemCallbacks = fileSystemCallbacks; + this.coneFileLockPath = sparseCheckoutPath + GVFSConstants.DotGit.LockExtension; + this.pendingFilePath = GetPendingFilePath(context.Enlistment); + } + + /// + /// The mount creates the manager only for a Git that shows + /// , and such a Git changes only + /// the index when the cone changes. + /// + public bool SparsityChangeIsIndexOnly => true; + + /// The path of the file that tells the hooks that a cone change is pending. + public static string GetPendingFilePath(GVFSEnlistment enlistment) + { + return Path.Combine(enlistment.DotGVFSRoot, GVFSConstants.DotGVFS.ConeChangePending); + } + + public IEnumerable GetModifiedPaths() + { + return this.fileSystemCallbacks.GetAllModifiedPaths(); + } + + public bool CanWriteIndex(int processId) + { + // While the holder waits in its pre-command hook, no other Git command writes the + // index. The virtualizer also blocks a rename to .git\index while no Git command + // holds the lock. + NamedPipeMessages.LockData holder = this.context.Repository.GVFSLock.GetExternalHolder(); + return holder != null && holder.PID == processId; + } + + public bool TryGetSparseDirectories(out IReadOnlyList sparseDirectories, out string error) + { + List directories = new List(); + GitProcess.Result result = new GitProcess(this.context.Enlistment).ListSparseDirectories(directories.Add); + if (result.ExitCodeIsFailure) + { + sparseDirectories = null; + error = result.Errors; + return false; + } + + sparseDirectories = directories; + error = null; + return true; + } + + public bool IsFileInWorkingDirectory(string gitPath) + { + string path = Path.Combine( + this.context.Enlistment.WorkingDirectoryBackingRoot, + gitPath.Replace(GVFSConstants.GitPathSeparator, Path.DirectorySeparatorChar)); + return this.context.FileSystem.FileExists(path); + } + + public bool TryLockConeFile(out IDisposable coneFileLock, out Exception error) + { + coneFileLock = null; + error = null; + try + { + // Git creates the lock file with O_EXCL, so its sparse-checkout writers fail while + // this file exists. Windows deletes the file when the handle closes, also when the + // mount process ends, so a lock file never stays behind. + coneFileLock = this.context.FileSystem.OpenFileStream( + this.coneFileLockPath, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + FileOptions.DeleteOnClose, + callFlushFileBuffers: false); + return true; + } + catch (IOException e) + { + error = e; + return false; + } + catch (UnauthorizedAccessException e) + { + error = e; + return false; + } + } + + public GitProcess.Result ApplyConeToIndex() + { + // Git reports success even when it cannot replace the index (update_working_directory + // ignores the result of write_locked_index). A replaced index is a new file. + string indexPath = this.context.Enlistment.GitIndexPath; + DateTime before = File.GetLastWriteTimeUtc(indexPath); + GitProcess.Result result = new GitProcess(this.context.Enlistment).ReapplySparseCheckout(); + if (!result.ExitCodeIsFailure && File.GetLastWriteTimeUtc(indexPath) == before) + { + return new GitProcess.Result(result.Output, "Git did not replace the index. " + result.Errors, GitProcess.Result.GenericFailureCode); + } + + return result; + } + + public ProcessStartTimeResult TryGetProcessStartTime(int processId, out long startTime) + { + return GVFSPlatform.Instance.TryGetActiveProcessStartTime(processId, out startTime); + } + + public bool TrySetConeChangePending(bool pending, out Exception error) + { + error = null; + try + { + if (pending) + { + // The hook only checks that the file exists. + using (new FileStream(this.pendingFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete)) + { + } + } + else + { + File.Delete(this.pendingFilePath); + } + + return true; + } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) + { + error = e; + return false; + } + } + + public bool TryGetPathsThatDifferFromHead(out ICollection paths, out string error) + { + List differing = new List(); + GitProcess.Result result = new GitProcess(this.context.Enlistment).ListPathsThatDifferFromHead(differing.Add, ListPathsTimeoutMs); + if (result.ExitCodeIsFailure) + { + paths = null; + error = result.Errors; + return false; + } + + paths = differing; + error = null; + return true; + } + + public long GetRepositoryStamp() + { + try + { + // "git reset --soft" moves HEAD without a write to the index, but Git logs the + // move in the HEAD reflog. + long index = File.GetLastWriteTimeUtc(this.context.Enlistment.GitIndexPath).Ticks; + long headLog = File.GetLastWriteTimeUtc(this.context.Enlistment.GitHeadLogPath).Ticks; + return unchecked((index * 31) + headLog); + } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) + { + // Unknown: the manager checks again. + return DateTime.UtcNow.Ticks; + } + } + } +} diff --git a/GVFS/GVFS.PerfProfiling/Program.cs b/GVFS/GVFS.PerfProfiling/Program.cs index cf4bc4933..3bb9dc9e4 100644 --- a/GVFS/GVFS.PerfProfiling/Program.cs +++ b/GVFS/GVFS.PerfProfiling/Program.cs @@ -40,10 +40,13 @@ private static void Main(string[] args) } ProfilingEnvironment environment = new ProfilingEnvironment(enlistmentRootPath); + bool sparseIndexEnabled = environment.Context.Repository.GetConfigBoolOrDefault( + GVFSConstants.GitConfig.AutoSparseIndex, + GVFSConstants.GitConfig.AutoSparseIndexDefault); Dictionary allTests = new Dictionary { - { TestsToRun.ValidateIndex, () => GitIndexProjection.ReadIndex(environment.Context.Tracer, Path.Combine(environment.Enlistment.WorkingDirectoryRoot, GVFSConstants.DotGit.Index)) }, + { TestsToRun.ValidateIndex, () => GitIndexProjection.ReadIndex(environment.Context.Tracer, Path.Combine(environment.Enlistment.WorkingDirectoryRoot, GVFSConstants.DotGit.Index), acceptSparseDirectories: sparseIndexEnabled) }, { TestsToRun.RebuildProjection, () => environment.FileSystemCallbacks.GitIndexProjectionProfiler.ForceRebuildProjection() }, { TestsToRun.ValidateModifiedPaths, () => environment.FileSystemCallbacks.GitIndexProjectionProfiler.ForceAddMissingModifiedPaths(environment.Context.Tracer) }, }; diff --git a/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs b/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs index 841613988..ec50a9454 100644 --- a/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs +++ b/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs @@ -1959,7 +1959,7 @@ private void NotifyFileHandleClosedFileModifiedOrDeletedHandler( } else { - this.FileSystemCallbacks.InvalidateGitStatusCache(); + this.FileSystemCallbacks.OnFileModified(virtualPath); } } else if (isFileDeleted) diff --git a/GVFS/GVFS.UnitTests/Common/ConeManagementMessagesTests.cs b/GVFS/GVFS.UnitTests/Common/ConeManagementMessagesTests.cs new file mode 100644 index 000000000..c935ccd5e --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/ConeManagementMessagesTests.cs @@ -0,0 +1,109 @@ +using GVFS.Common.NamedPipes; +using GVFS.Tests.Should; +using NUnit.Framework; +using System.Collections.Generic; + +namespace GVFS.UnitTests.Common +{ + [TestFixture] + public class ConeManagementMessagesTests + { + [TestCase] + public void WidenRequestRoundTripsThroughMessageFrame() + { + NamedPipeMessages.ConeManagement.WidenParameters original = + new NamedPipeMessages.ConeManagement.WidenParameters( + "4242", + new List { "A/b.txt", "my dir/a|b.txt", "C/D/" }); + + NamedPipeMessages.Message message = NamedPipeMessages.Message.FromString( + new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.WidenRequest, original.ToBody()).ToString()); + + message.Header.ShouldEqual(NamedPipeMessages.ConeManagement.WidenRequest); + NamedPipeMessages.ConeManagement.WidenParameters.TryParse( + message.Body, out NamedPipeMessages.ConeManagement.WidenParameters parsed) + .ShouldBeTrue(); + parsed.CommandId.ShouldEqual("4242"); + parsed.Paths.ShouldMatchInOrder("A/b.txt", "my dir/a|b.txt", "C/D/"); + } + + [TestCase] + public void WidenAllowsAnEmptyCommandId() + { + string body = new NamedPipeMessages.ConeManagement.WidenParameters(null, new List { "A/b.txt" }).ToBody(); + + NamedPipeMessages.ConeManagement.WidenParameters.TryParse(body, out NamedPipeMessages.ConeManagement.WidenParameters parsed).ShouldBeTrue(); + parsed.CommandId.ShouldEqual(string.Empty); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("4242")] + [TestCase("12a\0A/b.txt")] + [TestCase("4242\0/abs/path.txt")] + [TestCase("4242\0C:/Windows/x.txt")] + [TestCase("4242\0D:relative.txt")] + [TestCase("4242\0//server/share/x.txt")] + [TestCase("4242\0A\\b.txt")] + [TestCase("4242\0../outside.txt")] + [TestCase("4242\0A/../../outside.txt")] + [TestCase("4242\0A//b.txt")] + [TestCase("4242\0./A/b.txt")] + [TestCase("4242\0A/b.txt\0")] + [TestCase("4242\0A/line\nbreak.txt")] + [TestCase("4242\0A/frame\u0003end.txt")] + [TestCase("4242\0A/control\u0001.txt")] + [TestCase("4242\0A/*/x.txt")] + [TestCase("4242\0A/b?/")] + [TestCase("4242\0A/trailing./x.txt")] + [TestCase("4242\0A/trailing /x.txt")] + [TestCase("4242\0CON")] + [TestCase("4242\0A/nul.txt")] + [TestCase("4242\0A/COM1/")] + [TestCase("4242\0.git/config")] + [TestCase("12345678901\0A/b.txt")] + public void WidenParseRejectsBodiesThatAreNotRepoRelativePaths(string body) + { + NamedPipeMessages.ConeManagement.WidenParameters.TryParse(body, out NamedPipeMessages.ConeManagement.WidenParameters parsed) + .ShouldBeFalse(); + parsed.ShouldBeNull(); + } + + [TestCase] + public void WidenParseRejectsAnUnpairedSurrogate() + { + NamedPipeMessages.ConeManagement.WidenParameters.TryParse("4242\0A/" + '\uD800' + ".txt", out NamedPipeMessages.ConeManagement.WidenParameters parsed) + .ShouldBeFalse(); + parsed.ShouldBeNull(); + } + + [TestCase("A/*.cs")] + [TestCase("A/COM10.txt")] + [TestCase("A/console/")] + [TestCase("A/.gitignore")] + [TestCase("A/\uD83D\uDE00/b.txt")] + public void WidenParseAcceptsUnusualButValidPaths(string path) + { + NamedPipeMessages.ConeManagement.WidenParameters.TryParse("4242\0" + path, out NamedPipeMessages.ConeManagement.WidenParameters parsed) + .ShouldBeTrue(); + parsed.Paths.ShouldMatchInOrder(path); + } + + [TestCase("4242", true)] + [TestCase("", true)] + [TestCase(null, false)] + [TestCase("12a", false)] + [TestCase("-1", false)] + public void NarrowParseAcceptsOnlyDigits(string body, bool expected) + { + NamedPipeMessages.ConeManagement.NarrowParameters.TryParse(body, out NamedPipeMessages.ConeManagement.NarrowParameters parsed) + .ShouldEqual(expected); + + if (expected) + { + parsed.CommandId.ShouldEqual(body); + parsed.ToBody().ShouldEqual(body); + } + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/EnlistmentHydrationSummaryTests.cs b/GVFS/GVFS.UnitTests/Common/EnlistmentHydrationSummaryTests.cs index 3fe6b2104..cb9a52525 100644 --- a/GVFS/GVFS.UnitTests/Common/EnlistmentHydrationSummaryTests.cs +++ b/GVFS/GVFS.UnitTests/Common/EnlistmentHydrationSummaryTests.cs @@ -232,6 +232,19 @@ public void CreateSummary_CancelledToken_ReturnsInvalidSummary() Assert.IsNull(result.Error); } + [TestCase(42, 42)] + [TestCase(-1, 100)] + public void ProjectedFileCountReplacesTheIndexEntryCount(int projectedFileCount, int expectedTotalFileCount) + { + // The index header of a sparse index counts each collapsed folder as one entry. + // The projection provides the file count then, and -1 for a full index. + this.AddIndex(100); + EnlistmentHydrationSummary summary = EnlistmentHydrationSummary.CreateSummary( + this.context.Enlistment, this.fileSystem, this.tracer, () => 20, new TestPathData(), projectedFileCountProvider: () => projectedFileCount); + + Assert.AreEqual(expectedTotalFileCount, summary.TotalFileCount); + } + [TestCase(100, 20, "None")] [TestCase(100, 1, "HydratedFoldersExceedTotal")] [TestCase(4, 1, "HydratedFilesExceedTotal, HydratedFoldersExceedTotal")] diff --git a/GVFS/GVFS.UnitTests/Common/GitPathspecParserTests.cs b/GVFS/GVFS.UnitTests/Common/GitPathspecParserTests.cs new file mode 100644 index 000000000..8b448b31c --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/GitPathspecParserTests.cs @@ -0,0 +1,648 @@ +using GVFS.Common; +using GVFS.Tests.Should; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common +{ + [TestFixture] + public class GitPathspecParserTests + { + // ── Command extraction ────────────────────────────────────────── + + [TestCase] + public void EmptyArgs_ReturnsEmpty() + { + GitPathspecParser.ParseHookArgs(new string[0]).Command.ShouldBeNull(); + GitPathspecParser.ParseHookArgs(null).Command.ShouldBeNull(); + GitPathspecParser.ParseHookArgs(new[] { "pre-command" }).Command.ShouldBeNull(); + } + + [TestCase] + public void Command_IsLowercasedAndGitPrefixStripped() + { + GitPathspecParser.ParseHookArgs(new[] { "pre-command", "ADD", "file.txt" }) + .Command.ShouldEqual("add"); + GitPathspecParser.ParseHookArgs(new[] { "pre-command", "git-add", "file.txt" }) + .Command.ShouldEqual("add"); + } + + // ── add / stage / rm / mv: all positionals are pathspecs ──────── + + [TestCase] + public void Add_InlinePathspecs() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "a.txt", "b.txt" }); + result.Pathspecs.ShouldMatchInOrder("a.txt", "b.txt"); + result.NamesPaths.ShouldBeTrue(); + } + + [TestCase] + public void Add_NoPathspecs() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add" }); + result.Pathspecs.ShouldBeEmpty(); + result.NamesPaths.ShouldBeFalse(); + } + + [TestCase] + public void Add_SkipsOptionFlags() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "--all", "--verbose", "src/" }); + result.Pathspecs.ShouldMatchInOrder("src/"); + } + + [TestCase] + public void Add_CombinedShortFlags_AreNotPathspecs() + { + // -Av = --all --verbose; neither takes a value, so "file" is a pathspec. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "-Av", "file" }); + result.Pathspecs.ShouldMatchInOrder("file"); + } + + // ── Paths with spaces (shell already stripped quotes) ─────────── + + [TestCase] + public void Add_PathWithSpaces() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "my documents/todo list.txt" }); + result.Pathspecs.ShouldMatchInOrder("my documents/todo list.txt"); + } + + // ── "--" separator ────────────────────────────────────────────── + + [TestCase] + public void Add_PathsAfterDashDash() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "--", "-weird-name.txt", "b.txt" }); + result.Pathspecs.ShouldMatchInOrder("-weird-name.txt", "b.txt"); + } + + [TestCase] + public void DashDash_TokensAreLiteralNotOptions() + { + // After --, a token that looks like an option is still a pathspec. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "--", "--all" }); + result.Pathspecs.ShouldMatchInOrder("--all"); + } + + // ── checkout: leading ref, then pathspecs ─────────────────────── + + [TestCase] + public void Checkout_BranchOnly_NoPathspecs() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "my-branch" }); + result.Pathspecs.ShouldBeEmpty(); + } + + [TestCase] + public void Checkout_HeadDashDashPaths() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "HEAD", "--", "foo.txt", "bar.txt" }); + result.Pathspecs.ShouldMatchInOrder("foo.txt", "bar.txt"); + } + + [TestCase] + public void Checkout_RefThenPathspecsWithoutDashDash() + { + // git checkout branch file1 file2 — first positional is the ref. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "branch", "file1", "file2" }); + result.Pathspecs.ShouldMatchInOrder("file1", "file2"); + } + + [TestCase] + public void Checkout_DashB_ConsumesBranchName_NotPathspec() + { + // -b creates a branch; the value is not a pathspec. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "-b", "topic" }); + result.Pathspecs.ShouldBeEmpty(); + } + + [TestCase] + public void Checkout_DashDashPathsAfterDashB() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "-b", "topic", "--", "file.txt" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + // ── reset: leading ref, then pathspecs ────────────────────────── + + [TestCase] + public void Reset_MixedWithPaths() + { + // git reset HEAD file.txt — first positional is the ref. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "reset", "HEAD", "out1/f.txt" }); + result.Pathspecs.ShouldMatchInOrder("out1/f.txt"); + } + + [TestCase] + public void Reset_PathsAfterDashDash() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "reset", "--", "out1/f.txt" }); + result.Pathspecs.ShouldMatchInOrder("out1/f.txt"); + } + + // ── restore: existing behavior must be covered ────────────────── + + [TestCase] + public void Restore_StagedAllFiles() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "restore", "--staged", "." }); + result.Pathspecs.ShouldMatchInOrder("."); + } + + [TestCase] + public void Restore_SkipsSourceSeparateValue() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "restore", "--staged", "--source", "HEAD~1", "file.txt" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void Restore_SkipsSourceEqualsValue() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "restore", "--staged", "--source=HEAD~1", "file.txt" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void Restore_SkipsShortSourceSeparateValue() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "restore", "--staged", "-s", "HEAD~1", "file.txt" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + // ── commit: -m must not swallow a pathspec ────────────────────── + + [TestCase] + public void Commit_ShortMessageSeparateValue_ThenPathspec() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "commit", "-m", "my message", "file.txt" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void Commit_CombinedShortMessage_BakedValue() + { + // -am "msg": -a is boolean, -m is value-taking and last, so it + // consumes "wip"; "file.txt" remains a pathspec. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "commit", "-am", "wip", "file.txt" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void Commit_ShortMessageBakedIntoCluster() + { + // -mwip: -m is value-taking but not last, so "wip" is its baked + // value; "file.txt" is a pathspec. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "commit", "-mwip", "file.txt" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void Commit_LongMessageEqualsValue_ThenPathspec() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "commit", "--message=hello world", "file.txt" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + // ── switch: no pathspecs at all ───────────────────────────────── + + [TestCase] + public void Switch_TakesNoPathspecs() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "switch", "-c", "topic" }); + result.Pathspecs.ShouldBeEmpty(); + result.NamesPaths.ShouldBeFalse(); + } + + // ── stash push/save vs other subcommands ──────────────────────── + + [TestCase] + public void Stash_PushWithPaths() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "stash", "push", "out1/f.txt" }); + result.Pathspecs.ShouldMatchInOrder("out1/f.txt"); + } + + [TestCase] + public void Stash_PushDashDashPaths() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "stash", "push", "--", "out1/f.txt", "out2/g.txt" }); + result.Pathspecs.ShouldMatchInOrder("out1/f.txt", "out2/g.txt"); + } + + [TestCase] + public void Stash_PushSkipsMessageValue() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "stash", "push", "-m", "my stash", "out1/f.txt" }); + result.Pathspecs.ShouldMatchInOrder("out1/f.txt"); + } + + [TestCase] + public void Stash_PopHasNoPathspecs() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "stash", "pop" }); + result.Pathspecs.ShouldBeEmpty(); + } + + [TestCase] + public void Stash_BareIsNotPush() + { + // Bare "git stash" is an implicit push but names no paths. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "stash" }); + result.Pathspecs.ShouldBeEmpty(); + } + + // ── diff / log / show: only paths after "--" count ────────────── + + [TestCase] + public void Diff_RefsBeforeDashDashAreNotPathspecs() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "diff", "main", "feature", "--", "src/file.cs" }); + result.Pathspecs.ShouldMatchInOrder("src/file.cs"); + } + + [TestCase] + public void Log_NoDashDash_NoPathspecs() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "log", "--oneline", "main" }); + result.Pathspecs.ShouldBeEmpty(); + } + + // ── Unknown command: only "--" paths count ────────────────────── + + [TestCase] + public void UnknownCommand_OnlyDashDashPaths() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "frobnicate", "arg1", "--", "path.txt" }); + result.Pathspecs.ShouldMatchInOrder("path.txt"); + } + + // ── Injected --git-pid / --exit_code are filtered ─────────────── + + [TestCase] + public void GitPid_IsFiltered() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "file.txt", "--git-pid=1234" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void ExitCode_IsFilteredEvenPastDashDash() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "post-command", "add", "--", "file.txt", "--git-pid=1234", "--exit_code=0" }); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + // ── --pathspec-from-file / --pathspec-file-nul ────────────────── + + [TestCase] + public void PathspecFromFile_EqualsForm() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "--pathspec-from-file=list.txt" }); + result.PathspecFromFile.ShouldEqual("list.txt"); + result.PathspecFileNul.ShouldBeFalse(); + result.Failed.ShouldBeFalse(); + result.NamesPaths.ShouldBeTrue(); + } + + [TestCase] + public void PathspecFromFile_SeparateArg() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "--pathspec-from-file", "list.txt" }); + result.PathspecFromFile.ShouldEqual("list.txt"); + } + + [TestCase] + public void PathspecFileNul_SetsFlag() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "--pathspec-from-file=list.txt", "--pathspec-file-nul" }); + result.PathspecFromFile.ShouldEqual("list.txt"); + result.PathspecFileNul.ShouldBeTrue(); + } + + [TestCase] + public void PathspecFromFile_Stdin_Fails() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "--pathspec-from-file=-" }); + result.Failed.ShouldBeTrue(); + result.NamesPaths.ShouldBeFalse(); + } + + [TestCase] + public void PathspecFromFile_WithInlinePaths() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "--pathspec-from-file=list.txt", "extra.txt" }); + result.PathspecFromFile.ShouldEqual("list.txt"); + result.Pathspecs.ShouldMatchInOrder("extra.txt"); + } + + // ── Global options: -C, --git-dir, --work-tree ────────────────── + + [TestCase] + public void Global_DashC_SeparateValue() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "-C", "sub/dir", "add", "file.txt" }); + result.ChangeDirectory.ShouldEqual("sub/dir"); + result.Command.ShouldEqual("add"); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void Global_GitDir_SeparateValue() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "--git-dir", "/repo/.git", "add", "file.txt" }); + result.GitDir.ShouldEqual("/repo/.git"); + result.Command.ShouldEqual("add"); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void Global_GitDir_EqualsValue() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "--git-dir=/repo/.git", "add", "file.txt" }); + result.GitDir.ShouldEqual("/repo/.git"); + result.Command.ShouldEqual("add"); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void Global_WorkTree_AndConfig() + { + // -c key=value is a value-taking global; --work-tree consumes a value. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "-c", "core.autocrlf=false", "--work-tree", "/wt", "add", "file.txt" }); + result.WorkTree.ShouldEqual("/wt"); + result.Command.ShouldEqual("add"); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + [TestCase] + public void Global_BooleanPaginate_DoesNotConsumeCommand() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "--no-pager", "add", "file.txt" }); + result.Command.ShouldEqual("add"); + result.Pathspecs.ShouldMatchInOrder("file.txt"); + } + + // ── Mixed: everything at once ─────────────────────────────────── + + [TestCase] + public void Mixed_GlobalsOptionsValueOptionsPathspecs() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] + { + "pre-command", "-C", "repo", "commit", + "--message", "a commit", "-a", "src/a.cs", "src/b.cs", "--git-pid=99", + }); + result.ChangeDirectory.ShouldEqual("repo"); + result.Command.ShouldEqual("commit"); + result.Pathspecs.ShouldMatchInOrder("src/a.cs", "src/b.cs"); + } + + // ── Out-of-cone conflict resolution ───────────────────────────── + // + // When a rebase/merge conflicts on a file outside the sparse cone, the + // user resolves it by naming that path: "git add ", "git rm + // ", "git checkout --ours/--theirs ", "git restore + // ". Each must yield the path so the pre-command hook can widen + // the cone and let plain (non "--sparse") Git succeed. + + [TestCase] + public void Add_OutOfConeConflictPath_NamesPath() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "out0005/f0001.txt" }); + result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt"); + result.NamesPaths.ShouldBeTrue(); + } + + [TestCase] + public void Rm_OutOfConeConflictPath_NamesPath() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "rm", "out0005/f0001.txt" }); + result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt"); + result.NamesPaths.ShouldBeTrue(); + } + + [TestCase] + public void Restore_ConflictPathWithOurs_NamesPath() + { + // restore treats every positional as a pathspec, so --ours is just a + // boolean flag; the path is still extracted. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "restore", "--ours", "out0005/f0001.txt" }); + result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt"); + result.NamesPaths.ShouldBeTrue(); + } + + [TestCase] + public void Checkout_DashDashConflictPath_NamesPath() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "--", "out0005/f0001.txt" }); + result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt"); + result.NamesPaths.ShouldBeTrue(); + } + + [TestCase] + public void Reset_DashDashConflictPath_NamesPath() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "reset", "--", "out0005/f0001.txt" }); + result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt"); + result.NamesPaths.ShouldBeTrue(); + } + + // ── checkout --ours / --theirs / -p suppress the leading ref ──── + // + // "git checkout --ours " has no ref operand, so the first + // positional is a pathspec, not a branch. Without this, the parser + // would misread the conflicted path as a ref and never widen for it. + + [TestCase] + public void Checkout_Ours_FirstPositionalIsPathspec() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "--ours", "out0005/f0001.txt" }); + result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt"); + result.NamesPaths.ShouldBeTrue(); + } + + [TestCase] + public void Checkout_Theirs_FirstPositionalIsPathspec() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "--theirs", "a.txt", "b.txt" }); + result.Pathspecs.ShouldMatchInOrder("a.txt", "b.txt"); + } + + [TestCase] + public void Checkout_ShortPatch_FirstPositionalIsPathspec() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "-p", "out0005/f0001.txt" }); + result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt"); + } + + [TestCase] + public void Checkout_Ours_FlagAfterPathIsStillSuppressing() + { + // Flag order is not fixed: the ref-suppressing flag is detected + // across the whole command, so the path is a pathspec even when the + // flag follows it. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "out0005/f0001.txt", "--theirs" }); + result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt"); + } + + [TestCase] + public void Checkout_Ours_NoPath_NoPathspecs() + { + // "git checkout --ours" with no path still names nothing. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "--ours" }); + result.Pathspecs.ShouldBeEmpty(); + result.NamesPaths.ShouldBeFalse(); + } + + [TestCase] + public void Checkout_LiteralOursPathAfterDashDash_IsPathspec() + { + // After "--", "--ours" is a literal path, not a ref-suppressing flag; + // the branch before "--" is still a ref. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "topic", "--", "--ours" }); + result.Pathspecs.ShouldMatchInOrder("--ours"); + } + + // ── --end-of-options ──────────────────────────────────────────── + + [TestCase] + public void EndOfOptions_DashTokenIsPositional() + { + // "-topic" is a ref after --end-of-options, so it does not count as a + // short option cluster, and the next positional is a pathspec. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "--end-of-options", "-topic", "a.txt" }); + result.Pathspecs.ShouldMatchInOrder("a.txt"); + } + + [TestCase] + public void EndOfOptions_DashTokenIsPathspecForPathCommands() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "add", "--end-of-options", "-weird.txt", "--all" }); + result.Pathspecs.ShouldMatchInOrder("-weird.txt", "--all"); + } + + [TestCase] + public void EndOfOptions_DashDashStillSeparatesPathspecs() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "diff", "--end-of-options", "-topic", "--", "a.txt" }); + result.Pathspecs.ShouldMatchInOrder("a.txt"); + } + + [TestCase] + public void EndOfOptions_LaterRefSuppressingFlagIsARef() + { + // "--ours" after --end-of-options is a ref name, so the leading ref + // operand is not suppressed. + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "checkout", "--end-of-options", "--ours", "a.txt" }); + result.Pathspecs.ShouldMatchInOrder("a.txt"); + } + + // ── Other verbs in the table ──────────────────────────────────── + + [TestCase("stage")] + [TestCase("rm")] + [TestCase("mv")] + public void PathspecVerbs_EveryPositionalIsAPathspec(string verb) + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", verb, "-q", "a.txt", "dir/", "--git-pid=1" }); + result.Pathspecs.ShouldMatchInOrder("a.txt", "dir/"); + } + + [TestCase("grep")] + [TestCase("blame")] + [TestCase("show")] + public void RefsOnlyVerbs_OnlyPathsAfterDashDash(string verb) + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", verb, "HEAD", "--stat", "a.txt", "--", "b.txt" }); + result.Pathspecs.ShouldMatchInOrder("b.txt"); + } + + [TestCase] + public void Commit_FixupValueIsNotAPathspec() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "commit", "--fixup", "HEAD~1", "a.txt" }); + result.Pathspecs.ShouldMatchInOrder("a.txt"); + } + + [TestCase] + public void Restore_ConflictEqualsValue_ThenPathspec() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "restore", "--conflict=diff3", "a.txt" }); + result.Pathspecs.ShouldMatchInOrder("a.txt"); + } + + [TestCase] + public void Switch_DashDashPathsAreIgnored() + { + ParsedGitCommand result = GitPathspecParser.ParseHookArgs( + new[] { "pre-command", "switch", "-c", "topic", "--", "a.txt" }); + result.Pathspecs.ShouldBeEmpty(); + result.NamesPaths.ShouldBeFalse(); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs new file mode 100644 index 000000000..5c8d98970 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs @@ -0,0 +1,1296 @@ +using GVFS.Common; +using GVFS.Common.Git; +using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; +using GVFS.Common.Tracing; +using GVFS.Tests.Should; +using GVFS.UnitTests.Mock.Common; +using GVFS.UnitTests.Mock.FileSystem; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class AutoSparseIndexConeManagerTests + { + 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 ConeWithAB = Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n"; + private const string ConeWithC = Header + "/C/\n!/C/*/\n"; + + private const int FirstGit = 100; + private const int SecondGit = 200; + + private MockTracer tracer; + private TestFileSystem fileSystem; + private MockEnvironment environment; + private AutoSparseIndexConeManager manager; + + [SetUp] + public void SetUp() + { + this.tracer = new MockTracer(); + this.fileSystem = new TestFileSystem(); + this.fileSystem.WriteAllText(SparseCheckoutPath, Header); + this.environment = new MockEnvironment(this.fileSystem); + this.environment.RunningProcesses[FirstGit] = 1; + this.environment.RunningProcesses[SecondGit] = 2; + this.manager = this.CreateManager(ignoreCase: false, changeCheckDelayMs: Timeout.Infinite); + } + + [TearDown] + public void TearDown() + { + this.manager.Stop(); + } + + [TestCase("git version 2.56.1.vfs.0.0.6\nfeature: fsmonitor--daemon\nfeature: vfs-sparse-index\n", 0, true)] + [TestCase("git version 2.56.1.vfs.0.0.6\r\nfeature: vfs-sparse-index\r\n", 0, true)] + [TestCase("git version 2.56.1.vfs.0.1\nfeature: fsmonitor--daemon\n", 0, false)] + [TestCase("feature: vfs-sparse-index-v2\nfeatures: vfs-sparse-index\n", 0, false)] + [TestCase("feature: vfs-sparse-index\n", 1, false)] + [TestCase(null, 0, false)] + public void GitSupportsSparseIndexOnlyWithTheFeatureLine(string output, int exitCode, bool expected) + { + AutoSparseIndexConeManager.GitSupportsSparseIndex(new GitProcess.Result(output, string.Empty, exitCode)).ShouldEqual(expected); + } + + [TestCase] + public void WidenWritesTheConeAndAppliesItToTheIndex() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithAB); + this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB); + this.fileSystem.FileExists(BackupPath).ShouldBeFalse("The backup must be deleted"); + this.LastEvent("ConeWiden").Level.ShouldEqual(EventLevel.Informational); + } + + [TestCase] + public void NarrowWritesTheConeOfTheModifiedPathsWithoutRunningGit() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.ConeFile.ShouldEqual(Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n/C/\n!/C/*/\n"); + + this.Narrow(FirstGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + this.environment.ConeFilesAtApply.Count.ShouldEqual(1, "The narrow must not run Git"); + this.fileSystem.FileExists(BackupPath).ShouldBeFalse("The backup must be deleted"); + } + + [TestCase] + public void WidenAfterANarrowAppliesTheConeEvenWhenTheConeFileDoesNotChange() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.Narrow(FirstGit).ShouldBeTrue(); + + // A root file adds no directory, so the cone file stays the same. The index still + // has the entries that the first widen expanded, so Git must collapse them. + this.Widen(SecondGit, "root.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB, Header); + } + + [TestCase] + public void WidenDoesNotRunGitWhenTheConeAlreadyIncludesThePaths() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.Widen(SecondGit, "A/B/other.txt").ShouldBeTrue(); + + this.environment.ConeFilesAtApply.Count.ShouldEqual(1); + } + + [TestCase] + public void DirectoryStaysInTheConeUntilTheLastCommandThatNeedsItNarrows() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.Widen(SecondGit, "A/B/other.txt").ShouldBeTrue(); + + this.Narrow(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithAB); + + this.Narrow(SecondGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void EntriesOfACommandThatEndedWithoutANarrowAreRemovedAtTheNextRequest() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.environment.RunningProcesses.Remove(FirstGit); + + this.Widen(SecondGit, "C/c.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void NarrowOfAnotherCommandRemovesTheEntriesOfACommandThatEnded() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.environment.RunningProcesses.Remove(FirstGit); + + this.Narrow(SecondGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void EntriesOfAProcessIdThatAnotherProcessReusesAreRemoved() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.environment.RunningProcesses[FirstGit] = 99; + + this.Narrow(SecondGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void WidenThatArrivesAfterTheNarrowOfTheSameCommandIsRefused() + { + this.Narrow(FirstGit).ShouldBeTrue(); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + } + + [TestCase] + public void WidenFromACommandThatEndedIsRefused() + { + this.environment.RunningProcesses.Remove(FirstGit); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void WidenWithoutACommandIdIsRefused() + { + this.manager.TryWiden(new NamedPipeMessages.ConeManagement.WidenParameters(string.Empty, new[] { "A/B/b.txt" })).ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + } + + [TestCase] + public void WidenIsRefusedWhenGitCannotReplaceTheIndex() + { + this.environment.IndexWriteAllowed = false; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + } + + [TestCase] + public void WidenIsRefusedWhenGitHoldsTheConeFileLock() + { + this.environment.ConeFileLocked = true; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + this.LastEvent("ConeWiden").Level.ShouldEqual(EventLevel.Warning); + } + + [TestCase] + public void ConeFileLockIsReleasedAfterEachRequest() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.Narrow(FirstGit).ShouldBeTrue(); + + this.environment.LockCount.ShouldEqual(2); + this.environment.IsConeFileLockHeld.ShouldBeFalse(); + } + + [TestCase] + public void WidenWithAPathThatIsNotValidIsRefused() + { + this.manager.TryWiden(new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "../outside.txt" })).ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + } + + [TestCase] + public void ModifiedPathThatAConeFileCannotContainKeepsTheConeFileAndTheIndex() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.environment.ModifiedPaths.Add("D/*/d.txt"); + + this.Widen(SecondGit, "C/c.txt").ShouldBeFalse(); + this.LastEvent("ConeWiden").Metadata["InvalidPathException"].ToString().ShouldContain("D/*"); + + this.Narrow(FirstGit).ShouldBeFalse(); + + this.ConeFile.ShouldEqual(ConeWithAB); + this.environment.ConeFilesAtApply.Count.ShouldEqual(1); + } + + [TestCase] + public void ConeFileWriteFailureLeavesTheConeFileAndTheCommandEntriesUnchanged() + { + this.fileSystem.FailRenameTo = SparseCheckoutPath; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + this.fileSystem.FileExists(BackupPath).ShouldBeFalse("The backup must be deleted"); + + this.fileSystem.FailRenameTo = null; + this.Widen(SecondGit, "C/c.txt").ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void ApplyFailureRestoresThePreviousConeFile() + { + this.environment.ApplyExitCode = 128; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.fileSystem.FileExists(BackupPath).ShouldBeFalse("The backup must be deleted"); + this.LastEvent("ConeWiden").Metadata["Restored"].ShouldEqual(true); + + // The failed command has no entries, and the next widen applies the cone again. + this.environment.ApplyExitCode = 0; + this.Widen(SecondGit, "root.txt").ShouldBeTrue(); + this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB, Header); + } + + [TestCase] + public void ApplyExceptionRestoresThePreviousConeFile() + { + this.environment.ApplyException = new InvalidOperationException("Injected failure"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.LastEvent("ConeWiden").Metadata["Result"].ShouldEqual("ApplyFailed"); + + this.environment.ApplyException = null; + this.Widen(SecondGit, "root.txt").ShouldBeTrue(); + this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB, Header); + } + + [TestCase] + public void NarrowWithoutEntriesDoesNotWriteTheConeFile() + { + // The first request of a mount writes the cone file, which can be stale. + this.Narrow(FirstGit).ShouldBeTrue(); + this.environment.LockCount.ShouldEqual(1); + + this.Narrow(SecondGit).ShouldBeTrue(); + + this.environment.LockCount.ShouldEqual(1); + } + + [TestCase] + public void WidenIsRefusedForACommandThatDoesNotHoldTheGVFSLock() + { + this.environment.LockHolder = SecondGit; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + this.LastEvent("ConeWiden").Metadata["Result"].ShouldEqual("NotLockHolder"); + } + + [TestCase] + public void WidenWithTooManyPathsIsRefused() + { + string[] paths = Enumerable.Range(0, AutoSparseIndexConeManager.MaxWidenPaths + 1).Select(i => $"D{i}/f.txt").ToArray(); + + this.Widen(FirstGit, paths).ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + } + + [TestCase] + public void WidenThatWaitedTooLongForEarlierRequestsDoesNotRunGit() + { + this.environment.CanWriteIndexDelayMs = 600; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + this.LastEvent("ConeWiden").Metadata["Result"].ShouldEqual("QueueWaitTooLong"); + } + + [TestCase] + public void WidenIsRefusedWhenTheSparseDirectoriesAreNotKnown() + { + this.environment.ModifiedPaths.Add("D/deleted.txt"); + this.environment.DeletedFiles.Add("D/deleted.txt"); + this.environment.SparseDirectoriesFail = true; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + } + + [TestCase] + public void WidenDoesNotListSparseDirectoriesWithoutADeletedFileOrModifiedFolder() + { + this.environment.ModifiedPaths.Add("C/edited.txt"); + this.environment.SparseDirectoriesFail = true; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + } + + [TestCase] + public void WidenThatExpandsASparseDirectoryWithADeletedFileIsRefused() + { + // Git checks the deleted file out again when it expands A/. + this.environment.SparseDirectories.Add("A/"); + this.environment.ModifiedPaths.Add("A/B/deleted.txt"); + this.environment.DeletedFiles.Add("A/B/deleted.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + this.LastEvent("ConeWiden").Metadata["UnsafeModifiedPath"].ShouldEqual("A/B/deleted.txt"); + } + + [TestCase] + public void WidenOfASiblingDirectoryOfADeletedFileIsApplied() + { + // A/X stays a sparse-directory entry, so Git does not check the deleted file out. + this.environment.SparseDirectories.Add("A/"); + this.environment.ModifiedPaths.Add("A/X/deleted.txt"); + this.environment.DeletedFiles.Add("A/X/deleted.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithAB); + } + + [TestCase] + public void WidenThatExpandsASparseDirectoryWithAModifiedFolderIsRefused() + { + this.environment.SparseDirectories.Add("A/"); + this.environment.ModifiedPaths.Add("A/B/"); + + this.Widen(FirstGit, "A/B/C/c.txt").ShouldBeFalse(); + + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + } + + [TestCase] + public void ModifiedFileThatExistsInsideASparseDirectoryIsInTheCone() + { + // An existing file keeps its content when Git expands its directory. + this.environment.SparseDirectories.Add("A/"); + this.environment.ModifiedPaths.Add("A/B/edited.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.Narrow(FirstGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithAB); + } + + [TestCase] + public void DeletedFileInsideASparseDirectoryStaysOutOfTheCone() + { + this.environment.SparseDirectories.Add("D/"); + this.environment.ModifiedPaths.Add("D/d.txt"); + this.environment.DeletedFiles.Add("D/d.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithAB); + + this.Narrow(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void ModifiedPathWithItsOwnIndexEntryIsInTheCone() + { + this.environment.SparseDirectories.Add("D/"); + this.environment.ModifiedPaths.Add("C/c.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n/C/\n!/C/*/\n"); + } + + [TestCase] + public void NarrowAfterAFailedNarrowWritesTheConeFile() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.environment.ConeFileLocked = true; + this.Narrow(FirstGit).ShouldBeFalse(); + this.ConeFile.ShouldEqual(ConeWithAB); + + this.environment.ConeFileLocked = false; + this.Narrow(SecondGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void ApplyFailureDeletesAConeFileThatDidNotExistBefore() + { + this.fileSystem.DeleteFile(SparseCheckoutPath); + this.environment.ApplyExitCode = 128; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.fileSystem.FileExists(SparseCheckoutPath).ShouldBeFalse(); + } + + [TestCase] + public void FailedRestoreKeepsTheBackupAndTheNextRequestWritesTheConeFile() + { + this.environment.ApplyExitCode = 128; + this.environment.DuringApply = () => this.fileSystem.FailRenameTo = SparseCheckoutPath; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.LastEvent("ConeWiden").Metadata["Restored"].ShouldEqual(false); + this.fileSystem.FileExists(BackupPath).ShouldBeTrue("The backup must stay when the restore fails"); + this.ConeFile.ShouldEqual(ConeWithAB); + + this.fileSystem.FailRenameTo = null; + this.Narrow(SecondGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void ApplyFailureAfterASuccessfulWidenMakesTheNextWidenRunGit() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.environment.ApplyExitCode = 128; + this.Widen(SecondGit, "C/c.txt").ShouldBeFalse(); + this.ConeFile.ShouldEqual(ConeWithAB); + + // The cone file does not change, but Git may have changed the index before it failed. + this.environment.ApplyExitCode = 0; + this.Widen(FirstGit, "A/B/other.txt").ShouldBeTrue(); + + this.environment.ConeFilesAtApply.Count.ShouldEqual(3); + } + + [TestCase] + public void WidenFromAProcessThatTheMountCannotOpenIsRefused() + { + this.environment.StartTimeResults[FirstGit] = ProcessStartTimeResult.Inaccessible; + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void EntriesOfAProcessThatBecameInaccessibleAreRemoved() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.environment.StartTimeResults[FirstGit] = ProcessStartTimeResult.Inaccessible; + + this.Narrow(SecondGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void EntriesOfAProcessWithAnIndeterminateStateAreKept() + { + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + this.environment.StartTimeResults[FirstGit] = ProcessStartTimeResult.Indeterminate; + + this.Narrow(SecondGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithAB); + } + + [TestCase] + public void HandleRequestRepliesFailureForARefusedWiden() + { + this.environment.LockHolder = SecondGit; + NamedPipeMessages.Message widen = new NamedPipeMessages.Message( + NamedPipeMessages.ConeManagement.WidenRequest, + new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "A/B/b.txt" }).ToBody()); + + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, widen).ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); + } + + [TestCase] + public void ConcurrentWidensAndNarrowsEndWithTheConeOfTheModifiedPaths() + { + const int CommandCount = 16; + for (int i = 0; i < CommandCount; i++) + { + this.environment.RunningProcesses[1000 + i] = i; + } + + Parallel.For(0, CommandCount, i => + { + int processId = 1000 + i; + this.Widen(processId, $"Dir{i % 4}/file{i}.txt").ShouldBeTrue(); + this.Narrow(processId).ShouldBeTrue(); + }); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void HandleRequestRepliesNotEnabledWhenTheFeatureIsOff() + { + NamedPipeMessages.Message widen = new NamedPipeMessages.Message( + NamedPipeMessages.ConeManagement.WidenRequest, + new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "A/B/b.txt" }).ToBody()); + + AutoSparseIndexConeManager.HandleRequest(null, this.tracer, widen).ShouldEqual(NamedPipeMessages.ConeManagement.NotEnabledResult); + AutoSparseIndexConeManager.HandleRequest(null, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.NarrowRequest, FirstGit.ToString())) + .ShouldEqual(NamedPipeMessages.ConeManagement.NotEnabledResult); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void HandleRequestAppliesValidRequests() + { + NamedPipeMessages.Message widen = new NamedPipeMessages.Message( + NamedPipeMessages.ConeManagement.WidenRequest, + new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "A/B/b.txt" }).ToBody()); + + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, widen).ShouldEqual(NamedPipeMessages.ConeManagement.SuccessResult); + this.ConeFile.ShouldEqual(ConeWithAB); + + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.NarrowRequest, FirstGit.ToString())) + .ShouldEqual(NamedPipeMessages.ConeManagement.SuccessResult); + this.ConeFile.ShouldEqual(Header); + } + + [TestCase("100\0C:\\outside.txt")] + [TestCase("100\0/abs/path.txt")] + [TestCase("100\0A/../../outside.txt")] + [TestCase("not-a-pid\0A/a.txt")] + [TestCase("100")] + public void HandleRequestRepliesFailureForAWidenBodyThatIsNotValid(string body) + { + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.WidenRequest, body)) + .ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); + + this.ConeFile.ShouldEqual(Header); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + this.tracer.RelatedWarningEvents.ShouldContain(message => message.Contains("not valid")); + } + + [TestCase] + public void HandleRequestRepliesFailureForANarrowBodyThatIsNotValid() + { + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.NarrowRequest, "12345678901")) + .ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); + } + + [TestCase] + public void StartMakesTheFirstCommandApplyTheConeOfTheModifiedPaths() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + + this.manager.Start(); + this.environment.IsPending.ShouldBeTrue(); + + this.Apply(FirstGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithC); + this.environment.IsPending.ShouldBeFalse(); + this.LastEvent("ConeApply").Level.ShouldEqual(EventLevel.Informational); + } + + [TestCase] + public void ChangeOutsideTheAppliedConeIsPendingUntilTheNextApply() + { + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.IsPending.ShouldBeFalse(); + + // The callback runs before the mount adds the path to the modified paths. + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.ModifiedPaths.Add("C/c.txt"); + this.environment.IsPending.ShouldBeTrue(); + + this.Apply(FirstGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + this.environment.ConeFilesAtApply.Last().ShouldEqual(ConeWithC); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void ChangeInsideTheAppliedConeIsNotPending() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.OnWorkingDirectoryPathChanged(@"C\other.txt", isFolder: false); + this.manager.OnWorkingDirectoryPathChanged("root.txt", isFolder: false); + + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void FolderChangeIsPendingUntilTheConeIncludesItsWholeSubtree() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.OnWorkingDirectoryPathChanged(@"C\new", isFolder: true); + this.environment.ModifiedPaths.Add("C/new/"); + this.environment.IsPending.ShouldBeTrue(); + + this.Apply(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC + "/C/new/\n"); + } + + [TestCase] + public void WidenAlsoAppliesThePendingChanges() + { + this.Apply(FirstGit).ShouldBeTrue(); + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.ModifiedPaths.Add("C/c.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n/C/\n!/C/*/\n"); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void ApplyForACommandThatDoesNotHoldTheGVFSLockKeepsTheChangePending() + { + this.manager.Start(); + this.environment.LockHolder = SecondGit; + + this.Apply(FirstGit).ShouldBeFalse(); + + this.environment.IsPending.ShouldBeTrue(); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + } + + [TestCase] + public void FailedApplyKeepsTheChangePendingUntilAnApplySucceeds() + { + this.manager.Start(); + this.environment.ApplyExitCode = 1; + + for (int attempt = 0; attempt < 5; attempt++) + { + this.Apply(FirstGit).ShouldBeFalse(); + this.environment.IsPending.ShouldBeTrue("Git has no fallback for a change that the index does not show"); + } + + this.environment.ApplyExitCode = 0; + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void ApplyIncludesAChangeBeforeTheModifiedPathsHaveIt() + { + this.Apply(FirstGit).ShouldBeTrue(); + + // The background task that adds the modified path waits while Git holds the lock. + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.Apply(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + + // The cone keeps the path until the modified paths have it. + this.Widen(SecondGit, "A/B/b.txt").ShouldBeTrue(); + this.Narrow(SecondGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + + this.environment.ModifiedPaths.Add("C/c.txt"); + this.environment.DifferingPaths.Add("C/c.txt"); + this.manager.TryReconcile().ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void ChangedPathThatIsNotAModifiedPathLeavesTheConeWhenItIsClean() + { + this.Apply(FirstGit).ShouldBeTrue(); + + // For example, Git wrote the file with the content of HEAD. + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.Apply(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void PendingFileThatCannotBeDeletedIsDeletedByTheNextApply() + { + this.manager.Start(); + this.environment.PendingFileDeleteFails = true; + + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.IsPending.ShouldBeTrue(); + + this.environment.PendingFileDeleteFails = false; + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void PendingFileThatCannotBeCreatedIsCreatedByTheNextChange() + { + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.PendingFileFails = true; + + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.IsPending.ShouldBeFalse(); + + this.environment.PendingFileFails = false; + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.IsPending.ShouldBeTrue(); + } + + [TestCase] + public void ReconcileRemovesAModifiedFileThatMatchesHeadWithoutRunningGitToApply() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + this.environment.DiffCount.ShouldEqual(1); + this.environment.ConeFilesAtApply.Count.ShouldEqual(1, "Only Git can apply a cone"); + this.environment.IsPending.ShouldBeFalse(); + // The root file .gitattributes is clean too. + this.LastEvent("ConeReconcile").Metadata["NewlyCleanCount"].ShouldEqual(2); + } + + [TestCase] + public void ReconcileKeepsFilesThatDifferFromHead() + { + // C differs, D is untracked, E is a deleted tracked file, and F was created and + // deleted again. + this.environment.ModifiedPaths.AddRange(new[] { "C/c.txt", "D/d.txt", "E/e.txt", "F/f.txt" }); + this.environment.DifferingPaths.Add("C/c.txt"); + this.environment.UntrackedFiles.Add("D/d.txt"); + this.environment.DeletedFiles.Add("E/e.txt"); + this.environment.DeletedFiles.Add("F/f.txt"); + this.environment.UntrackedFiles.Add("F/f.txt"); + this.environment.SparsityChangeIsIndexOnly = true; + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header + "/C/\n!/C/*/\n/D/\n!/D/*/\n/E/\n!/E/*/\n"); + } + + [TestCase] + public void ReconcileKeepsAFileInAnUntrackedFolderAndRemovesAnIgnoredFile() + { + // Git lists the untracked folder A/B/, not the file in it. Git does not list the + // ignored file C/c.log. + this.environment.ModifiedPaths.AddRange(new[] { "A/B/new.txt", "C/c.log" }); + this.environment.DifferingPaths.Add("A/B/"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithAB); + } + + [TestCase] + public void ReconcileUsesTheRepositoryCaseRule() + { + this.manager = this.CreateManager(ignoreCase: true, changeCheckDelayMs: Timeout.Infinite); + this.environment.ModifiedPaths.Add("C/c.txt"); + this.environment.DifferingPaths.Add("c/C.TXT"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void CleanFileThatChangesAgainIsPendingAndTheApplyWidensTheCone() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.manager.TryReconcile().ShouldBeTrue(); + this.ConeFile.ShouldEqual(Header); + + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.IsPending.ShouldBeTrue(); + this.Apply(FirstGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + this.environment.ConeFilesAtApply.Last().ShouldEqual(ConeWithC); + } + + [TestCase] + public void CleanFileThatDiffersAfterAHeadChangeIsPending() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.manager.TryReconcile().ShouldBeTrue(); + this.ConeFile.ShouldEqual(Header); + + // For example "git reset --soft HEAD~1" after a commit of the file. + this.environment.DifferingPaths.Add("C/c.txt"); + this.environment.RepositoryStamp++; + this.manager.TryReconcile().ShouldBeTrue(); + + this.environment.IsPending.ShouldBeTrue(); + this.Apply(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void ReconcileDoesNotRunGitWhileAChangeIsPendingOrWhenNothingChanged() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.manager.Start(); + + this.manager.TryReconcile().ShouldBeTrue(); + this.environment.DiffCount.ShouldEqual(0, "A pending change can be in a directory that the index does not expand"); + + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DifferingPaths.Add("C/c.txt"); + this.manager.TryReconcile().ShouldBeTrue(); + this.manager.TryReconcile().ShouldBeTrue(); + this.environment.DiffCount.ShouldEqual(1); + } + + [TestCase] + public void ChangeDuringTheCheckKeepsTheFileInTheCone() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DuringDiff = () => this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void ChangeInsideTheAppliedConeStartsACheckWhenTheChangesStop() + { + this.manager.Stop(); + this.manager = this.CreateManager(ignoreCase: false, changeCheckDelayMs: 10); + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + + // For example, an editor wrote the content of HEAD back. + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + + SpinWait.SpinUntil(() => this.tracer.SnapshotRelatedEvents().Any(recorded => recorded.Name == "ConeReconcile"), TimeSpan.FromSeconds(10)) + .ShouldBeTrue("The check did not run"); + this.ConeFile.ShouldEqual(Header); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void CheckThatCannotWriteTheConeFileTriesAgainWithoutGit() + { + this.manager = this.CreateManager(ignoreCase: false, changeCheckDelayMs: 200); + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.ConeFileLocked = true; + + this.manager.TryReconcile().ShouldBeFalse(); + this.ConeFile.ShouldEqual(ConeWithC); + this.environment.ConeFileLocked = false; + + SpinWait.SpinUntil(() => this.ConeFile == Header, TimeSpan.FromSeconds(10)).ShouldBeTrue("The check did not try again"); + this.environment.DiffCount.ShouldEqual(1); + } + + [TestCase] + public void ApplyRunsGitForANewModifiedPathThatACheckWroteToTheConeFile() + { + const string ConeWithD = Header + "/D/\n!/D/*/\n"; + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DuringDiff = () => + { + this.environment.ModifiedPaths.Add("D/d.txt"); + this.manager.OnWorkingDirectoryPathChanged(@"D\d.txt", isFolder: false); + }; + + // The check writes D into the cone file, but the index does not expand D yet. + this.manager.TryReconcile().ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithD); + + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.ConeFilesAtApply.Last().ShouldEqual(ConeWithD); + } + + [TestCase] + public void ApplyDuringTheCheckDiscardsTheResult() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DuringDiff = () => this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void ReconcileFailureKeepsTheCone() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DiffFails = true; + + this.manager.TryReconcile().ShouldBeFalse(); + + this.ConeFile.ShouldEqual(ConeWithC); + this.LastEvent("ConeReconcile").Level.ShouldEqual(EventLevel.Warning); + } + + [TestCase] + public void NarrowDoesNotPutACleanFileBackInTheCone() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.manager.TryReconcile().ShouldBeTrue(); + + this.Widen(SecondGit, "A/B/b.txt").ShouldBeTrue(); + this.Narrow(SecondGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void WhenGitChangesOnlyTheIndexADeletedFileInASparseDirectoryIsInTheCone() + { + this.environment.SparsityChangeIsIndexOnly = true; + this.environment.SparseDirectories.Add("A/"); + this.environment.ModifiedPaths.Add("A/B/deleted.txt"); + this.environment.DeletedFiles.Add("A/B/deleted.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithAB); + this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB); + } + + [TestCase] + public void DeletedFileInTheAppliedConeDoesNotNeedTheSparseDirectories() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.SparseDirectoriesFail = true; + this.environment.ModifiedPaths.Add("C/deleted.txt"); + this.environment.DeletedFiles.Add("C/deleted.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n/C/\n!/C/*/\n"); + } + + [TestCase] + public void HandleRequestAppliesAnApplyRequest() + { + this.manager.Start(); + + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.ApplyRequest, FirstGit.ToString())) + .ShouldEqual(NamedPipeMessages.ConeManagement.SuccessResult); + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.ApplyRequest, "x")) + .ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); + AutoSparseIndexConeManager.HandleRequest(null, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.ApplyRequest, FirstGit.ToString())) + .ShouldEqual(NamedPipeMessages.ConeManagement.NotEnabledResult); + this.environment.IsPending.ShouldBeFalse(); + } + + private string ConeFile => this.fileSystem.ReadAllText(SparseCheckoutPath); + + private AutoSparseIndexConeManager CreateManager(bool ignoreCase, int changeCheckDelayMs) + { + return new AutoSparseIndexConeManager(this.tracer, this.fileSystem, SparseCheckoutPath, ignoreCase, this.environment, changeCheckDelayMs); + } + + private bool Apply(int processId) + { + return this.manager.TryApply(new NamedPipeMessages.ConeManagement.ApplyParameters(processId.ToString())); + } + + private bool Widen(int processId, params string[] paths) + { + return this.manager.TryWiden(new NamedPipeMessages.ConeManagement.WidenParameters(processId.ToString(), paths)); + } + + private bool Narrow(int processId) + { + return this.manager.TryNarrow(new NamedPipeMessages.ConeManagement.NarrowParameters(processId.ToString())); + } + + private MockTracer.RecordedEvent LastEvent(string name) + { + return this.tracer.SnapshotRelatedEvents().Last(recorded => recorded.Name == name); + } + + private sealed class TestFileSystem : MockFileSystem + { + public TestFileSystem() + : base(CreateRoot()) + { + } + + public string FailRenameTo { get; set; } + + public override void MoveAndOverwriteFile(string sourcePath, string destinationPath) + { + if (string.Equals(destinationPath, this.FailRenameTo, StringComparison.OrdinalIgnoreCase)) + { + throw new IOException("Injected rename failure"); + } + + base.MoveAndOverwriteFile(sourcePath, destinationPath); + } + + private static MockDirectory CreateRoot() + { + MockDirectory info = new MockDirectory(InfoDir, folders: null, files: null); + MockDirectory git = new MockDirectory(GitDir, new[] { info }, files: null); + return new MockDirectory(RepoRoot, new[] { git }, files: null); + } + } + + private sealed class MockEnvironment : IConeManagerEnvironment + { + private readonly MockFileSystem fileSystem; + private int lockHeld; + + public MockEnvironment(MockFileSystem fileSystem) + { + this.fileSystem = fileSystem; + } + + public List ModifiedPaths { get; } = new List { ".gitattributes" }; + + public Dictionary RunningProcesses { get; } = new Dictionary(); + + public List ConeFilesAtApply { get; } = new List(); + + public List SparseDirectories { get; } = new List(); + + public HashSet DeletedFiles { get; } = new HashSet(); + + public bool SparseDirectoriesFail { get; set; } + + public Dictionary StartTimeResults { get; } = new Dictionary(); + + public bool IndexWriteAllowed { get; set; } = true; + + public int? LockHolder { get; set; } + + public int CanWriteIndexDelayMs { get; set; } + + public bool ConeFileLocked { get; set; } + + public int ApplyExitCode { get; set; } + + public Exception ApplyException { get; set; } + + public Action DuringApply { get; set; } + + public int LockCount { get; private set; } + + public bool IsConeFileLockHeld => this.lockHeld != 0; + + public bool SparsityChangeIsIndexOnly { get; set; } + + public bool IsPending { get; private set; } + + public int PendingFileCreateCount { get; private set; } + + public bool PendingFileFails { get; set; } + + public bool PendingFileDeleteFails { get; set; } + + public HashSet DifferingPaths { get; } = new HashSet(); + + public HashSet UntrackedFiles { get; } = new HashSet(); + + public bool DiffFails { get; set; } + + public int DiffCount { get; private set; } + + public Action DuringDiff { get; set; } + + public long RepositoryStamp { get; set; } + + public bool TrySetConeChangePending(bool pending, out Exception error) + { + if (this.PendingFileFails || (!pending && this.PendingFileDeleteFails)) + { + error = new IOException("Injected pending file failure"); + return false; + } + + if (pending && !this.IsPending) + { + this.PendingFileCreateCount++; + } + + this.IsPending = pending; + error = null; + return true; + } + + public bool TryGetPathsThatDifferFromHead(out ICollection paths, out string error) + { + this.DiffCount++; + this.DuringDiff?.Invoke(); + if (this.DiffFails) + { + paths = null; + error = "fatal: injected failure"; + return false; + } + + // Like Git: an untracked file that exists, and a tracked file that was deleted. + paths = this.DifferingPaths + .Concat(this.UntrackedFiles.Except(this.DeletedFiles)) + .Concat(this.DeletedFiles.Except(this.UntrackedFiles)) + .ToList(); + error = null; + return true; + } + + public long GetRepositoryStamp() + { + return this.RepositoryStamp; + } + + public IEnumerable GetModifiedPaths() + { + return this.ModifiedPaths.ToList(); + } + + public bool CanWriteIndex(int processId) + { + if (this.CanWriteIndexDelayMs > 0) + { + Thread.Sleep(this.CanWriteIndexDelayMs); + } + + return this.IndexWriteAllowed && (this.LockHolder == null || this.LockHolder == processId); + } + + public bool TryGetSparseDirectories(out IReadOnlyList sparseDirectories, out string error) + { + if (this.SparseDirectoriesFail) + { + sparseDirectories = null; + error = "fatal: injected failure"; + return false; + } + + sparseDirectories = this.SparseDirectories.ToList(); + error = null; + return true; + } + + public bool IsFileInWorkingDirectory(string gitPath) + { + return !this.DeletedFiles.Contains(gitPath); + } + + public bool TryLockConeFile(out IDisposable coneFileLock, out Exception error) + { + if (this.ConeFileLocked) + { + coneFileLock = null; + error = new IOException("sparse-checkout.lock: File exists"); + return false; + } + + // The manager must serialize requests, so the lock is never held twice. + Interlocked.Exchange(ref this.lockHeld, 1).ShouldEqual(0, "The cone file lock is already held"); + this.LockCount++; + coneFileLock = new Releaser(() => Interlocked.Exchange(ref this.lockHeld, 0)); + error = null; + return true; + } + + public GitProcess.Result ApplyConeToIndex() + { + this.ConeFilesAtApply.Add(this.fileSystem.ReadAllText(SparseCheckoutPath)); + this.DuringApply?.Invoke(); + if (this.ApplyException != null) + { + throw this.ApplyException; + } + + return new GitProcess.Result(string.Empty, this.ApplyExitCode == 0 ? string.Empty : "fatal: Unable to write new index file", this.ApplyExitCode); + } + + public ProcessStartTimeResult TryGetProcessStartTime(int processId, out long startTime) + { + lock (this.RunningProcesses) + { + if (this.StartTimeResults.TryGetValue(processId, out ProcessStartTimeResult result)) + { + startTime = 0; + return result; + } + + if (this.RunningProcesses.TryGetValue(processId, out startTime)) + { + return ProcessStartTimeResult.Success; + } + } + + return ProcessStartTimeResult.ProcessNotFound; + } + + private sealed class Releaser : IDisposable + { + private readonly Action release; + + public Releaser(Action release) + { + this.release = release; + } + + public void Dispose() + { + this.release(); + } + } + } + } +} 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/ConeCoverageTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/ConeCoverageTests.cs new file mode 100644 index 000000000..d8fe1ee52 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/ConeCoverageTests.cs @@ -0,0 +1,165 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class ConeCoverageTests + { + private const string Header = "/*\n!/*/\n"; + + [TestCase] + public void ParseReadsBackWhatTheWriterWrites() + { + ConePatternSet written = new ConePatternSet( + new[] { "A", "A/B", "W" }, + new[] { "A/B/C", "W/x*y", "Q[1]" }, + ignoreCase: false); + + ConeCoverage.TryParseConeFile(ConeFileWriter.Serialize(written), ignoreCase: false, out ConePatternSet read).ShouldBeTrue(); + + read.ParentOnlyDirectories.ShouldMatchInOrder("A", "A/B", "W"); + read.RecursiveDirectories.ShouldMatchInOrder("A/B/C", "W/x*y", "Q[1]"); + read.IgnoreCase.ShouldBeFalse(); + } + + [TestCase] + public void ParseAcceptsCrLfLineEndings() + { + ConeCoverage.TryParseConeFile("/*\r\n!/*/\r\n/A/\r\n", ignoreCase: true, out ConePatternSet read).ShouldBeTrue(); + read.RecursiveDirectories.ShouldMatchInOrder("A"); + read.IgnoreCase.ShouldBeTrue(); + } + + [TestCase] + public void ParseAcceptsHeaderOnly() + { + ConeCoverage.TryParseConeFile(Header, ignoreCase: false, out ConePatternSet read).ShouldBeTrue(); + read.ParentOnlyDirectories.ShouldBeEmpty(); + read.RecursiveDirectories.ShouldBeEmpty(); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("/A/\n")] + [TestCase("/*\n/A/\n")] + [TestCase("!/*/\n/*\n/A/\n")] + [TestCase("/A/\n/*\n!/*/\n")] + [TestCase(Header + "!/A/*/\n")] + [TestCase(Header + "!/A/*/\n/A/\n")] + [TestCase(Header + "/A/\n!/A/*/\n!/A/*/\n")] + [TestCase(Header + "/A/\n!/A/*/\n/A/\n")] + [TestCase(Header + "/A*/\n")] + [TestCase(Header + "/A\\b/\n")] + [TestCase(Header + "/A\uFFFD/\n")] + [TestCase(Header + "/A/\n/A/\n")] + [TestCase(Header + "/A/./B/\n")] + [TestCase(Header + "/A\n")] + [TestCase(Header + "!/A/\n")] + public void ParseRejectsFilesThatGitDoesNotReadAsTheSameCone(string content) + { + ConeCoverage.TryParseConeFile(content, ignoreCase: false, out ConePatternSet read).ShouldBeFalse(); + read.ShouldBeNull(); + } + + [TestCase] + public void ParseAcceptsDirectoriesWithoutTheirAncestors() + { + // Git's reader does not add the ancestors of a cone directory, and neither does + // ConePathMatcher, so both read this file with the same meaning. + ConeCoverage.TryParseConeFile(Header + "/A/B/\n/C/\n!/C/*/\n/C/D/E/\n", ignoreCase: false, out ConePatternSet read).ShouldBeTrue(); + read.ParentOnlyDirectories.ShouldMatchInOrder("C"); + read.RecursiveDirectories.ShouldMatchInOrder("A/B", "C/D/E"); + + ConeCoverage coverage = new ConeCoverage(read); + coverage.IsCovered("A/B/file.txt").ShouldBeTrue(); + coverage.IsCovered("A/file.txt").ShouldBeFalse(); + } + + [TestCase("/*\n!/*/\n", true)] + [TestCase("\n/*\r\n\r\n!/*/\r\n/A/\n", true)] + [TestCase("# written by a tool\n/*\n# root files\n!/*/\n", true)] + [TestCase("/.gitattributes\r\n", false)] + [TestCase("!/*/\n/*\n", false)] + [TestCase("/*\n/A/\n!/*/\n", false)] + [TestCase("", false)] + [TestCase(null, false)] + public void HasConeHeaderNeedsTheHeaderLinesFirst(string content, bool expected) + { + ConeCoverage.HasConeHeader(content).ShouldEqual(expected); + } + + [TestCase] + public void ParseSkipsCommentLinesAsGitDoes() + { + ConeCoverage.TryParseConeFile("# note\n" + Header + "# A is recursive\n/A/\n", ignoreCase: false, out ConePatternSet read).ShouldBeTrue(); + read.RecursiveDirectories.ShouldMatchInOrder("A"); + } + + [TestCase] + public void DecodeSkipsOnlyAUtf8ByteOrderMark() + { + byte[] utf8 = Encoding.UTF8.GetBytes(Header + "/Ä/\n"); + byte[] utf8WithBom = new byte[] { 0xEF, 0xBB, 0xBF }.Concat(utf8).ToArray(); + ConeCoverage.DecodeConeFile(utf8WithBom).ShouldEqual(Header + "/Ä/\n"); + ConeCoverage.DecodeConeFile(utf8).ShouldEqual(Header + "/Ä/\n"); + + byte[] utf16WithBom = Encoding.Unicode.GetPreamble().Concat(Encoding.Unicode.GetBytes(Header + "/A/\n")).ToArray(); + ConeCoverage.HasConeHeader(ConeCoverage.DecodeConeFile(utf16WithBom)).ShouldBeFalse(); + } + + [TestCase] + public void ParseAppliesTheCaseRule() + { + string content = Header + "/A/\n/a/\n"; + + ConeCoverage.TryParseConeFile(content, ignoreCase: false, out ConePatternSet caseSensitive).ShouldBeTrue(); + caseSensitive.RecursiveDirectories.ShouldMatchInOrder("A", "a"); + + ConeCoverage.TryParseConeFile(content, ignoreCase: true, out ConePatternSet caseInsensitive).ShouldBeFalse(); + caseInsensitive.ShouldBeNull(); + } + + [TestCase("root.txt", true)] + [TestCase("A/file.txt", true)] + [TestCase("A/Other/file.txt", false)] + [TestCase("A/B/file.txt", true)] + [TestCase("A/B/deep/er/file.txt", true)] + [TestCase("Z/file.txt", false)] + [TestCase("A/B/", true)] + [TestCase("A/B/deep/", true)] + [TestCase("A/", false)] + [TestCase("A/Other/", false)] + [TestCase("Z/", false)] + public void IsCoveredFollowsTheCone(string path, bool expected) + { + CreateCoverage(ignoreCase: false).IsCovered(path).ShouldEqual(expected); + } + + [TestCase(true, true)] + [TestCase(false, false)] + public void IsCoveredUsesTheCaseRule(bool ignoreCase, bool expected) + { + ConeCoverage coverage = CreateCoverage(ignoreCase); + coverage.IsCovered("a/b/file.txt").ShouldEqual(expected); + coverage.IsCovered("a/b/sub/").ShouldEqual(expected); + } + + [TestCase] + public void GetUncoveredPathsKeepsInputOrder() + { + CreateCoverage(ignoreCase: false) + .GetUncoveredPaths(new[] { "Z/z.txt", "A/a.txt", "Y/", "A/B/b.txt", "A/" }) + .ShouldMatchInOrder("Z/z.txt", "Y/", "A/"); + } + + private static ConeCoverage CreateCoverage(bool ignoreCase) + { + return new ConeCoverage(new ConePatternSet(new[] { "A" }, new[] { "A/B" }, ignoreCase)); + } + } +} 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/ConePathspecResolverTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/ConePathspecResolverTests.cs new file mode 100644 index 000000000..c72b9789a --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/ConePathspecResolverTests.cs @@ -0,0 +1,174 @@ +using System.Collections.Generic; +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using NUnit.Framework; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class ConePathspecResolverTests + { + private const string Root = "C:/repo/src"; + + [TestCase] + public void RelativeFileResolvesAgainstBaseDirectory() + { + Resolve("C:/repo/src/A", "b.txt").ShouldMatchInOrder("A/b.txt"); + } + + [TestCase] + public void RelativeNestedFileKeepsFullPath() + { + Resolve("C:/repo/src/A", "B/c.txt").ShouldMatchInOrder("A/B/c.txt"); + } + + [TestCase] + public void TrailingSlashMarksRecursiveFolder() + { + Resolve("C:/repo/src/A", "sub/").ShouldMatchInOrder("A/sub/"); + } + + [TestCase] + public void FileAtRepoRootResolvesToBareName() + { + Resolve(Root, "root.txt").ShouldMatchInOrder("root.txt"); + } + + [TestCase] + public void DotSegmentsAreCollapsed() + { + Resolve("C:/repo/src/A", "./B/./c.txt").ShouldMatchInOrder("A/B/c.txt"); + } + + [TestCase] + public void DotDotClimbsToSibling() + { + Resolve("C:/repo/src/A", "../D/d.txt").ShouldMatchInOrder("D/d.txt"); + } + + [TestCase] + public void DotDotThatEscapesRootIsSkipped() + { + // From C:/repo/src/A, ../.. is C:/repo, which is above the worktree root. + Resolve("C:/repo/src/A", "../../outside.txt").ShouldBeEmpty(); + } + + [TestCase] + public void BackslashesAreNormalized() + { + Resolve("C:\\repo\\src\\A", "B\\c.txt").ShouldMatchInOrder("A/B/c.txt"); + } + + [TestCase] + public void AbsolutePathUnderRootIsMadeRelative() + { + Resolve("C:/repo/src", "C:/repo/src/X/y.txt").ShouldMatchInOrder("X/y.txt"); + } + + [TestCase] + public void AbsolutePathOutsideRootIsSkipped() + { + Resolve("C:/repo/src", "C:/other/z.txt").ShouldBeEmpty(); + } + + [TestCase] + public void RootPrefixMatchIsCaseInsensitiveButSuffixCasingIsKept() + { + Resolve("C:/repo/src", "C:/REPO/SRC/Keep/Case.txt").ShouldMatchInOrder("Keep/Case.txt"); + } + + [TestCase] + public void PathspecEqualToRootIsSkipped() + { + Resolve("C:/repo/src", "C:/repo/src").ShouldBeEmpty(); + } + + [TestCase] + public void MagicPathspecIsSkipped() + { + Resolve("C:/repo/src", ":(glob)**/*.txt").ShouldBeEmpty(); + Resolve("C:/repo/src", ":/top.txt").ShouldBeEmpty(); + } + + [TestCase] + public void DuplicateResultsAreDeduplicated() + { + Resolve("C:/repo/src/A", "b.txt", "./b.txt").ShouldMatchInOrder("A/b.txt"); + } + + [TestCase] + public void EmptyAndNullPathspecsAreSkipped() + { + Resolve("C:/repo/src", string.Empty, null, "keep.txt").ShouldMatchInOrder("keep.txt"); + } + + [TestCase] + public void NullPathspecEnumerableYieldsEmpty() + { + ConePathspecResolver.ResolveToGitPaths(Root, Root, null).ShouldBeEmpty(); + } + + [TestCase] + public void FileAndFolderShapesAreDistinctEntries() + { + Resolve("C:/repo/src", "A", "A/").ShouldMatchInOrder("A", "A/"); + } + + [TestCase] + public void WildcardInFileNameIsKept() + { + Resolve("C:/repo/src/A", "*.cs", "B/f?le.txt").ShouldMatchInOrder("A/*.cs", "A/B/f?le.txt"); + } + + [TestCase] + public void WildcardInDirectorySegmentIsSkipped() + { + Resolve("C:/repo/src", "*/a.txt", "A/[bc]/d.txt", "A/B*/", "**/x.cs", "keep/a.txt") + .ShouldMatchInOrder("keep/a.txt"); + } + + [TestCase("C:/repo/src", null, "C:/repo/src")] + [TestCase("C:/repo/src", "", "C:/repo/src")] + [TestCase("C:/repo/src", "A/B/", "C:/repo/src/A/B")] + [TestCase("C:\\REPO\\src\\", "A\\B\\", "C:/repo/src/A/B")] + [TestCase("C:/repo/src/A", "B/", "C:/repo/src/A")] + public void PathspecBaseDirectoryAppliesPrefixOnlyAtWorktreeRoot(string hookCurrentDirectory, string gitPrefix, string expected) + { + string actual = ConePathspecResolver.GetPathspecBaseDirectory(hookCurrentDirectory, Root, gitPrefix); + actual.Replace('\\', '/').TrimEnd('/').ShouldEqual(expected); + } + + [TestCase] + public void PrefixedBaseDirectoryResolvesRelativePathspecs() + { + string baseDirectory = ConePathspecResolver.GetPathspecBaseDirectory(Root, Root, "A/B/"); + ConePathspecResolver.ResolveToGitPaths(baseDirectory, Root, new[] { "c.txt", "../d/" }) + .ShouldMatchInOrder("A/B/c.txt", "A/d/"); + } + + [TestCase("../outside/")] + [TestCase("A/../../outside/")] + [TestCase("C:/Windows/")] + [TestCase("D:relative/")] + [TestCase("/rooted/")] + [TestCase("A//B/")] + public void PrefixThatCanLeaveTheWorktreeIsIgnored(string gitPrefix) + { + ConePathspecResolver.GetPathspecBaseDirectory(Root, Root, gitPrefix).ShouldEqual(Root); + } + + [TestCase("D:dir/file.txt")] + [TestCase("A/stream.txt:alternate")] + [TestCase("A/line\nbreak.txt")] + [TestCase("A/frame\u0003end.txt")] + public void PathThatIsNotAValidGitPathIsSkipped(string pathspec) + { + Resolve("C:/repo/src", pathspec, "keep.txt").ShouldMatchInOrder("keep.txt"); + } + + private static IReadOnlyList Resolve(string baseDirectory, params string[] pathspecs) + { + return ConePathspecResolver.ResolveToGitPaths(baseDirectory, Root, pathspecs); + } + } +} 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/Sparse/SparseDirectoryExpansionGuardTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/SparseDirectoryExpansionGuardTests.cs new file mode 100644 index 000000000..ae92d28d9 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/SparseDirectoryExpansionGuardTests.cs @@ -0,0 +1,51 @@ +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using NUnit.Framework; +using System.Collections.Generic; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class SparseDirectoryExpansionGuardTests + { + [TestCase("A/B/f.txt", "A/", true)] + [TestCase("A/f.txt", "A/", true)] + [TestCase("A/", "A/", true)] + [TestCase("B/f.txt", "A/", false)] + [TestCase("AB/f.txt", "A/", false)] + [TestCase("f.txt", "A/", false)] + [TestCase("A/", "A/B/", true)] + [TestCase("A/f.txt", "A/B/", false)] + [TestCase("a/b/f.txt", "A/", true)] + public void FindHiddenModifiedPathsFindsPathsInsideOrAroundASparseDirectory(string modifiedPath, string sparseDirectory, bool hidden) + { + List result = SparseDirectoryExpansionGuard.FindHiddenModifiedPaths(new[] { modifiedPath }, new[] { sparseDirectory }, ignoreCase: true); + + (result.Count == 1).ShouldEqual(hidden); + } + + [TestCase] + public void FindHiddenModifiedPathsUsesTheCaseRule() + { + SparseDirectoryExpansionGuard.FindHiddenModifiedPaths(new[] { "a/f.txt" }, new[] { "A/" }, ignoreCase: false).ShouldBeEmpty(); + } + + [TestCase("A/B/b.txt", "A/B/deleted.txt", true)] + [TestCase("A/B/", "A/B/C/deleted.txt", true)] + [TestCase("A/B/b.txt", "A/X/deleted.txt", false)] + [TestCase("A/B/b.txt", "A/deleted.txt", true)] + [TestCase("A/b.txt", "A/B/", false)] + [TestCase("A/B/C/c.txt", "A/B/", true)] + [TestCase("A/", "A/B/", true)] + [TestCase("C/c.txt", "A/B/deleted.txt", false)] + public void FindReachedPathReturnsAPathWhoseDirectoryTheConeIncludes(string conePath, string unsafePath, bool reached) + { + ConePatternSet cone = ConeBuilder.BuildFromModifiedPaths(new[] { conePath }, ignoreCase: false); + + string result = SparseDirectoryExpansionGuard.FindReachedPath(cone, new[] { unsafePath }, ignoreCase: false); + + (result == unsafePath).ShouldEqual(reached); + (result == null).ShouldEqual(!reached); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/TransientConeStateTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/TransientConeStateTests.cs new file mode 100644 index 000000000..0d4006d9e --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/Sparse/TransientConeStateTests.cs @@ -0,0 +1,93 @@ +using GVFS.Common.Sparse; +using GVFS.Tests.Should; +using NUnit.Framework; +using System.Collections.Generic; +using System.Linq; + +namespace GVFS.UnitTests.Common.Sparse +{ + [TestFixture] + public class TransientConeStateTests + { + [TestCase] + public void PathsOfAllCommandsAreKeptUntilEachCommandIsRemoved() + { + TransientConeState state = new TransientConeState(); + state.Add(100, startTime: 1, new[] { "A/a.txt", "B/" }); + state.Add(200, startTime: 2, new[] { "A/a.txt", "C/c.txt" }); + + Sorted(state.GetAllPaths()).ShouldMatchInOrder("A/a.txt", "B/", "C/c.txt"); + + state.Remove(100, startTime: 1).ShouldBeTrue(); + Sorted(state.GetAllPaths()).ShouldMatchInOrder("A/a.txt", "C/c.txt"); + + state.Remove(200, startTime: 2).ShouldBeTrue(); + state.GetAllPaths().ShouldBeEmpty(); + state.CommandCount.ShouldEqual(0); + } + + [TestCase] + public void RepeatedAddOfOneCommandKeepsThePathsOfBothRequests() + { + TransientConeState state = new TransientConeState(); + state.Add(100, startTime: 1, new[] { "A/a.txt" }); + state.Add(100, startTime: 1, new[] { "B/b.txt" }); + + Sorted(state.GetAllPaths()).ShouldMatchInOrder("A/a.txt", "B/b.txt"); + state.CommandCount.ShouldEqual(1); + } + + [TestCase] + public void AddForAReusedProcessIdReplacesThePathsOfTheEndedProcess() + { + TransientConeState state = new TransientConeState(); + state.Add(100, startTime: 1, new[] { "A/a.txt" }); + state.Add(100, startTime: 2, new[] { "B/b.txt" }); + + state.GetAllPaths().ShouldMatchInOrder("B/b.txt"); + } + + [TestCase] + public void RemoveOfACommandWithoutPathsRecordsItAsNarrowed() + { + TransientConeState state = new TransientConeState(); + + state.Remove(100, startTime: 1).ShouldBeFalse(); + + state.IsNarrowed(100, startTime: 1).ShouldBeTrue(); + state.IsNarrowed(100, startTime: null).ShouldBeTrue(); + state.IsNarrowed(100, startTime: 2).ShouldBeFalse("Another process has this id"); + state.IsNarrowed(200, startTime: 1).ShouldBeFalse(); + } + + [TestCase] + public void RemoveWithoutAStartTimeRecordsNoNarrowedCommand() + { + TransientConeState state = new TransientConeState(); + + state.Remove(100, startTime: null).ShouldBeFalse(); + + state.IsNarrowed(100, startTime: 1).ShouldBeFalse(); + } + + [TestCase] + public void RemoveEndedRemovesThePathsAndNarrowedRecordsOfEndedProcesses() + { + TransientConeState state = new TransientConeState(); + state.Add(100, startTime: 1, new[] { "A/a.txt" }); + state.Add(200, startTime: 2, new[] { "B/b.txt" }); + state.Remove(300, startTime: 3); + HashSet running = new HashSet { 200 }; + + state.RemoveEnded((processId, startTime) => running.Contains(processId)).ShouldEqual(1); + + state.GetAllPaths().ShouldMatchInOrder("B/b.txt"); + state.IsNarrowed(300, startTime: 3).ShouldBeFalse(); + } + + private static IEnumerable Sorted(IEnumerable paths) + { + return paths.OrderBy(path => path, System.StringComparer.Ordinal); + } + } +} 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/GVFS.UnitTests.csproj b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj index 42ed65d1d..cc9c71a9a 100644 --- a/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj +++ b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj @@ -28,6 +28,18 @@ + + Hooks\ConeManagementHook.cs + + + Hooks\ConeRequestOutcome.cs + + + Hooks\PendingConeChangeHook.cs + + + Hooks\PreCommandConeRequests.cs + Hooks\GitCommandLock.cs diff --git a/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs b/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs index 6af3f9c9c..cff508e14 100644 --- a/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs +++ b/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs @@ -30,6 +30,19 @@ public void ReadStdOutTokens_SplitsOnNul() tokens.ShouldMatchInOrder("a.txt", "d/b.txt", "d/c.txt"); } + [TestCase("1 .M N... 100644 100644 100644 0123 0123 d/a.txt", "d/a.txt")] + [TestCase("1 D. N... 100644 000000 000000 0123 0000 d/with space.txt", "d/with space.txt")] + [TestCase("u UU N... 100644 100644 100644 100644 0123 0456 0789 d/conflict.txt", "d/conflict.txt")] + [TestCase("? d/untracked.txt", "d/untracked.txt")] + [TestCase("? d/new folder/", "d/new folder/")] + [TestCase("! d/ignored.txt", null)] + [TestCase("# branch.oid 0123", null)] + [TestCase("1 .M N... 100644", null)] + public void GetPorcelainV2PathReturnsThePathOfAChangedEntry(string record, string expectedPath) + { + GitProcess.GetPorcelainV2Path(record).ShouldEqual(expectedPath); + } + [TestCase] public void ReadStdOutTokens_EmptyInputYieldsNoTokens() { diff --git a/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs b/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs new file mode 100644 index 000000000..16ab7bc26 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs @@ -0,0 +1,432 @@ +using GVFS.Common.NamedPipes; +using GVFS.Hooks; +using GVFS.UnitTests.Mock.Common; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Threading; + +namespace GVFS.UnitTests.Hooks +{ + [TestFixture] + public class ConeManagementHookTests + { + private const string Root = "C:\\repo\\src"; + private const string Header = "/*\n!/*/\n"; + private const string ConeWithRecursiveA = Header + "/A/\n"; + private const string ConeWithParentOnlyA = Header + "/A/\n!/A/*/\n"; + private const string GitPid = "--git-pid=1234"; + + // Tests that expect a reply use a long budget, so that a slow test machine cannot turn + // the reply into a timeout. + private const int ReplyBudgetMs = 30000; + + private bool featureEnabled; + private int configReadCount; + private string coneFileContent; + private List createdClients; + private Func clientFactory; + + [SetUp] + public void SetUp() + { + this.featureEnabled = true; + this.configReadCount = 0; + this.coneFileContent = ConeWithRecursiveA; + this.createdClients = new List(); + this.clientFactory = () => ReplyWith(NamedPipeMessages.ConeManagement.SuccessResult); + } + + [TestCase] + public void WidenWithFeatureOffSendsNothing() + { + this.featureEnabled = false; + + this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.FeatureDisabled); + + this.configReadCount.ShouldEqual(1); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase(null)] + [TestCase("/.gitattributes\r\n")] + [TestCase("/A/\n")] + public void WithoutConeModeFileNeitherHookReadsConfigOrSends(string content) + { + this.coneFileContent = content; + + this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.NoConeFile); + this.Narrow("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.NoConeFile); + + this.configReadCount.ShouldEqual(0); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase(null, true, false, 0)] + [TestCase("/A/\n", true, false, 0)] + [TestCase(ConeWithRecursiveA, false, false, 1)] + [TestCase(ConeWithRecursiveA, true, true, 1)] + public void IsSparseIndexConeManagedUsesTheGateOfAWiden(string content, bool enabled, bool expected, int expectedConfigReads) + { + this.coneFileContent = content; + this.featureEnabled = enabled; + + this.CreateHook().IsSparseIndexConeManaged().ShouldEqual(expected); + + this.configReadCount.ShouldEqual(expectedConfigReads); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase("status")] + [TestCase("commit", "-m", "message")] + [TestCase("checkout", "topic")] + public void WidenForCommandWithoutPathsDoesNotReadConfig(params string[] command) + { + this.Widen(command).ShouldEqual(ConeRequestOutcome.NoPathsNamed); + + this.configReadCount.ShouldEqual(0); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase] + public void WidenTreatsAnAmbiguousRefOrPathAsARef() + { + // Without "--", git diff can read "Z/z.txt" as a revision, so the parser does not + // count it as a path, and the hook does not widen. + this.Widen("diff", "HEAD", "Z/z.txt").ShouldEqual(ConeRequestOutcome.NoPathsNamed); + } + + [TestCase("add", "A/a.txt")] + [TestCase("add", "A/deep/er/")] + [TestCase("rm", "root.txt")] + [TestCase("restore", "--staged", "A/a.txt", "root.txt")] + [TestCase("checkout", "HEAD", "--", "A/a.txt")] + public void WidenForInConePathsSendsNoRequest(params string[] command) + { + this.Widen(command).ShouldEqual(ConeRequestOutcome.SkippedInCone); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase] + public void WidenUsesTheRepositoryCaseRule() + { + this.CreateHook(ignoreCase: true).TrySendWiden(BuildArgs("add", "a/a.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.SkippedInCone); + this.CreateHook(ignoreCase: false).TrySendWiden(BuildArgs("add", "a/a.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.Applied); + } + + [TestCase] + public void WidenSendsOnlyTheOutOfConePaths() + { + this.Widen("add", "A/a.txt", "Z/z.txt", ":(glob)**/*.cs", ".").ShouldEqual(ConeRequestOutcome.Applied); + + NamedPipeMessages.ConeManagement.WidenParameters parameters = this.GetSingleWidenRequest(); + parameters.CommandId.ShouldEqual("1234"); + parameters.Paths.ShouldMatchInOrder("Z/z.txt"); + } + + [TestCase("A/")] + [TestCase("Z/")] + public void WidenForFolderNeedsTheWholeSubtreeInCone(string folder) + { + this.coneFileContent = ConeWithParentOnlyA; + + this.Widen("add", folder).ShouldEqual(ConeRequestOutcome.Applied); + this.GetSingleWidenRequest().Paths.ShouldMatchInOrder(folder); + } + + [TestCase] + public void WidenResolvesRelativePathsAgainstGitPrefix() + { + this.coneFileContent = ConeWithParentOnlyA; + + this.CreateHook(gitPrefix: "B/").TrySendWiden(BuildArgs("add", "x.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.Applied); + this.GetSingleWidenRequest().Paths.ShouldMatchInOrder("B/x.txt"); + + this.createdClients.Clear(); + this.CreateHook(gitPrefix: "A/").TrySendWiden(BuildArgs("add", "x.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.SkippedInCone); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase(Header + "/A*/\n", false)] + [TestCase(Header + "/A/\n/a/\n", true)] + public void WidenSendsEveryPathWhenTheConeFileCannotBeTrusted(string content, bool ignoreCase) + { + this.coneFileContent = content; + + this.CreateHook(ignoreCase: ignoreCase).TrySendWiden(BuildArgs("add", "A/a.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.Applied); + this.GetSingleWidenRequest().Paths.ShouldMatchInOrder("A/a.txt"); + } + + [TestCase("add", "C:\\other\\file.txt")] + [TestCase("add", "../outside.txt")] + [TestCase("add", "A/*/x.txt")] + [TestCase("add", "Z/frame\u0003end.txt")] + [TestCase("add", ":(glob)**/*.cs")] + [TestCase("add", ".")] + [TestCase("add", "--pathspec-from-file=list.txt")] + public void WidenSendsNothingForPathsWithoutAConeEntry(params string[] command) + { + this.Widen(command).ShouldEqual(ConeRequestOutcome.NoResolvablePaths); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase("-C", "sub")] + [TestCase("--git-dir=other")] + [TestCase("--work-tree", "other")] + public void WidenSendsNothingWhenAGlobalOptionChangesTheRepository(params string[] globalOptions) + { + List command = new List(globalOptions) { "add", "Z/z.txt" }; + + this.Widen(command.ToArray()).ShouldEqual(ConeRequestOutcome.NoResolvablePaths); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase] + public void WidenForStashSendsNoRequest() + { + this.Widen("stash", "push", "--", "Z/z.txt").ShouldEqual(ConeRequestOutcome.SkippedStash); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase(NamedPipeMessages.UnknownRequest)] + [TestCase(NamedPipeMessages.MountNotReadyResult)] + [TestCase(NamedPipeMessages.ConeManagement.FailureResult)] + [TestCase(NamedPipeMessages.ConeManagement.NotEnabledResult)] + public void WidenWithNonSuccessReplyLetsGitRun(string responseHeader) + { + this.clientFactory = () => ReplyWith(responseHeader); + + this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.Rejected); + this.createdClients[0].Requests.Count.ShouldEqual(1); + } + + [TestCase] + public void WidenWithoutMountLetsGitRun() + { + this.clientFactory = NoMount; + + this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.MountUnavailable); + this.createdClients[0].Requests.ShouldBeEmpty(); + this.createdClients[0].ConnectTimeoutMs.ShouldEqual(NamedPipeMessages.ConeManagement.ConnectTimeoutMs); + this.createdClients[0].Disposed.ShouldBeTrue(); + } + + [TestCase] + public void WidenWaitsForTheReplyAfterTheWaitBudget() + { + ManualResetEventSlim releaseReply = new ManualResetEventSlim(initialState: false); + this.clientFactory = () => ReplyAfter(releaseReply); + using (Timer releaseLater = new Timer(_ => releaseReply.Set(), null, dueTime: 300, period: Timeout.Infinite)) + { + Stopwatch stopwatch = Stopwatch.StartNew(); + this.CreateHook().TrySendWiden(BuildArgs("add", "Z/z.txt"), waitBudgetMs: 50, replyCeilingMs: ReplyBudgetMs) + .ShouldEqual(ConeRequestOutcome.Applied); + stopwatch.Stop(); + + (stopwatch.ElapsedMilliseconds >= 250).ShouldBeTrue("The hook must wait for the reply after it sent the widen."); + } + } + + [TestCase] + public void WidenWithoutAReplyLetsGitRunAtTheReplyCeiling() + { + // The event is not disposed, because the abandoned request task still waits on it. + ManualResetEventSlim releaseReply = new ManualResetEventSlim(initialState: false); + this.clientFactory = () => ReplyAfter(releaseReply); + + Stopwatch stopwatch = Stopwatch.StartNew(); + this.CreateHook().TrySendWiden(BuildArgs("add", "Z/z.txt"), waitBudgetMs: ReplyBudgetMs, replyCeilingMs: 50) + .ShouldEqual(ConeRequestOutcome.ReplyTimedOut); + stopwatch.Stop(); + releaseReply.Set(); + + (stopwatch.ElapsedMilliseconds < 5000).ShouldBeTrue("The hook must not wait for the reply after the ceiling ends."); + } + + [TestCase] + public void WidenThatCannotSendInTheWaitBudgetLetsGitRunAndNeverSends() + { + ManualResetEventSlim releaseConnect = new ManualResetEventSlim(initialState: false); + this.clientFactory = () => new MockNamedPipeClient + { + ConnectCallback = () => releaseConnect.Wait(), + Response = new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null), + }; + + Stopwatch stopwatch = Stopwatch.StartNew(); + this.CreateHook().TrySendWiden(BuildArgs("add", "Z/z.txt"), waitBudgetMs: 50, replyCeilingMs: ReplyBudgetMs) + .ShouldEqual(ConeRequestOutcome.TimedOut); + stopwatch.Stop(); + (stopwatch.ElapsedMilliseconds < 5000).ShouldBeTrue("The hook must not wait for the reply ceiling when it did not send."); + + // The test lets the abandoned task connect, then checks that the task did not send. + releaseConnect.Set(); + SpinWait.SpinUntil(() => this.createdClients.Count == 1 && this.createdClients[0].Disposed, 5000).ShouldBeTrue(); + this.createdClients[0].Requests.ShouldBeEmpty(); + } + + [TestCase] + public void WidenThatThrowsLetsGitRun() + { + this.clientFactory = () => new MockNamedPipeClient { SendError = new BrokenPipeException("send failed", null) }; + this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.Failed); + + this.clientFactory = () => throw new InvalidOperationException("no client"); + this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.Failed); + + ConeManagementHook throwingConfig = new ConeManagementHook( + (out bool ignoreCase) => throw new InvalidOperationException("config"), + () => this.coneFileContent, + () => throw new InvalidOperationException("no client"), + Root, + () => Root, + null, + null); + throwingConfig.TrySendWiden(BuildArgs("add", "Z/z.txt")).ShouldEqual(ConeRequestOutcome.Failed); + throwingConfig.TrySendNarrow(BuildArgs("add", "Z/z.txt")).ShouldEqual(ConeRequestOutcome.Failed); + } + + [TestCase] + public void NarrowWithFeatureOffSendsNothing() + { + this.featureEnabled = false; + + this.Narrow("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.FeatureDisabled); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase] + public void NarrowSendsTheGitProcessIdFromThePostCommandArguments() + { + string[] postCommandArgs = new[] { "post-command", "add", "A/a.txt", "--git-pid=1234", "--exit_code=0" }; + + this.CreateHook().TrySendNarrow(postCommandArgs, ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.Applied); + + NamedPipeMessages.Message request = this.createdClients[0].Requests[0]; + request.Header.ShouldEqual(NamedPipeMessages.ConeManagement.NarrowRequest); + NamedPipeMessages.ConeManagement.NarrowParameters.TryParse(request.Body, out NamedPipeMessages.ConeManagement.NarrowParameters parameters).ShouldBeTrue(); + parameters.CommandId.ShouldEqual("1234"); + } + + [TestCase] + public void NarrowSkipsCommandsThatCannotWiden() + { + this.Narrow("status").ShouldEqual(ConeRequestOutcome.NoPathsNamed); + this.Narrow("stash", "push", "--", "Z/z.txt").ShouldEqual(ConeRequestOutcome.SkippedStash); + this.createdClients.ShouldBeEmpty(); + } + + [TestCase] + public void NarrowFailuresLetGitFinish() + { + this.clientFactory = NoMount; + this.Narrow("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.MountUnavailable); + + this.clientFactory = () => ReplyWith(NamedPipeMessages.UnknownRequest); + this.Narrow("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.Rejected); + + ManualResetEventSlim releaseReply = new ManualResetEventSlim(initialState: false); + this.clientFactory = () => ReplyAfter(releaseReply); + this.CreateHook().TrySendNarrow(BuildArgs("add", "Z/z.txt"), waitBudgetMs: 50).ShouldEqual(ConeRequestOutcome.TimedOut); + releaseReply.Set(); + } + + [TestCase] + public void FailedRequestsWriteADiagnostic() + { + List messages = new List(); + this.clientFactory = () => ReplyWith(NamedPipeMessages.UnknownRequest); + + this.CreateHook(trace: messages.Add).TrySendWiden(BuildArgs("add", "Z/z.txt"), ReplyBudgetMs); + this.CreateHook(trace: messages.Add).TrySendNarrow(BuildArgs("add", "Z/z.txt"), ReplyBudgetMs); + + messages.ShouldMatchInOrder("widen not applied: Rejected", "narrow not applied: Rejected"); + } + + [TestCase(new[] { "pre-command", "add", "a.txt", "--git-pid=77" }, "77")] + [TestCase(new[] { "post-command", "add", "a.txt", "--git-pid=77", "--exit_code=0" }, "77")] + [TestCase(new[] { "pre-command", "diff", "--", "--git-pid=99", "--git-pid=77" }, "77")] + [TestCase(new[] { "pre-command", "add", "a.txt", "--git-pid=12a" }, "")] + [TestCase(new[] { "pre-command", "add", "a.txt" }, "")] + public void CommandIdIsTheGitProcessId(string[] args, string expected) + { + ConeManagementHook.GetCommandId(args).ShouldEqual(expected); + } + + private static string[] BuildArgs(params string[] command) + { + List args = new List { "pre-command" }; + args.AddRange(command); + args.Add(GitPid); + return args.ToArray(); + } + + private ConeRequestOutcome Widen(params string[] command) + { + return this.CreateHook().TrySendWiden(BuildArgs(command), ReplyBudgetMs); + } + + private ConeRequestOutcome Narrow(params string[] command) + { + return this.CreateHook().TrySendNarrow(BuildArgs(command), ReplyBudgetMs); + } + + private ConeManagementHook CreateHook(string gitPrefix = null, bool ignoreCase = false, Action trace = null) + { + return new ConeManagementHook( + (out bool readIgnoreCase) => + { + this.configReadCount++; + readIgnoreCase = ignoreCase; + return this.featureEnabled; + }, + () => this.coneFileContent, + () => + { + MockNamedPipeClient client = this.clientFactory(); + this.createdClients.Add(client); + return client; + }, + Root, + () => Root, + gitPrefix, + trace); + } + + private NamedPipeMessages.ConeManagement.WidenParameters GetSingleWidenRequest() + { + this.createdClients.Count.ShouldEqual(1); + this.createdClients[0].Requests.Count.ShouldEqual(1); + + NamedPipeMessages.Message request = this.createdClients[0].Requests[0]; + request.Header.ShouldEqual(NamedPipeMessages.ConeManagement.WidenRequest); + NamedPipeMessages.ConeManagement.WidenParameters.TryParse(request.Body, out NamedPipeMessages.ConeManagement.WidenParameters parameters).ShouldBeTrue(); + return parameters; + } + + private static MockNamedPipeClient ReplyWith(string responseHeader) + { + return new MockNamedPipeClient { Response = new NamedPipeMessages.Message(responseHeader, null) }; + } + + private static MockNamedPipeClient ReplyAfter(ManualResetEventSlim releaseReply) + { + return new MockNamedPipeClient + { + ReadResponseCallback = () => + { + releaseReply.Wait(); + return new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null); + }, + }; + } + + private static MockNamedPipeClient NoMount() + { + return new MockNamedPipeClient { ConnectError = new IOException("no mount") }; + } + } +} diff --git a/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs b/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs new file mode 100644 index 000000000..d5d1eeaea --- /dev/null +++ b/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs @@ -0,0 +1,233 @@ +using GVFS.Common.NamedPipes; +using GVFS.Hooks; +using GVFS.Tests.Should; +using GVFS.UnitTests.Mock.Common; +using NUnit.Framework; +using System.Collections.Generic; +using System.Linq; +using System.Threading; + +namespace GVFS.UnitTests.Hooks +{ + [TestFixture] + public class PendingConeChangeHookTests + { + private const string GitPid = "--git-pid=1234"; + + // Tests that expect a reply use a long budget, so that a slow test machine cannot turn + // the reply into a timeout. + private const int ReplyBudgetMs = 30000; + + private bool pending; + private bool pendingFileDeleted; + private Queue clients; + private List createdClients; + private int lockRequestCount; + private int lockProcessId; + + [SetUp] + public void SetUp() + { + this.pending = true; + this.pendingFileDeleted = false; + this.clients = new Queue(); + this.createdClients = new List(); + this.lockRequestCount = 0; + this.lockProcessId = 0; + } + + [TestCase] + public void NothingPendingSendsNothing() + { + this.pending = false; + + this.Apply(holdsLock: true, "status").ShouldEqual(ConeRequestOutcome.NothingPending); + this.Apply(holdsLock: false, "diff").ShouldEqual(ConeRequestOutcome.NothingPending); + + this.createdClients.ShouldBeEmpty(); + } + + [TestCase] + public void CommandThatHoldsTheLockSendsAnApplyWithItsCommandId() + { + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ConeManagement.SuccessResult)); + + this.Apply(holdsLock: true, "commit", "-a", "-m", "message").ShouldEqual(ConeRequestOutcome.Applied); + + this.RequestHeaders().ShouldMatchInOrder(NamedPipeMessages.ConeManagement.ApplyRequest); + this.createdClients[0].Requests[0].Body.ShouldEqual("1234"); + this.lockRequestCount.ShouldEqual(0); + } + + [TestCase("log")] + [TestCase("fetch")] + [TestCase("git-diff")] + public void UnlockedCommandThatDoesNotReadTheIndexSendsNothing(string command) + { + this.Apply(holdsLock: false, command).ShouldEqual(ConeRequestOutcome.NotAnIndexReader); + + this.createdClients.ShouldBeEmpty(); + } + + [TestCase("diff")] + [TestCase("ls-files")] + [TestCase("rev-parse")] + [TestCase("show")] + [TestCase("status")] + public void UnlockedIndexReaderTakesTheLockForTheApplyAndReleasesIt(string command) + { + this.clients.Enqueue(ReplyWith(NamedPipeMessages.AcquireLock.AcceptResult)); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ConeManagement.SuccessResult)); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ReleaseLock.SuccessResult)); + + this.Apply(holdsLock: false, command).ShouldEqual(ConeRequestOutcome.Applied); + + this.RequestHeaders().ShouldMatchInOrder( + NamedPipeMessages.AcquireLock.AcquireRequest, + NamedPipeMessages.ConeManagement.ApplyRequest, + NamedPipeMessages.ReleaseLock.Request); + this.lockProcessId.ShouldEqual(1234, "The lock and the apply must name the same process"); + } + + [TestCase] + public void UnlockedIndexReaderWaitsWhileTheMountProcessesChanges() + { + Queue results = new Queue(new[] { NamedPipeMessages.AcquireLock.DenyGVFSResult, NamedPipeMessages.AcquireLock.AcceptResult }); + this.clients.Enqueue(new MockNamedPipeClient { ReadResponseCallback = () => new NamedPipeMessages.Message(results.Dequeue(), null) }); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ConeManagement.SuccessResult)); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ReleaseLock.SuccessResult)); + + this.Apply(holdsLock: false, "diff").ShouldEqual(ConeRequestOutcome.Applied); + + this.createdClients[0].Requests.Count.ShouldEqual(2); + } + + [TestCase] + public void UnlockedIndexReaderDoesNotWaitForAnotherGitCommand() + { + this.clients.Enqueue(ReplyWith(NamedPipeMessages.AcquireLock.DenyGitResult)); + + this.Apply(holdsLock: false, "diff").ShouldEqual(ConeRequestOutcome.LockUnavailable); + + this.RequestHeaders().ShouldMatchInOrder(NamedPipeMessages.AcquireLock.AcquireRequest); + } + + [TestCase] + public void UnlockedIndexReaderKeepsTheLockUntilTheMountFinishesAfterATimeout() + { + List events = new List(); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.AcquireLock.AcceptResult)); + this.clients.Enqueue(new MockNamedPipeClient + { + ReadResponseCallback = () => + { + // The mount replies after the hook stopped its wait. + Thread.Sleep(300); + lock (events) + { + events.Add("apply reply"); + } + + return new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null); + }, + }); + this.clients.Enqueue(new MockNamedPipeClient + { + ReadResponseCallback = () => + { + lock (events) + { + events.Add("release"); + } + + return new NamedPipeMessages.Message(NamedPipeMessages.ReleaseLock.SuccessResult, null); + }, + }); + + this.CreateHook().TryApply(BuildArgs("diff"), holdsLock: false, this.CreateLockRequest, waitBudgetMs: 10) + .ShouldEqual(ConeRequestOutcome.ReplyTimedOut); + + events.ShouldMatchInOrder("apply reply", "release"); + } + + [TestCase(NamedPipeMessages.ConeManagement.NotEnabledResult, "FeatureDisabled")] + [TestCase(NamedPipeMessages.UnknownRequest, "Rejected")] + public void MountThatNeverAppliesTheChangeDeletesThePendingFile(string reply, string expected) + { + this.clients.Enqueue(ReplyWith(reply)); + + this.Apply(holdsLock: true, "status").ToString().ShouldEqual(expected); + + this.pendingFileDeleted.ShouldBeTrue(); + } + + [TestCase] + public void MountThatIsNotReadyKeepsThePendingFile() + { + this.clients.Enqueue(ReplyWith(NamedPipeMessages.MountNotReadyResult)); + + this.Apply(holdsLock: true, "status").ShouldEqual(ConeRequestOutcome.Rejected); + + this.pendingFileDeleted.ShouldBeFalse(); + } + + [TestCase] + public void UnlockedIndexReaderWithoutAProcessIdSendsNothing() + { + this.CreateHook().TryApply(new[] { "pre-command", "diff" }, holdsLock: false, this.CreateLockRequest, ReplyBudgetMs) + .ShouldEqual(ConeRequestOutcome.Failed); + + this.createdClients.ShouldBeEmpty(); + } + + private static string[] BuildArgs(params string[] command) + { + List args = new List { "pre-command" }; + args.AddRange(command); + args.Add(GitPid); + return args.ToArray(); + } + + private static MockNamedPipeClient ReplyWith(string responseHeader) + { + return new MockNamedPipeClient { Response = new NamedPipeMessages.Message(responseHeader, null) }; + } + + private ConeRequestOutcome Apply(bool holdsLock, params string[] command) + { + return this.CreateHook().TryApply(BuildArgs(command), holdsLock, this.CreateLockRequest, ReplyBudgetMs); + } + + private NamedPipeMessages.LockRequest CreateLockRequest(int processId) + { + this.lockRequestCount++; + this.lockProcessId = processId; + return new NamedPipeMessages.LockRequest(processId, isElevated: false, checkAvailabilityOnly: false, "git diff", gitCommandSessionId: string.Empty); + } + + private List RequestHeaders() + { + lock (this.createdClients) + { + return this.createdClients.SelectMany(client => client.Requests).Select(request => request.Header).ToList(); + } + } + + private PendingConeChangeHook CreateHook() + { + return new PendingConeChangeHook( + () => this.pending, + () => this.pendingFileDeleted = true, + () => + { + lock (this.createdClients) + { + MockNamedPipeClient client = this.clients.Dequeue(); + this.createdClients.Add(client); + return client; + } + }, + trace: null); + } + } +} \ No newline at end of file diff --git a/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs b/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs new file mode 100644 index 000000000..b0e7e9718 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs @@ -0,0 +1,161 @@ +using GVFS.Hooks; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; + +namespace GVFS.UnitTests.Hooks +{ + [TestFixture] + public class PreCommandConeRequestsTests + { + private List calls; + private bool pending; + + [SetUp] + public void SetUp() + { + this.calls = new List(); + this.pending = false; + } + + [TestCase] + public void UnstageWidensBeforeItPrepares() + { + // Git does not match a pathspec with a path inside a sparse-directory entry, so the + // staged-file query of the preparation must run after the widen. + this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.Applied).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?"); + } + + [TestCase("Applied")] + [TestCase("NoPathsNamed")] + [TestCase("NoResolvablePaths")] + public void UnstageAppliesAChangeThatThePreparationMadePending(string widenOutcome) + { + this.Send(isUnstage: true, widenOutcome: Parse(widenOutcome), preparationMakesPending: true).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?", "apply"); + } + + [TestCase] + public void UnstageAppliesOnceAChangeThatWasPendingBeforeAWidenThatDidNotApply() + { + this.pending = true; + this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.NoPathsNamed).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?", "apply"); + } + + [TestCase] + public void UnstageDoesNotApplyWhenNothingIsPendingAfterThePreparation() + { + this.pending = true; + this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.Applied, widenClearsPending: true).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?"); + } + + [TestCase("NothingPending")] + [TestCase("FeatureDisabled")] + public void UnstageRunsWhenTheApplyHasNothingToDo(string applyOutcome) + { + this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.NoPathsNamed, preparationMakesPending: true, applyOutcome: Parse(applyOutcome)) + .ShouldBeNull(); + } + + [TestCase("TimedOut")] + [TestCase("Rejected")] + [TestCase("Failed")] + [TestCase("MountUnavailable")] + [TestCase("NotAnIndexReader")] + public void UnstageStopsWhenTheApplyFails(string applyOutcome) + { + // Without the apply, the unstaged file stays inside a sparse-directory entry with + // skip-worktree set, and Git does not report the change. + this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.NoPathsNamed, preparationMakesPending: true, applyOutcome: Parse(applyOutcome)) + .ShouldEqual("apply: " + applyOutcome); + } + + [TestCase] + public void UnstageStopsWithoutPreparingWhenTheWidenTimedOut() + { + // The mount can still change the cone and the index after the hook stops waiting. + this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.TimedOut).ShouldEqual("widen: TimedOut"); + + this.calls.ShouldMatchInOrder("pending?", "widen"); + } + + [TestCase] + public void OtherCommandSkipsTheApplyAfterAnAppliedWiden() + { + this.pending = true; + this.Send(isUnstage: false, widenOutcome: ConeRequestOutcome.Applied).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen"); + } + + [TestCase] + public void OtherCommandAppliesAPendingChangeWhenTheWidenDidNotApply() + { + this.pending = true; + this.Send(isUnstage: false, widenOutcome: ConeRequestOutcome.TimedOut, applyOutcome: ConeRequestOutcome.Failed).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen", "apply"); + } + + [TestCase] + public void OtherCommandDoesNotApplyWhenNothingIsPending() + { + this.Send(isUnstage: false, widenOutcome: ConeRequestOutcome.NoPathsNamed).ShouldBeNull(); + + this.calls.ShouldMatchInOrder("pending?", "widen"); + } + + // ConeRequestOutcome is internal, and NUnit test methods are public, so test cases name it. + private static ConeRequestOutcome Parse(string outcome) + { + return Enum.Parse(outcome); + } + + private string Send( + bool isUnstage, + ConeRequestOutcome widenOutcome, + bool preparationMakesPending = false, + bool widenClearsPending = false, + ConeRequestOutcome applyOutcome = ConeRequestOutcome.Applied) + { + return PreCommandConeRequests.Send( + isUnstage, + () => + { + this.calls.Add("pending?"); + return this.pending; + }, + () => + { + this.calls.Add("widen"); + if (widenClearsPending) + { + this.pending = false; + } + + return widenOutcome; + }, + () => + { + this.calls.Add("prepare"); + if (preparationMakesPending) + { + this.pending = true; + } + }, + () => + { + this.calls.Add("apply"); + return applyOutcome; + }); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Hooks/UnstageTests.cs b/GVFS/GVFS.UnitTests/Hooks/UnstageTests.cs index 2341c15be..15ff0355a 100644 --- a/GVFS/GVFS.UnitTests/Hooks/UnstageTests.cs +++ b/GVFS/GVFS.UnitTests/Hooks/UnstageTests.cs @@ -92,6 +92,72 @@ public void IsUnstageOperation_OtherCommand() .ShouldBeFalse(); } + [TestCase("reset")] + [TestCase("reset", "--mixed")] + [TestCase("reset", "--", "file.txt")] + [TestCase("reset", "HEAD", "file.txt")] + public void IsUnstageOperation_MixedReset(params string[] gitArgs) + { + UnstageCommandParser.IsUnstageOperation("reset", PreCommandArgs(gitArgs)).ShouldBeTrue(); + } + + [TestCase("reset", "--soft", "HEAD~1")] + [TestCase("reset", "--hard")] + [TestCase("reset", "--merge")] + [TestCase("reset", "--keep", "HEAD~1")] + [TestCase("reset", "-p")] + [TestCase("reset", "--patch", "--", "file.txt")] + public void IsUnstageOperation_ResetThatDoesNotUnstage(params string[] gitArgs) + { + UnstageCommandParser.IsUnstageOperation("reset", PreCommandArgs(gitArgs)).ShouldBeFalse(); + } + + [TestCase(false, false)] + [TestCase(true, true)] + public void ShouldPrepareForUnstage_ResetOnlyWhenTheConeIsManaged(bool managed, bool expected) + { + int checks = 0; + UnstageCommandParser.ShouldPrepareForUnstage("reset", PreCommandArgs(new[] { "reset" }), () => { checks++; return managed; }) + .ShouldEqual(expected); + checks.ShouldEqual(1); + } + + [TestCase] + public void ShouldPrepareForUnstage_RestoreDoesNotCheckTheCone() + { + UnstageCommandParser.ShouldPrepareForUnstage("restore", PreCommandArgs(new[] { "restore", "--staged", "." }), () => throw new AssertionException("checked the cone")) + .ShouldBeTrue(); + } + + [TestCase("reset", "--pathspec-from-file=-")] + [TestCase("reset", "--soft", "HEAD~1")] + public void ShouldPrepareForUnstage_SkipsResetThatItCannotPrepare(params string[] gitArgs) + { + UnstageCommandParser.ShouldPrepareForUnstage("reset", PreCommandArgs(gitArgs), () => true).ShouldBeFalse(); + } + + [TestCase] + public void ShouldPrepareForUnstage_OtherCommand() + { + UnstageCommandParser.ShouldPrepareForUnstage("status", PreCommandArgs(new[] { "status" }), () => true).ShouldBeFalse(); + } + + [TestCase(new[] { "reset" }, "")] + [TestCase(new[] { "reset", "-q" }, "")] + [TestCase(new[] { "reset", "HEAD" }, "")] + [TestCase(new[] { "reset", "-q", "HEAD", "--", "a.txt" }, "a.txt")] + [TestCase(new[] { "reset", "--", "a.txt", "b.txt" }, "a.txt\0b.txt")] + [TestCase(new[] { "reset", "HEAD", "a.txt" }, "a.txt")] + [TestCase(new[] { "reset", "HEAD", "--", "a.txt" }, "a.txt")] + [TestCase(new[] { "reset", "main", "--", "a.txt" }, "a.txt")] + [TestCase(new[] { "reset", "a.txt" }, "a.txt")] + public void GetRestorePathspec_ResetStripsTreeish(string[] gitArgs, string expectedPathspecs) + { + UnstageCommandParser.PathspecResult result = UnstageCommandParser.GetRestorePathspec("reset", PreCommandArgs(gitArgs)); + result.Failed.ShouldBeFalse(); + result.InlinePathspecs.ShouldEqual(expectedPathspecs); + } + // ── GetRestorePathspec: inline pathspecs ──────────────────────── [TestCase] @@ -282,5 +348,14 @@ public void GetRestorePathspec_PathspecFromFileWithInlinePaths() result.PathspecFromFile.ShouldEqual("list.txt"); result.InlinePathspecs.ShouldEqual("extra.txt"); } + + private static string[] PreCommandArgs(string[] gitArgs) + { + string[] args = new string[gitArgs.Length + 2]; + args[0] = "pre-command"; + gitArgs.CopyTo(args, 1); + args[args.Length - 1] = "--git-pid=1234"; + return args; + } } } diff --git a/GVFS/GVFS.UnitTests/Mock/Common/MockNamedPipeClient.cs b/GVFS/GVFS.UnitTests/Mock/Common/MockNamedPipeClient.cs index dd2fad641..521b28655 100644 --- a/GVFS/GVFS.UnitTests/Mock/Common/MockNamedPipeClient.cs +++ b/GVFS/GVFS.UnitTests/Mock/Common/MockNamedPipeClient.cs @@ -1,5 +1,6 @@ using GVFS.Common.NamedPipes; using System; +using System.Collections.Generic; namespace GVFS.UnitTests.Mock.Common { @@ -10,16 +11,19 @@ public MockNamedPipeClient() : base("mock-pipe") } public Exception ConnectError { get; set; } + public Action ConnectCallback { get; set; } public Exception SendError { get; set; } public Exception ReadError { get; set; } public Func ReadResponseCallback { get; set; } public NamedPipeMessages.Message Response { get; set; } public bool Disposed { get; private set; } public int ConnectTimeoutMs { get; private set; } + public List Requests { get; } = new List(); public override bool Connect(int timeoutMilliseconds, out Exception error) { this.ConnectTimeoutMs = timeoutMilliseconds; + this.ConnectCallback?.Invoke(); error = this.ConnectError; return error == null; } @@ -30,6 +34,8 @@ public override void SendRequest(NamedPipeMessages.Message message) { throw this.SendError; } + + this.Requests.Add(message); } public override NamedPipeMessages.Message ReadResponse() 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; + } } } diff --git a/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs b/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs index 0ceb04e21..320de72bc 100644 --- a/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs +++ b/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs @@ -2,6 +2,7 @@ using GVFS.Common.Database; using GVFS.Common.FileSystem; using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; using GVFS.Common.Tracing; using GVFS.Tests.Should; using GVFS.UnitTests.Category; @@ -426,6 +427,93 @@ public void WorktreeLogsHeadWatcherRefreshesWorktreeProperties() } } + [TestCase] + public void WorkingDirectoryChangesReachTheObserver() + { + Mock mockPlaceholderDb = new Mock(MockBehavior.Strict); + mockPlaceholderDb.Setup(x => x.GetCount()).Returns(1); + Mock mockSparseDb = new Mock(MockBehavior.Strict); + mockSparseDb.Setup(x => x.GetAll()).Returns(new HashSet()); + using (MockBackgroundFileSystemTaskRunner backgroundTaskRunner = new MockBackgroundFileSystemTaskRunner()) + using (FileSystemCallbacks fileSystemCallbacks = new FileSystemCallbacks( + this.Repo.Context, + this.Repo.GitObjects, + RepoMetadata.Instance, + new MockBlobSizes(), + gitIndexProjection: null, + backgroundFileSystemTaskRunner: backgroundTaskRunner, + fileSystemVirtualizer: null, + placeholderDatabase: mockPlaceholderDb.Object, + sparseCollection: mockSparseDb.Object)) + { + RecordingObserver observer = new RecordingObserver(); + fileSystemCallbacks.SetWorkingDirectoryChangeObserver(observer); + + fileSystemCallbacks.OnFileModified(@"A\modified.txt"); + fileSystemCallbacks.OnFileConvertedToFull(@"A\full.txt"); + fileSystemCallbacks.OnFileCreated(@"A\created.txt"); + fileSystemCallbacks.OnFileDeleted(@"A\deleted.txt"); + fileSystemCallbacks.OnFileRenamed(@"A\old.txt", @"B\new.txt"); + fileSystemCallbacks.OnFolderRenamed(@"A\OldFolder", @"B\NewFolder"); + fileSystemCallbacks.OnFolderDeleted(@"A\DeletedFolder"); + fileSystemCallbacks.OnFileModified(@".git\config"); + + observer.Changes.ShouldMatchInOrder( + @"A\modified.txt", + @"A\full.txt", + @"A\created.txt", + @"A\deleted.txt", + @"A\old.txt", + @"B\new.txt", + @"A\OldFolder\", + @"B\NewFolder\", + @"A\DeletedFolder\"); + + fileSystemCallbacks.SetWorkingDirectoryChangeObserver(null); + fileSystemCallbacks.OnFileModified(@"A\after.txt"); + observer.Changes.Count.ShouldEqual(9); + } + } + + [TestCase] + public void StagedFilesReachModifiedPathsAndTheObserver() + { + // "git reset --soft" stages files without a file system write, so no callback reports + // them. The unstage preparation must report them, so that the cone includes them. + Mock mockPlaceholderDb = new Mock(MockBehavior.Strict); + mockPlaceholderDb.Setup(x => x.GetCount()).Returns(1); + Mock mockSparseDb = new Mock(MockBehavior.Strict); + mockSparseDb.Setup(x => x.GetAll()).Returns(new HashSet()); + using (MockBackgroundFileSystemTaskRunner backgroundTaskRunner = new MockBackgroundFileSystemTaskRunner()) + using (FileSystemCallbacks fileSystemCallbacks = new FileSystemCallbacks( + this.Repo.Context, + this.Repo.GitObjects, + RepoMetadata.Instance, + new MockBlobSizes(), + gitIndexProjection: null, + backgroundFileSystemTaskRunner: backgroundTaskRunner, + fileSystemVirtualizer: null, + placeholderDatabase: mockPlaceholderDb.Object, + sparseCollection: mockSparseDb.Object)) + { + RecordingObserver observer = new RecordingObserver(); + fileSystemCallbacks.SetWorkingDirectoryChangeObserver(observer); + + fileSystemCallbacks.TryAddStagedFileToModifiedPaths("Out/Inc/staged.h", out bool wasModifiedPath).ShouldBeTrue(); + wasModifiedPath.ShouldBeFalse(); + fileSystemCallbacks.TryAddStagedFileToModifiedPaths(string.Empty, out _).ShouldBeFalse(); + + fileSystemCallbacks.GetAllModifiedPaths().ShouldContain(path => path == "Out/Inc/staged.h"); + observer.Changes.ShouldMatchInOrder(@"Out\Inc\staged.h"); + + // A path that already is a modified path is reported again, so that a staged file + // that left the cone comes back into it. The caller must not overwrite it. + fileSystemCallbacks.TryAddStagedFileToModifiedPaths("Out/Inc/staged.h", out wasModifiedPath).ShouldBeTrue(); + wasModifiedPath.ShouldBeTrue(); + observer.Changes.ShouldMatchInOrder(@"Out\Inc\staged.h", @"Out\Inc\staged.h"); + } + } + [TestCase] public void FileAndFolderCallbacksScheduleBackgroundTasks() { @@ -597,5 +685,15 @@ private void CallbackSchedulesBackgroundTask( backgroundTaskRunner.BackgroundTasks[0].VirtualPath.ShouldEqual(newPath); backgroundTaskRunner.BackgroundTasks.Clear(); } + + private sealed class RecordingObserver : IWorkingDirectoryChangeObserver + { + public List Changes { get; } = new List(); + + public void OnWorkingDirectoryPathChanged(string relativePath, bool isFolder) + { + this.Changes.Add(isFolder ? relativePath + Path.DirectorySeparatorChar : relativePath); + } + } } } diff --git a/GVFS/GVFS.UnitTests/Virtualization/Projection/SparseIndexExpansionTests.cs b/GVFS/GVFS.UnitTests/Virtualization/Projection/SparseIndexExpansionTests.cs new file mode 100644 index 000000000..30cd84d62 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Virtualization/Projection/SparseIndexExpansionTests.cs @@ -0,0 +1,1023 @@ +using GVFS.Common; +using GVFS.Common.Database; +using GVFS.Common.FileSystem; +using GVFS.Common.Git; +using GVFS.Common.Tracing; +using GVFS.Tests.Should; +using GVFS.UnitTests.Category; +using GVFS.UnitTests.Mock.Common; +using GVFS.UnitTests.Mock.FileSystem; +using GVFS.UnitTests.Mock.Git; +using GVFS.Virtualization.Background; +using GVFS.Virtualization.Projection; +using Moq; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using static GVFS.Virtualization.Projection.GitIndexProjection; +using static GVFS.Virtualization.Projection.GitIndexProjection.GitIndexParser; +using Entry = GVFS.UnitTests.Mock.Git.GitIndexV4Writer.Entry; + +namespace GVFS.UnitTests.Virtualization.Projection +{ + /// + /// Tests for the expansion of the sparse-directory entries of a sparse index (git index.sparse), + /// when gvfs.auto-sparse-index is true. Each test builds a repository of trees in memory, and + /// writes the full index and a sparse index for the same files. The projection of the sparse + /// index must be the same as the projection of the full index: every folder, every file, every + /// SHA, and every file mode. + /// + [TestFixture] + public class SparseIndexExpansionTests + { + private const uint RegularMode = 0x81A4; // 100644 + private const uint ExecutableMode = 0x81ED; // 100755 + private const uint SymLinkMode = 0xA000; // 120000 + private const uint GitLinkMode = 0xE000; // 160000 + private const uint TreeMode = 0x4000; // 040000 + + private string testRoot; + private List disposables; + + public static IEnumerable EquivalentRepositories() + { + foreach (bool supportsFileMode in new[] { true, false }) + { + yield return new TestCaseData( + supportsFileMode, + new[] { "a/x/b.txt", "a/x/deep/er/c.txt", "a/x/deep/d.txt", "a/y.txt", "b.txt", "z/1.txt" }, + new string[0], + new[] { "a/x", "z" }) + .SetName($"NestedSparseDirectoryNextToInConeFiles(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "big/a/1.txt", "big/a/b/2.txt", "big/a/b/c/3.txt", "big/a/b/c/d/4.txt", "big/e/5.txt", "big/6.txt" }, + new string[0], + new[] { "big" }) + .SetName($"DeeplyNestedTrees(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "p/a.b", "p/a/1.txt", "p/a-", "p/a0", "p/A/2.txt", "q/a.b", "q/a/1.txt", "q/a-", "q/a0", "r.txt" }, + new string[0], + new[] { "p" }) + .SetName($"TreeOrderDiffersFromProjectionOrder(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "c/Foo/Sub/1.txt", "c/foo/sub/2.txt", "c/foo/3.txt", "c/FOO.txt", "d.txt" }, + new string[0], + new[] { "c" }) + .SetName($"FolderNamesThatDifferOnlyInCase(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "e/file.txt", "e/inner/f.txt" }, + new[] { "e/empty", "e/inner/empty", "onlyempty/a", "onlyempty/b/c" }, + new[] { "e", "onlyempty" }) + .SetName($"EmptyTrees(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "m/1.txt", "n/2.txt", "o/3.txt", "o/p/4.txt" }, + new string[0], + new[] { "m", "n", "o/p" }) + .SetName($"AdjacentSparseDirectories(supportsFileMode={supportsFileMode})"); + } + } + + [SetUp] + public void SetUp() + { + if (GVFSPlatform.Instance == null) + { + GVFSPlatform.Register(new MockPlatform()); + } + + RepoMetadata.Shutdown(); + this.disposables = new List(); + this.testRoot = Path.Combine(Path.GetTempPath(), "SparseIndexExpansionTests_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(this.testRoot); + } + + [TearDown] + public void TearDown() + { + // GVFSPlatform.Instance is shared by every fixture, so restore its default. + SetSupportsFileMode(true); + RepoMetadata.Shutdown(); + this.disposables.ForEach(disposable => disposable.Dispose()); + + if (Directory.Exists(this.testRoot)) + { + Directory.Delete(this.testRoot, recursive: true); + } + } + + [TestCaseSource(nameof(EquivalentRepositories))] + public void SparseIndexProjectsTheSameAsFullIndex(bool supportsFileMode, string[] files, string[] emptyTrees, string[] sparseDirectories) + { + SetSupportsFileMode(supportsFileMode); + TestRepository repository = new TestRepository(); + foreach (string file in files) + { + repository.AddFile(file); + } + + foreach (string emptyTree in emptyTrees) + { + repository.AddEmptyTree(emptyTree); + } + + this.ShouldProjectTheSame(repository, sparseDirectories); + } + + [TestCase(true)] + [TestCase(false)] + public void SparseIndexProjectsFileModesTheSameAsFullIndex(bool supportsFileMode) + { + SetSupportsFileMode(supportsFileMode); + TestRepository repository = new TestRepository(); + repository.AddFile("tools/run.sh", ExecutableMode); + repository.AddFile("tools/link", SymLinkMode); + repository.AddFile("tools/module", GitLinkMode); + repository.AddFile("tools/plain.txt", RegularMode); + repository.AddFile("tools/nested/run2.sh", ExecutableMode); + repository.AddFile("top.txt", RegularMode); + + List projection = this.ShouldProjectTheSame(repository, "tools"); + + if (supportsFileMode) + { + projection.ShouldContain(line => line.StartsWith("tools/run.sh=") && line.EndsWith(" Regular 755")); + projection.ShouldContain(line => line.StartsWith("tools/link=") && line.EndsWith(" SymLink 0")); + projection.ShouldContain(line => line.StartsWith("tools/module=") && line.EndsWith(" GitLink 0")); + projection.ShouldContain(line => line.StartsWith("tools/nested/run2.sh=") && line.EndsWith(" Regular 755")); + } + } + + [TestCase] + public void SparseIndexIncludesFoldersTheSameAsFullIndex() + { + // The gvfs sparse folders (ISparseCollection) mark folders as included or excluded + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + foreach (string file in new[] { "a/b/c/1.txt", "a/b/c/d/e/7.txt", "a/b/d/2.txt", "a/e/3.txt", "a/4.txt", "f/g/5.txt", "h/6.txt", "h/i/8.txt" }) + { + repository.AddFile(file); + } + + // "a/b/c" is a recursive sparse folder with folders under it. "h" is a recursive sparse + // folder above the sparse directory "h/i". + Mock sparseCollection = new Mock(MockBehavior.Strict); + sparseCollection + .Setup(x => x.GetAll()) + .Returns(new HashSet(StringComparer.OrdinalIgnoreCase) { Path.Combine("a", "b", "c"), "h" }); + + this.ShouldProjectTheSame(repository, new[] { "a", "f" }, sparseCollection: sparseCollection.Object); + this.ShouldProjectTheSame(repository, new[] { "a/b", "a/e", "f/g", "h/i" }, sparseCollection: sparseCollection.Object); + } + + [TestCase] + public void ModifiedPathsUnderSparseDirectoryAreProjectedAsInFullIndex() + { + // For a full index, the virtual file system hook reports the modified paths, and git + // clears the skip-worktree bit of each index entry that they match. The full index does + // not project those entries. Matches ignore case. + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + foreach (string file in new[] { "s/keep.txt", "s/edited.txt", "s/dir/1.txt", "s/dir/sub/2.txt", "s/only/3.txt", "s/other/4.txt", "t/5.txt", "u/6.txt", "p/x/7.txt", "p/y.txt" }) + { + repository.AddFile(file); + } + + // "p/" is a modified folder above the sparse directory "p/x" + ModifiedPathsDatabase modifiedPaths = this.CreateModifiedPaths( + "S/EDITED.txt", + "s/dir/", + "s/only/3.txt", + "t/", + "p/", + "new-folder/", + "s/other/not-in-tree.txt"); + + string[] nonSkipWorktree = { "s/edited.txt", "s/dir/1.txt", "s/dir/sub/2.txt", "s/only/3.txt", "t/5.txt", "p/x/7.txt", "p/y.txt" }; + List full = this.BuildProjection(repository.CreateFullIndex(nonSkipWorktree), repository, modifiedPaths: null); + List sparse = this.BuildProjection(repository.CreateSparseIndex(new[] { "s", "t", "u", "p/x" }, "p/y.txt"), repository, modifiedPaths); + + sparse.ShouldMatchInOrder(full); + sparse.ShouldContain(line => line.StartsWith("s/keep.txt=")); + sparse.ShouldNotContain(line => line.StartsWith("s/edited.txt=") || line.StartsWith("s/dir/") || line.StartsWith("s/only/") || line.StartsWith("t/") || line.StartsWith("p/")); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void FeatureFlagEnablesExpansionThroughRepository() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b/c.txt"); + repository.AddFile("d.txt"); + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, repository.CreateSparseIndex("a")); + + MockTracer tracer = new MockTracer(); + MockGVFSEnlistment enlistment = new MockGVFSEnlistment(this.testRoot, "mock://repoUrl", Path.Combine("mock:", "git"), gitProcess: null); + ConfiguredGitRepo gitRepo = new ConfiguredGitRepo(tracer, enlistment, repository.Store); + gitRepo.Config[GVFSConstants.GitConfig.AutoSparseIndex] = true; + GVFSContext context = new GVFSContext(tracer, new PhysicalFileSystem(), gitRepo, enlistment); + + using (GitIndexProjection projection = new GitIndexProjection(context, null, null, null, null, null, null, null)) + { + projection.BuildProjectionFromPath(tracer, indexPath); + DumpProjection(projection).ShouldMatchInOrder( + "a/", + "a/b/", + "a/b/c.txt=" + TestRepository.HashOf("blob a/b/c.txt"), + "d.txt=" + TestRepository.HashOf("blob d.txt")); + } + + gitRepo.Config[GVFSConstants.GitConfig.AutoSparseIndex] = false; + using (GitIndexProjection projection = new GitIndexProjection(context, null, null, null, null, null, null, null)) + { + Assert.Throws(() => projection.BuildProjectionFromPath(tracer, indexPath)); + } + } + + [TestCase] + public void FullIndexWithExpansionEnabledReadsNoTrees() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b.txt"); + repository.AddFile("c.txt"); + + List withoutExpansion = this.BuildProjection(repository.CreateFullIndex(), treeReader: null); + List withExpansion = this.BuildProjection(repository.CreateFullIndex(), repository); + + withExpansion.ShouldMatchInOrder(withoutExpansion); + repository.Store.ReadCount.ShouldEqual(0); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void SparseIndexWithExpansionDisabledStillFails() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b.txt"); + + SparseIndexNotSupportedException error = Assert.Throws( + () => this.BuildProjection(repository.CreateSparseIndex("a"), treeReader: null)); + error.Message.ShouldContain("sparse-directory entry 'a/'", "1. If the enlistment is mounted, run 'gvfs unmount'."); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void FileNamesThatDifferOnlyInCaseFailAsInFullIndex() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("c/A.txt"); + repository.AddFile("c/a.txt"); + + Exception fullError = Assert.Catch(() => this.BuildProjection(repository.CreateFullIndex(), repository)); + Exception sparseError = Assert.Catch(() => this.BuildProjection(repository.CreateSparseIndex("c"), repository)); + sparseError.GetType().ShouldEqual(fullError.GetType()); + sparseError.Message.ShouldEqual(fullError.Message); + } + + [TestCase] + public void MissingTreeIsDownloadedOnce() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b/c.txt"); + repository.AddFile("a/d.txt"); + string subtree = repository.GetTreeSha("a/b"); + repository.Store.MissingTrees.Add(subtree); + repository.Store.DownloadableTrees.Add(subtree); + + List full = this.BuildProjection(repository.CreateFullIndex(), treeReader: null); + List sparse = this.BuildProjection(repository.CreateSparseIndex("a"), repository); + + sparse.ShouldMatchInOrder(full); + repository.Store.Downloads.ShouldMatchInOrder(subtree); + } + + [TestCase(TreeEnumerationResult.MissingTree, false)] + [TestCase(TreeEnumerationResult.MissingTree, true)] + [TestCase(TreeEnumerationResult.CorruptTree, false)] + [TestCase(TreeEnumerationResult.NotTree, false)] + [TestCase(TreeEnumerationResult.RepositoryUnavailable, false)] + [Category(CategoryConstants.ExceptionExpected)] + public void UnreadableTreeFailsTheBuild(TreeEnumerationResult readResult, bool downloadSucceedsButTreeStaysMissing) + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b/c.txt"); + repository.AddFile("a/d.txt"); + string subtree = repository.GetTreeSha("a/b"); + repository.Store.FailingTrees[subtree] = readResult; + if (downloadSucceedsButTreeStaysMissing) + { + repository.Store.DownloadSucceedsWithoutEffect.Add(subtree); + } + + SparseIndexExpansionException error = Assert.Throws( + () => this.BuildProjection(repository.CreateSparseIndex("a"), repository)); + error.Message.ShouldContain( + "Cannot read tree " + subtree + " for the folder 'a/b' in the sparse index (" + readResult + ")", + "run 'git -c core.hookspath= config gvfs.auto-sparse-index false'"); + + // Only a missing tree can become readable after a download + repository.Store.Downloads.Count.ShouldEqual(readResult == TreeEnumerationResult.MissingTree ? 1 : 0); + } + + [TestCase("..")] + [TestCase(".")] + [TestCase(".GIT")] + [TestCase(".git.")] + [TestCase(".Git ")] + [TestCase("GIT~1")] + [TestCase("a\\b")] + [TestCase("a/b")] + [TestCase("a\0b")] + [TestCase("")] + [Category(CategoryConstants.ExceptionExpected)] + public void InvalidTreeEntryNameFailsTheBuild(string name) + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + string blob = TestRepository.HashOf("blob"); + string badTree = repository.Store.AddTree(new TreeEntry(name, RegularMode, blob)); + byte[] index = GitIndexV4Writer.Create(new Entry("bad/", GitIndexV4Writer.SparseDirectoryMode, badTree)); + + SparseIndexExpansionException error = Assert.Throws(() => this.BuildProjection(index, repository)); + error.Message.ShouldContain("The folder 'bad' in the sparse index has a tree entry with the name", "Git cannot add this name to an index."); + } + + [TestCase("a{0}b")] + [TestCase("{")] + [Category(CategoryConstants.ExceptionExpected)] + public void TreeEntryNameWithBracesIsReportedLiterally(string folderName) + { + // The name reaches the message without string.Format, so braces do not throw FormatException + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + string badTree = repository.Store.AddTree(new TreeEntry("..", RegularMode, TestRepository.HashOf("blob"))); + string parent = repository.Store.AddTree(new TreeEntry(folderName, TreeMode, badTree)); + byte[] index = GitIndexV4Writer.Create(new Entry("top/", GitIndexV4Writer.SparseDirectoryMode, parent)); + + SparseIndexExpansionException error = Assert.Throws(() => this.BuildProjection(index, repository)); + error.Message.ShouldContain("The folder 'top/" + folderName + "' in the sparse index"); + } + + [TestCase(0x81B6u)] // 100666 + [TestCase(0xA1A4u)] // 120644 + [TestCase(0x6000u)] // unknown type + [Category(CategoryConstants.ExceptionExpected)] + public void InvalidFileModeFailsTheBuildWhenThePlatformRecordsModes(uint mode) + { + SetSupportsFileMode(true); + TestRepository repository = new TestRepository(); + string badTree = repository.Store.AddTree(new TreeEntry("file", mode, TestRepository.HashOf("blob"))); + byte[] index = GitIndexV4Writer.Create(new Entry("bad/", GitIndexV4Writer.SparseDirectoryMode, badTree)); + + SparseIndexExpansionException error = Assert.Throws(() => this.BuildProjection(index, repository)); + error.Message.ShouldContain("The file 'bad/file' in the folder 'bad' of the sparse index has the invalid type"); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void PathLongerThanTheIndexLimitFailsTheBuild() + { + // Also a tree that is deeper than the projection can hold. The walk does not recurse, + // so the depth cannot exhaust the stack. + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + string tree = repository.Store.AddTree(new TreeEntry("file.txt", RegularMode, TestRepository.HashOf("blob"))); + for (int i = 0; i < SparseDirectoryExpander.MaxPathLength; i++) + { + tree = repository.Store.AddTree(new TreeEntry("d", TreeMode, tree)); + } + + byte[] index = GitIndexV4Writer.Create(new Entry("deep/", GitIndexV4Writer.SparseDirectoryMode, tree)); + + SparseIndexExpansionException error = Assert.Throws(() => this.BuildProjection(index, repository)); + error.Message.ShouldContain("has a path that is longer than " + SparseDirectoryExpander.MaxPathLength + " bytes"); + } + + [TestCase] + public void LongNamesAndWideTreesProjectTheSameAsFullIndexWithSmallPools() + { + // A sparse index has few entries, so the string pools start small. A name that is + // longer than one pool expansion must not overrun the pool. + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + for (int i = 0; i < 150; i++) + { + repository.AddFile("wide/" + i.ToString("D3") + new string('x', 200) + ".txt"); + } + + repository.AddFile("top.txt"); + + List full = this.BuildProjection(repository.CreateFullIndex(), treeReader: null); + ResetStringPools(indexEntryCount: 1); + List sparse = this.BuildProjection(repository.CreateSparseIndex("wide"), repository); + + sparse.ShouldMatchInOrder(full); + sparse.Count.ShouldEqual(152); + } + + [TestCase] + public void RebuildUsesTheCurrentModifiedPaths() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("s/a.txt"); + repository.AddFile("s/b.txt"); + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, repository.CreateSparseIndex("s")); + ModifiedPathsDatabase modifiedPaths = this.CreateModifiedPaths(); + + GitIndexProjection projection = this.CreateProjection(new Mock(MockBehavior.Strict).Object, modifiedPaths, sparseCollection: null); + try + { + projection.EnableSparseIndexExpansionForTests(repository.Store); + projection.BuildProjectionFromPath(new MockTracer(), indexPath); + DumpProjection(projection).ShouldContain(line => line.StartsWith("s/a.txt=")); + + modifiedPaths.TryAdd("s/a.txt", isFolder: false, out bool _).ShouldBeTrue(); + projection.BuildProjectionFromPath(new MockTracer(), indexPath); + DumpProjection(projection).ShouldNotContain(line => line.StartsWith("s/a.txt=")); + DumpProjection(projection).ShouldContain(line => line.StartsWith("s/b.txt=")); + } + finally + { + projection.Dispose(); + } + } + + [TestCase] + public void SparseDirectoryWithoutSkipWorktreeIsNotProjected() + { + // As a full index does not project an entry without the skip-worktree bit + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("gone/a.txt"); + repository.AddFile("kept.txt"); + byte[] index = GitIndexV4Writer.Create( + new Entry("gone/", GitIndexV4Writer.SparseDirectoryMode, repository.GetTreeSha("gone")) { SkipWorktree = false }, + new Entry("kept.txt", GitIndexV4Writer.RegularFileMode, TestRepository.HashOf("blob kept.txt"))); + + this.BuildProjection(index, repository).ShouldMatchInOrder("kept.txt=" + TestRepository.HashOf("blob kept.txt")); + repository.Store.ReadCount.ShouldEqual(0); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void InitializeFailsAndInvalidatesProjectionWhenATreeCannotBeRead() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b.txt"); + MockGVFSEnlistment enlistment = this.CreateEnlistmentWithMetadata(); + File.WriteAllBytes(enlistment.GitIndexPath, repository.CreateSparseIndex("a")); + repository.Store.FailingTrees[repository.GetTreeSha("a")] = TreeEnumerationResult.MissingTree; + + GitIndexProjection projection = this.CreateProjection(new Mock(MockBehavior.Strict).Object, modifiedPaths: null, sparseCollection: null, RepoMetadata.Instance); + try + { + projection.EnableSparseIndexExpansionForTests(repository.Store); + Assert.Throws(() => projection.Initialize(backgroundFileSystemTaskRunner: null)); + RepoMetadata.Instance.GetProjectionInvalid().ShouldBeTrue(); + } + finally + { + projection.Dispose(); + } + } + + [TestCase(true)] + [TestCase(false)] + public void ProjectedFileCountIsReportedOnlyForASparseIndex(bool sparse) + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b.txt"); + repository.AddFile("a/c/d.txt"); + repository.AddFile("e.txt"); + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, sparse ? repository.CreateSparseIndex("a") : repository.CreateFullIndex()); + + GitIndexProjection projection = this.CreateProjection(new Mock(MockBehavior.Strict).Object, modifiedPaths: null, sparseCollection: null); + try + { + projection.EnableSparseIndexExpansionForTests(repository.Store); + projection.BuildProjectionFromPath(new MockTracer(), indexPath); + projection.GetProjectedFileCountIfSparseIndex().ShouldEqual(sparse ? 3 : -1); + } + finally + { + projection.Dispose(); + } + } + + [TestCase("src", true)] + [TestCase("src//x/", false)] + [TestCase("/src/", false)] + [TestCase("src/", false, (int)MergeStage.Theirs)] + [Category(CategoryConstants.ExceptionExpected)] + public void MalformedSparseDirectoryEntryFailsValidation(string path, bool supportsFileMode, int mergeStage = 0) + { + SetSupportsFileMode(supportsFileMode); + byte[] index = GitIndexV4Writer.Create(new Entry(path, GitIndexV4Writer.SparseDirectoryMode) { MergeState = (MergeStage)mergeStage }); + + using (MemoryStream stream = new MemoryStream(index)) + { + InvalidDataException error = Assert.Throws( + () => GitIndexParser.ValidateIndex(new MockTracer(), stream, GitIndexParser.SparseDirectoryHandling.Accept)); + error.Message.ShouldContain("The sparse-directory entry '" + path + "'"); + } + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void SparseDirectoryPathWithFileModeFailsValidation() + { + SetSupportsFileMode(true); + byte[] index = GitIndexV4Writer.Create(new Entry("src/", GitIndexV4Writer.RegularFileMode)); + + using (MemoryStream stream = new MemoryStream(index)) + { + InvalidDataException error = Assert.Throws( + () => GitIndexParser.ValidateIndex(new MockTracer(), stream, GitIndexParser.SparseDirectoryHandling.Accept)); + error.Message.ShouldContain("does not have the directory mode"); + } + } + + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void RepairValidationAcceptsSparseIndexWithoutReadingTrees() + { + SetSupportsFileMode(false); + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, GitIndexV4Writer.Create(new Entry("README.md"), new Entry("src/", GitIndexV4Writer.SparseDirectoryMode))); + + GitIndexProjection projection = this.CreateProjection(placeholders: null, modifiedPaths: null, sparseCollection: null); + try + { + projection.BuildProjectionFromPath(new MockTracer(), indexPath, acceptSparseDirectories: true); + + // The setting applies to one call only + Assert.Throws(() => projection.BuildProjectionFromPath(new MockTracer(), indexPath)); + } + finally + { + projection.Dispose(); + } + } + + [TestCase] + public void PlaceholderScanTreatsFilesInSparseDirectoryTreeAsInIndex() + { + // A full index has an entry, with the skip-worktree bit, for each file in the tree of a + // collapsed folder. The placeholder scan must not move their placeholders to the + // modified paths. A placeholder for a file that is not in the tree (for example after + // 'git reset --mixed') is not in the index, so it moves to the modified paths and the + // file stays on disk. + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("src/deep/file.txt"); + repository.AddFile("src/Foo/1.txt"); + repository.AddFile("src/foo/2.txt"); + repository.AddFile("unreadable/x.txt"); + repository.Store.FailingTrees[repository.GetTreeSha("unreadable")] = TreeEnumerationResult.CorruptTree; + ModifiedPathsDatabase modifiedPaths = this.CreateModifiedPaths(); + + string inTree = Path.Combine("src", "DEEP", "File.txt"); + string inSecondCaseFolder = Path.Combine("src", "FOO", "2.txt"); + string notInTree = Path.Combine("src", "deep", "stale.txt"); + string folderNotFile = Path.Combine("src", "deep"); + string underUnreadableTree = Path.Combine("unreadable", "x.txt"); + string underNotSkipWorktree = Path.Combine("gone", "file.txt"); + string notInIndex = Path.Combine("other", "file.txt"); + string similarPrefix = Path.Combine("src2", "file.txt"); + + Mock placeholders = new Mock(MockBehavior.Strict); + placeholders + .Setup(x => x.GetAllFilePaths()) + .Returns(new HashSet(StringComparer.OrdinalIgnoreCase) + { + inTree, inSecondCaseFolder, notInTree, folderNotFile, underUnreadableTree, underNotSkipWorktree, notInIndex, similarPrefix, "README.md" + }); + foreach (string removed in new[] { notInTree, folderNotFile, underUnreadableTree, underNotSkipWorktree, notInIndex, similarPrefix }) + { + placeholders.Setup(x => x.Remove(removed)); + } + + byte[] index = GitIndexV4Writer.Create( + new Entry("README.md"), + new Entry("gone/", GitIndexV4Writer.SparseDirectoryMode) { SkipWorktree = false }, + new Entry("src/", GitIndexV4Writer.SparseDirectoryMode, repository.GetTreeSha("src")), + new Entry("unreadable/", GitIndexV4Writer.SparseDirectoryMode, repository.GetTreeSha("unreadable"))); + + GitIndexProjection projection = this.CreateProjection(placeholders.Object, modifiedPaths, sparseCollection: null); + try + { + projection.EnableSparseIndexExpansionForTests(repository.Store); + GitIndexParser parser = new GitIndexParser(projection); + using (MemoryStream stream = new MemoryStream(index)) + { + parser.AddMissingModifiedFilesAndRemoveThemFromPlaceholderList(new MockTracer(), stream).ShouldEqual(FileSystemTaskResult.Success); + } + + placeholders.VerifyAll(); + placeholders.Verify(x => x.Remove(It.IsAny()), Times.Exactly(6)); + modifiedPaths.Contains("gone", isFolder: true).ShouldBeTrue(); + modifiedPaths.Contains("src/deep/stale.txt", isFolder: false).ShouldBeTrue(); + modifiedPaths.Contains("unreadable/x.txt", isFolder: false).ShouldBeTrue(); + modifiedPaths.Contains("other/file.txt", isFolder: false).ShouldBeTrue(); + modifiedPaths.Contains("src2/file.txt", isFolder: false).ShouldBeTrue(); + modifiedPaths.Contains("src/deep/file.txt", isFolder: false).ShouldBeFalse(); + modifiedPaths.Contains("src/foo/2.txt", isFolder: false).ShouldBeFalse(); + } + finally + { + projection.Dispose(); + } + } + + private static void SetSupportsFileMode(bool value) + { + ((MockPlatformFileSystem)GVFSPlatform.Instance.FileSystem).SupportsFileMode = value; + } + + private static void ResetStringPools(uint indexEntryCount) + { + LazyUTF8String.ResetPool(new MockTracer(), indexEntryCount); + } + + /// + /// Lists every folder and file of the projection, depth first in projection order. A + /// folder line shows whether the folder is included. A file line shows the SHA, and the + /// file type and mode when the platform supports file modes. + /// + private static List DumpProjection(GitIndexProjection projection) + { + FieldInfo rootField = typeof(GitIndexProjection).GetField("rootFolderData", BindingFlags.Instance | BindingFlags.NonPublic); + FolderData root = (FolderData)rootField.GetValue(projection); + List lines = new List(); + DumpFolder(projection, root, string.Empty, lines); + return lines; + } + + private static void DumpFolder(GitIndexProjection projection, FolderData folder, string folderPath, List lines) + { + for (int i = 0; i < folder.ChildEntries.Count; i++) + { + FolderEntryData child = folder.ChildEntries[i]; + string childPath = folderPath + child.Name.GetString(); + if (child.IsFolder) + { + FolderData childFolder = (FolderData)child; + lines.Add(childPath + "/" + (childFolder.IsIncluded ? string.Empty : " excluded")); + DumpFolder(projection, childFolder, childPath + "/", lines); + } + else + { + string line = childPath + "=" + ((FileData)child).ConvertShaToString().ToLowerInvariant(); + if (GVFSPlatform.Instance.FileSystem.SupportsFileMode) + { + projection.GetFileTypeAndMode(childPath, out FileType fileType, out ushort fileMode); + line += " " + fileType + " " + Convert.ToString(fileMode, 8); + } + + lines.Add(line); + } + } + } + + private List ShouldProjectTheSame(TestRepository repository, params string[] sparseDirectories) + { + return this.ShouldProjectTheSame(repository, sparseDirectories, sparseCollection: null); + } + + private List ShouldProjectTheSame(TestRepository repository, string[] sparseDirectories, ISparseCollection sparseCollection) + { + List full = this.BuildProjection(repository.CreateFullIndex(), treeReader: null, sparseCollection: sparseCollection); + List sparse = this.BuildProjection(repository.CreateSparseIndex(sparseDirectories), repository, sparseCollection: sparseCollection); + + full.Count.ShouldBeAtLeast(1); + sparse.ShouldMatchInOrder(full); + return sparse; + } + + private List BuildProjection(byte[] index, TestRepository treeReader, ModifiedPathsDatabase modifiedPaths = null, ISparseCollection sparseCollection = null) + { + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, index); + + GitIndexProjection projection = this.CreateProjection(new Mock(MockBehavior.Strict).Object, modifiedPaths, sparseCollection); + try + { + if (treeReader != null) + { + projection.EnableSparseIndexExpansionForTests(treeReader.Store); + } + + projection.BuildProjectionFromPath(new MockTracer(), indexPath); + return DumpProjection(projection); + } + finally + { + projection.Dispose(); + } + } + + private ModifiedPathsDatabase CreateModifiedPaths(params string[] paths) + { + string dataPath = Path.Combine(this.testRoot, "ModifiedPaths_" + Guid.NewGuid().ToString("N") + ".dat"); + ModifiedPathsDatabase.TryLoadOrCreate(new MockTracer(), dataPath, new PhysicalFileSystem(), out ModifiedPathsDatabase modifiedPaths, out string error).ShouldBeTrue(error); + this.disposables.Add(modifiedPaths); + foreach (string path in paths) + { + bool isFolder = path.EndsWith("/"); + modifiedPaths.TryAdd(isFolder ? path.TrimEnd('/') : path, isFolder, out bool _).ShouldBeTrue(); + } + + return modifiedPaths; + } + + private GitIndexProjection CreateProjection(IPlaceholderCollection placeholders, ModifiedPathsDatabase modifiedPaths, ISparseCollection sparseCollection, RepoMetadata repoMetadata = null) + { + MockTracer tracer = new MockTracer(); + MockGVFSEnlistment enlistment = this.CreateEnlistment(); + GVFSContext context = new GVFSContext(tracer, new PhysicalFileSystem(), new MockGitRepo(tracer, enlistment, fileSystem: null), enlistment); + return new GitIndexProjection( + context, + gitObjects: null, + blobSizes: null, + repoMetadata: repoMetadata, + fileSystemVirtualizer: null, + placeholderDatabase: placeholders, + sparseCollection: sparseCollection, + modifiedPaths: modifiedPaths); + } + + private MockGVFSEnlistment CreateEnlistment() + { + return new MockGVFSEnlistment(this.testRoot, "mock://repoUrl", Path.Combine("mock:", "git"), gitProcess: null); + } + + private MockGVFSEnlistment CreateEnlistmentWithMetadata() + { + MockGVFSEnlistment enlistment = this.CreateEnlistment(); + Directory.CreateDirectory(Path.GetDirectoryName(enlistment.GitIndexPath)); + Directory.CreateDirectory(enlistment.DotGVFSRoot); + RepoMetadata.TryInitialize(new MockTracer(), new OverwritingFileSystem(), enlistment.DotGVFSRoot, out string error).ShouldBeTrue(error); + RepoMetadata.Instance.SetProjectionInvalid(false); + return enlistment; + } + + private class OverwritingFileSystem : PhysicalFileSystem + { + // RepoMetadata flushes through MoveAndOverwriteFile, which MockPlatform does not support + public override void MoveAndOverwriteFile(string sourceFileName, string destinationFilename) + { + File.Move(sourceFileName, destinationFilename, overwrite: true); + } + } + + private class ConfiguredGitRepo : MockGitRepo + { + private readonly IProjectionTreeReader trees; + + public ConfiguredGitRepo(ITracer tracer, Enlistment enlistment, IProjectionTreeReader trees) + : base(tracer, enlistment, fileSystem: null) + { + this.trees = trees; + } + + public Dictionary Config { get; } = new Dictionary(); + + public override bool GetConfigBoolOrDefault(string name, bool defaultValue) + { + return this.Config.TryGetValue(name, out bool value) ? value : defaultValue; + } + + public override TreeEnumerationResult TryEnumerateTree(byte[] treeId, TreeEntryVisitor visitor) + { + return this.trees.TryReadTree(treeId, visitor); + } + } + + private class TreeEntry + { + public TreeEntry(string name, uint mode, string sha) + { + this.Name = name; + this.Mode = mode; + this.Sha = sha; + } + + public string Name { get; } + public uint Mode { get; } + public string Sha { get; } + + public bool IsTree => this.Mode == TreeMode; + + // Git sorts the entries of a tree as if the name of a tree ends in '/' + public string SortKey => this.IsTree ? this.Name + "/" : this.Name; + } + + /// + /// An object store with trees only, that the expander reads through . + /// + private class FakeTreeStore : IProjectionTreeReader + { + private readonly Dictionary> trees = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + public HashSet MissingTrees { get; } = new HashSet(StringComparer.OrdinalIgnoreCase); + public HashSet DownloadableTrees { get; } = new HashSet(StringComparer.OrdinalIgnoreCase); + + // Trees whose read always gives this result + public Dictionary FailingTrees { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); + + // Trees whose download reports success, but does not make the tree readable + public HashSet DownloadSucceedsWithoutEffect { get; } = new HashSet(StringComparer.OrdinalIgnoreCase); + public List Downloads { get; } = new List(); + public int ReadCount { get; private set; } + + public string AddTree(params TreeEntry[] entries) + { + List sorted = entries.OrderBy(entry => entry.SortKey, StringComparer.Ordinal).ToList(); + string sha = TestRepository.HashOf("tree " + string.Join("|", sorted.Select(entry => $"{entry.Mode:X} {entry.Name} {entry.Sha}"))); + this.trees[sha] = sorted; + return sha; + } + + public TreeEnumerationResult TryReadTree(byte[] treeId, TreeEntryVisitor visitor) + { + this.ReadCount++; + string sha = SHA1Util.HexStringFromBytes(treeId); + if (this.FailingTrees.TryGetValue(sha, out TreeEnumerationResult failure)) + { + return failure; + } + + if (this.MissingTrees.Contains(sha) || !this.trees.TryGetValue(sha, out List entries)) + { + return TreeEnumerationResult.MissingTree; + } + + foreach (TreeEntry entry in entries) + { + visitor(Encoding.UTF8.GetBytes(entry.Name), SHA1Util.BytesFromHexString(entry.Sha), entry.Mode); + } + + return TreeEnumerationResult.Success; + } + + public bool TryDownloadTree(string treeSha) + { + this.Downloads.Add(treeSha); + if (this.DownloadSucceedsWithoutEffect.Contains(treeSha)) + { + return true; + } + + if (this.DownloadableTrees.Remove(treeSha)) + { + this.MissingTrees.Remove(treeSha); + return true; + } + + return false; + } + } + + /// + /// A set of files and empty trees. It builds the trees in a , and + /// writes a full index or a sparse index for the files. + /// + private class TestRepository + { + private readonly SortedDictionary files = new SortedDictionary(StringComparer.Ordinal); + private readonly HashSet emptyTrees = new HashSet(StringComparer.Ordinal); + private Dictionary treeShas; + + public FakeTreeStore Store { get; } = new FakeTreeStore(); + + public static string HashOf(string value) + { + using (SHA1 sha1 = SHA1.Create()) + { + return SHA1Util.HexStringFromBytes(sha1.ComputeHash(Encoding.UTF8.GetBytes(value))).ToLowerInvariant(); + } + } + + public void AddFile(string path, uint mode = RegularMode) + { + this.files.Add(path, new TreeEntry(path, mode, HashOf("blob " + path))); + this.treeShas = null; + } + + public void AddEmptyTree(string path) + { + this.emptyTrees.Add(path); + this.treeShas = null; + } + + public string GetTreeSha(string folderPath) + { + return this.BuildTrees()[folderPath]; + } + + public byte[] CreateFullIndex(params string[] notSkipWorktree) + { + return GitIndexV4Writer.Create(this.files.Values + .Select(file => new Entry(file.Name, (ushort)file.Mode, file.Sha) { SkipWorktree = !notSkipWorktree.Contains(file.Name) }) + .ToArray()); + } + + public byte[] CreateSparseIndex(params string[] sparseDirectories) + { + return this.CreateSparseIndex(sparseDirectories, new string[0]); + } + + public byte[] CreateSparseIndex(string[] sparseDirectories, params string[] notSkipWorktree) + { + Dictionary trees = this.BuildTrees(); + List entries = this.files.Values + .Where(file => !sparseDirectories.Any(folder => file.Name.StartsWith(folder + "/", StringComparison.Ordinal))) + .Select(file => new Entry(file.Name, (ushort)file.Mode, file.Sha) { SkipWorktree = !notSkipWorktree.Contains(file.Name) }) + .ToList(); + entries.AddRange(sparseDirectories.Select(folder => new Entry(folder + "/", GitIndexV4Writer.SparseDirectoryMode, trees[folder]))); + return GitIndexV4Writer.Create(entries.OrderBy(entry => entry.Path, StringComparer.Ordinal).ToArray()); + } + + /// + /// Adds a tree for every folder to the store, and returns the tree SHA of each folder path. + /// + private Dictionary BuildTrees() + { + if (this.treeShas != null) + { + return this.treeShas; + } + + Dictionary> folderEntries = new Dictionary>(StringComparer.Ordinal) { { string.Empty, new List() } }; + foreach (string folder in this.files.Keys.Select(GetParent).Concat(this.emptyTrees).ToList()) + { + for (string current = folder; current.Length > 0; current = GetParent(current)) + { + if (!folderEntries.ContainsKey(current)) + { + folderEntries.Add(current, new List()); + } + } + } + + foreach (TreeEntry file in this.files.Values) + { + folderEntries[GetParent(file.Name)].Add(new TreeEntry(GetName(file.Name), file.Mode, file.Sha)); + } + + this.treeShas = new Dictionary(StringComparer.Ordinal); + foreach (string folder in folderEntries.Keys.OrderByDescending(path => path.Count(c => c == '/')).ThenByDescending(path => path.Length)) + { + if (folder.Length == 0) + { + continue; + } + + string sha = this.Store.AddTree(folderEntries[folder].ToArray()); + this.treeShas.Add(folder, sha); + folderEntries[GetParent(folder)].Add(new TreeEntry(GetName(folder), TreeMode, sha)); + } + + return this.treeShas; + } + + private static string GetParent(string path) + { + int separator = path.LastIndexOf('/'); + return separator < 0 ? string.Empty : path.Substring(0, separator); + } + + private static string GetName(string path) + { + return path.Substring(path.LastIndexOf('/') + 1); + } + } + } +} diff --git a/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs b/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs index c3410cd73..dc605c46a 100644 --- a/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs +++ b/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs @@ -3,6 +3,7 @@ using GVFS.Common.FileSystem; using GVFS.Common.Git; using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; using GVFS.Common.Tracing; using GVFS.Virtualization.Background; using GVFS.Virtualization.BlobSize; @@ -48,6 +49,9 @@ public class FileSystemCallbacks : IDisposable, IHeartBeatMetadataProvider private GitStatusCache gitStatusCache; private bool enableGitStatusCache; + // Receives the working-tree changes, or null. See SetWorkingDirectoryChangeObserver. + private IWorkingDirectoryChangeObserver workingDirectoryChangeObserver; + public FileSystemCallbacks( GVFSContext context, GVFSGitObjects gitObjects, @@ -120,6 +124,8 @@ public FileSystemCallbacks( this.gitStatusCache = gitStatusCache ?? new GitStatusCache(context, TimeSpan.Zero); this.gitStatusCache.SetProjectedFolderCountProvider( () => this.GitIndexProjection.GetProjectedFolderCount()); + this.gitStatusCache.SetProjectedFileCountProvider( + () => this.GitIndexProjection.GetProjectedFileCountIfSparseIndex()); this.gitStatusCache.SetModifiedPathsProvider(this.GetAllModifiedPaths); this.logsHeadPath = this.context.Enlistment.GitHeadLogPath; @@ -419,9 +425,12 @@ public bool IsPathOrParentInModifiedPaths(string path, bool isFolder) /// Finds index entries that are staged (differ from HEAD) matching the given /// pathspec, and adds them to ModifiedPaths. This prepares for an unstage operation /// (e.g., restore --staged) by ensuring git will clear skip-worktree for these - /// entries so it can detect their working tree state correctly. - /// Files that were added (not in HEAD) are also written to disk from the git object - /// store as full files, so they persist after projection changes. + /// entries so it can detect their working tree state correctly. Each path is also + /// reported to the working-tree change observer (see + /// ). + /// Files that were added (not in HEAD) and were not modified paths yet are also + /// written to disk from the git object store as full files, so they persist after + /// projection changes. /// /// /// IPC message body. Formats: @@ -487,16 +496,17 @@ public bool AddStagedFilesToModifiedPaths(string messageBody, out int addedCount return; } - string platformPath = gitPath.Replace(GVFSConstants.GitPathSeparator, Path.DirectorySeparatorChar); - if (this.modifiedPaths.TryAdd(platformPath, isFolder: false, isRetryable: out _)) + if (this.TryAddStagedFileToModifiedPaths(gitPath, out bool wasModifiedPath)) { added++; } // Added files (in index but not in HEAD) are ProjFS placeholders that // would vanish when the projection reverts to HEAD. Collect them for - // hydration below. - if (status.StartsWith("A")) + // hydration below. A path that already was a modified path is a file that + // the user or Git owns in the working tree, and it can have unstaged + // changes, so it is not overwritten with the staged content. + if (!wasModifiedPath && status.StartsWith("A")) { addedFilePaths.Add(gitPath); } @@ -624,6 +634,41 @@ public bool AddStagedFilesToModifiedPaths(string messageBody, out int addedCount return success; } + /// + /// Add one staged file to ModifiedPaths, and report it to the working-tree change + /// observer. + /// + /// + /// git reset --soft changes which files are staged without a file system write, so + /// no callback reports these paths. With a sparse index, Git clears skip-worktree only for + /// a path that has its own index entry, so the cone must include the path before Git + /// unstages it. The observer makes a cone change pending when the cone does not include + /// the path. + /// + /// The path relative to the working-tree root, with forward slashes. + /// + /// True when ModifiedPaths already had the path or one of its parent folders before this call. + /// + /// True when ModifiedPaths has the path or one of its parent folders. + internal bool TryAddStagedFileToModifiedPaths(string gitPath, out bool wasModifiedPath) + { + wasModifiedPath = false; + if (string.IsNullOrEmpty(gitPath)) + { + return false; + } + + string platformPath = gitPath.Replace(GVFSConstants.GitPathSeparator, Path.DirectorySeparatorChar); + wasModifiedPath = this.IsPathOrParentInModifiedPaths(platformPath, isFolder: false); + if (!this.modifiedPaths.TryAdd(platformPath, isFolder: false, isRetryable: out _)) + { + return false; + } + + this.NotifyWorkingDirectoryChange(platformPath, isFolder: false); + return true; + } + /// /// Writes the staged (index) versions of files to the working directory as /// full files, bypassing ProjFS. Uses "git checkout-index --force" with @@ -727,25 +772,48 @@ public void OnExcludeFileChanged() this.InvalidateGitStatusCache(); } + /// + /// Set the receiver of working-tree changes, or null to stop the notifications. The + /// receiver runs in file system callbacks. + /// + public void SetWorkingDirectoryChangeObserver(IWorkingDirectoryChangeObserver observer) + { + Volatile.Write(ref this.workingDirectoryChangeObserver, observer); + } + + /// + /// A handle to a file that was written was closed. This happens for every change, also + /// for a file that already is a full file. + /// + public void OnFileModified(string relativePath) + { + this.InvalidateGitStatusCache(); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); + } + public void OnFileCreated(string relativePath) { this.AddToNewlyCreatedList(relativePath, isFolder: false); this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileCreated(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFileOverwritten(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileOverwritten(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFileSuperseded(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileSuperseded(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFileConvertedToFull(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileConvertedToFull(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFailedFileHydration(string relativePath) @@ -756,21 +824,26 @@ public void OnFailedFileHydration(string relativePath) public virtual void OnFileRenamed(string oldRelativePath, string newRelativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileRenamed(oldRelativePath, newRelativePath)); + this.NotifyWorkingDirectoryChange(oldRelativePath, isFolder: false); + this.NotifyWorkingDirectoryChange(newRelativePath, isFolder: false); } public virtual void OnFileHardLinkCreated(string newLinkRelativePath, string existingRelativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileHardLinkCreated(newLinkRelativePath, existingRelativePath)); + this.NotifyWorkingDirectoryChange(newLinkRelativePath, isFolder: false); } public virtual void OnFileSymLinkCreated(string newLinkRelativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileSymLinkCreated(newLinkRelativePath)); + this.NotifyWorkingDirectoryChange(newLinkRelativePath, isFolder: false); } public void OnFileDeleted(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileDeleted(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFilePreDelete(string relativePath) @@ -801,16 +874,20 @@ public void OnFolderCreated(string relativePath, out bool sparseFoldersUpdated) this.AddToNewlyCreatedList(relativePath, isFolder: true); this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFolderCreated(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: true); } public virtual void OnFolderRenamed(string oldRelativePath, string newRelativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFolderRenamed(oldRelativePath, newRelativePath)); + this.NotifyWorkingDirectoryChange(oldRelativePath, isFolder: true); + this.NotifyWorkingDirectoryChange(newRelativePath, isFolder: true); } public void OnFolderDeleted(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFolderDeleted(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: true); } public void OnPossibleTombstoneFolderCreated(string relativePath) @@ -823,6 +900,15 @@ public void OnFolderPreDelete(string relativePath) this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFolderPreDelete(relativePath)); } + private void NotifyWorkingDirectoryChange(string relativePath, bool isFolder) + { + IWorkingDirectoryChangeObserver observer = Volatile.Read(ref this.workingDirectoryChangeObserver); + if (observer != null && !string.IsNullOrEmpty(relativePath) && !IsPathInsideDotGit(relativePath)) + { + observer.OnWorkingDirectoryPathChanged(relativePath, isFolder); + } + } + public void OnPlaceholderFileCreated(string relativePath, string sha, string triggeringProcessImageFileName) { this.GitIndexProjection.OnPlaceholderFileCreated(relativePath, sha); diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.FolderData.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.FolderData.cs index f4866a6b4..2492595b9 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.FolderData.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.FolderData.cs @@ -44,6 +44,31 @@ public int GetRecursiveFolderCount() return count; } + public int GetRecursiveFileCount() + { + int count = 0; + Stack stack = new Stack(); + stack.Push(this); + + while (stack.Count > 0) + { + FolderData current = stack.Pop(); + for (int i = 0; i < current.ChildEntries.Count; i++) + { + if (current.ChildEntries[i] is FolderData childFolder) + { + stack.Push(childFolder); + } + else + { + count++; + } + } + } + + return count; + } + public void ResetData(LazyUTF8String name, bool isIncluded) { this.Name = name; diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexEntry.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexEntry.cs index 4c0a7b715..f8f8d3685 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexEntry.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexEntry.cs @@ -59,6 +59,12 @@ public bool PathEndsInSlash get { return this.PathLength > 0 && this.PathBuffer[this.PathLength - 1] == PathSeparatorCode; } } + /// + /// True when the entry is a sparse-directory entry that the parser accepted. Its path ends + /// in '/', and its is the id of the tree of the collapsed folder. + /// + public bool IsSparseDirectory { get; set; } + public FolderData BuildingProjection_LastParent { get; set; } // Only used when buildingNewProjection is true @@ -155,6 +161,38 @@ public unsafe void BuildingProjection_ParsePath() } } + /// + /// Parses the path of a sparse-directory entry, without its trailing '/', into + /// . The final part is the name of the + /// collapsed folder. It should only be called when building a new projection. + /// + /// + /// Call before and after this method. This method does not + /// change , so the prefix compression of the next entry stays correct. + /// + public unsafe void BuildingProjection_ParseSparseDirectoryPath() + { + int length = this.PathLength - 1; + int currentPartStartIndex = 0; + this.BuildingProjection_NumParts = 0; + + fixed (byte* pathPtr = this.PathBuffer) + { + for (int i = 0; i < length; i++) + { + if (pathPtr[i] == PathSeparatorCode) + { + this.BuildingProjection_PathParts[this.BuildingProjection_NumParts] = LazyUTF8String.FromByteArray(pathPtr + currentPartStartIndex, i - currentPartStartIndex); + this.BuildingProjection_NumParts++; + currentPartStartIndex = i + 1; + } + } + + this.BuildingProjection_PathParts[this.BuildingProjection_NumParts] = LazyUTF8String.FromByteArray(pathPtr + currentPartStartIndex, length - currentPartStartIndex); + this.BuildingProjection_NumParts++; + } + } + /// /// Parses the path from the index as platform-specific relative path. /// It should only be called when running a background task. diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexParser.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexParser.cs index f1498566f..06249914a 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexParser.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexParser.cs @@ -19,6 +19,7 @@ internal partial class GitIndexParser private const ushort ExtendedBit = 0x4000; private const ushort SkipWorktreeBit = 0x4000; + private const byte PathSeparatorByte = (byte)'/'; private Stream indexStream; private byte[] page; @@ -50,10 +51,28 @@ public enum MergeStage : byte Theirs = 3 } - public static void ValidateIndex(ITracer tracer, Stream indexStream) + /// + /// What does with a sparse-directory entry of a sparse index. + /// + public enum SparseDirectoryHandling + { + /// + /// Throw . The default, when + /// gvfs.auto-sparse-index is false. + /// + Reject, + + /// + /// Validate the entry, and give it to the entry action with + /// set. + /// + Accept, + } + + public static void ValidateIndex(ITracer tracer, Stream indexStream, SparseDirectoryHandling sparseDirectoryHandling = SparseDirectoryHandling.Reject) { GitIndexParser indexParser = new GitIndexParser(null); - FileSystemTaskResult result = indexParser.ParseIndex(tracer, indexStream, indexParser.resuableProjectionBuildingIndexEntry, ValidateIndexEntry); + FileSystemTaskResult result = indexParser.ParseIndex(tracer, indexStream, indexParser.resuableProjectionBuildingIndexEntry, sparseDirectoryHandling, ValidateIndexEntry); if (result != FileSystemTaskResult.Success) { @@ -75,6 +94,7 @@ public static int CountIndexFolders(ITracer tracer, Stream indexStream) tracer, indexStream, indexParser.resuableProjectionBuildingIndexEntry, + SparseDirectoryHandling.Reject, entry => { // Match the same filter as AddIndexEntryToProjection so the @@ -117,10 +137,13 @@ public void RebuildProjection(ITracer tracer, Stream indexStream) } this.projection.ClearProjectionCaches(); + this.projection.projectionHasExpandedSparseDirectories = false; + this.projection.sparseDirectoryExpander?.StartBuild(this.projection.GetModifiedPathsForExpansion); FileSystemTaskResult result = this.ParseIndex( tracer, indexStream, this.resuableProjectionBuildingIndexEntry, + this.projection.ProjectionSparseDirectoryHandling, this.AddIndexEntryToProjection); if (result != FileSystemTaskResult.Success) @@ -128,6 +151,8 @@ public void RebuildProjection(ITracer tracer, Stream indexStream) // RebuildProjection should always result in FileSystemTaskResult.Success (or a thrown exception) throw new InvalidOperationException($"{nameof(this.RebuildProjection)}: {nameof(GitIndexParser.ParseIndex)} failed to {nameof(this.AddIndexEntryToProjection)}"); } + + this.projection.projectionHasExpandedSparseDirectories = this.projection.sparseDirectoryExpander?.SparseDirectoryCount > 0; } public FileSystemTaskResult AddMissingModifiedFilesAndRemoveThemFromPlaceholderList( @@ -149,21 +174,34 @@ public FileSystemTaskResult AddMissingModifiedFilesAndRemoveThemFromPlaceholderL { "FilePlaceholderCount", filePlaceholders.Count } }); + // The tree id of each sparse-directory entry, by the platform-relative folder path + Dictionary sparseDirectories = new Dictionary(GVFSPlatform.Instance.Constants.PathComparer); + FileSystemTaskResult result = this.ParseIndex( tracer, indexStream, this.resuableBackgroundTaskThreadIndexEntry, - (data) => this.AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfNeeded(data, filePlaceholders)); + this.projection.ProjectionSparseDirectoryHandling, + (data) => this.AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfNeeded(data, filePlaceholders, sparseDirectories)); if (result != FileSystemTaskResult.Success) { return result; } + SparseDirectoryTreeLookup treeLookup = sparseDirectories.Count > 0 && this.projection.sparseDirectoryExpander != null + ? new SparseDirectoryTreeLookup(this.projection.sparseDirectoryExpander.TreeReader) + : null; + // Any paths that were not found in the index need to be added to ModifiedPaths // and removed from the placeholder list foreach (string path in filePlaceholders) { + if (treeLookup != null && this.IsInSparseDirectoryTree(tracer, path, sparseDirectories, treeLookup)) + { + continue; + } + result = this.projection.AddModifiedPath(path); if (result != FileSystemTaskResult.Success) { @@ -176,6 +214,34 @@ public FileSystemTaskResult AddMissingModifiedFilesAndRemoveThemFromPlaceholderL return FileSystemTaskResult.Success; } + /// + /// Replaces control and format characters with \uXXXX escapes, so that a path read from + /// the index cannot add lines or terminal escape sequences to a message. + /// + internal static string EscapeForDisplay(string value) + { + StringBuilder escaped = null; + for (int i = 0; i < value.Length; i++) + { + char c = value[i]; + if (char.IsControl(c) || CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Format) + { + if (escaped == null) + { + escaped = new StringBuilder(value, 0, i, value.Length + 16); + } + + escaped.Append("\\u").Append(((int)c).ToString("X4")); + } + else + { + escaped?.Append(c); + } + } + + return escaped?.ToString() ?? value; + } + private static FileSystemTaskResult ValidateIndexEntry(GitIndexEntry data) { if (data.PathLength <= 0 || data.PathBuffer[0] == 0) @@ -212,56 +278,61 @@ private static string GetSparseDirectoryEntryErrorMessage(string entryPath, stri } /// - /// Replaces control and format characters with \uXXXX escapes, so that a path read from - /// the index cannot add lines or terminal escape sequences to a message. + /// Handles a sparse-directory entry from a sparse index (git index.sparse). Such an entry + /// has mode 040000, a tree id, the skip-worktree bit, and a path that ends in '/'. It + /// stands in for a collapsed subtree. /// - private static string EscapeForDisplay(string value) + /// + /// ParseIndex calls this for every entry, before the entry callback. A callback that does + /// not know about sparse-directory entries would treat the entry as a file: the projection + /// would omit every file in the collapsed subtree and contain a folder with an empty name, + /// and the placeholder scan would treat every placeholder in the subtree as absent from + /// the index. Thus throws, and + /// sets . + /// The check uses the trailing '/' because ParseIndex reads the mode field only when + /// SupportsFileMode is true, and it is false on Windows. + /// + private void HandleSparseDirectoryEntry(GitIndexEntry data, SparseDirectoryHandling sparseDirectoryHandling, bool parseMode) { - StringBuilder escaped = null; - for (int i = 0; i < value.Length; i++) + data.IsSparseDirectory = false; + if (!data.PathEndsInSlash && data.TypeAndMode.Type != FileType.Directory) { - char c = value[i]; - if (char.IsControl(c) || CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Format) - { - if (escaped == null) - { - escaped = new StringBuilder(value, 0, i, value.Length + 16); - } - - escaped.Append("\\u").Append(((int)c).ToString("X4")); - } - else - { - escaped?.Append(c); - } + return; } - return escaped?.ToString() ?? value; - } - - /// - /// Throws if is a sparse-directory entry from a sparse index - /// (git index.sparse). Such an entry has mode 040000, a tree id, the skip-worktree bit, - /// and a path that ends in '/'. It stands in for a collapsed subtree. - /// - /// - /// ParseIndex calls this for every entry, before the entry callback. A callback that - /// received the entry would treat it as a file: the projection would omit every file in - /// the collapsed subtree and contain a folder with an empty name, and the placeholder scan - /// would treat every placeholder in the subtree as absent from the index. The check uses - /// the trailing '/' because ParseIndex reads the mode field only when SupportsFileMode is - /// true, and it is false on Windows. - /// - private void FailIfSparseDirectoryEntry(GitIndexEntry data) - { - if (data.PathEndsInSlash || data.TypeAndMode.Type == FileType.Directory) + string entryPath = Encoding.UTF8.GetString(data.PathBuffer, 0, data.PathLength); + if (sparseDirectoryHandling == SparseDirectoryHandling.Reject) { - string entryPath = Encoding.UTF8.GetString(data.PathBuffer, 0, data.PathLength); throw new SparseIndexNotSupportedException(GetSparseDirectoryEntryErrorMessage( entryPath, this.projection?.context.Enlistment.WorkingDirectoryRoot, this.projection?.projectionIndexBackupPath)); } + + string error = null; + if (!data.PathEndsInSlash) + { + error = "has the directory mode, but its path does not end in '/'"; + } + else if (parseMode && data.TypeAndMode.Type != FileType.Directory) + { + error = "has a path that ends in '/', but it does not have the directory mode"; + } + else if (data.PathLength < 2 || data.PathBuffer[0] == PathSeparatorByte || entryPath.Contains("//", StringComparison.Ordinal)) + { + error = "has an empty path component"; + } + else if (data.MergeState != MergeStage.NoConflicts) + { + error = "has a merge stage"; + } + + if (error != null) + { + throw new InvalidDataException($"The sparse-directory entry '{EscapeForDisplay(entryPath)}' in the index {error}"); + } + + data.IsSparseDirectory = true; } private FileSystemTaskResult AddIndexEntryToProjection(GitIndexEntry data) @@ -269,8 +340,15 @@ private FileSystemTaskResult AddIndexEntryToProjection(GitIndexEntry data) // Never want to project the common ancestor even if the skip worktree bit is on if ((data.MergeState != MergeStage.CommonAncestor && data.SkipWorktree) || data.MergeState == MergeStage.Yours) { - data.BuildingProjection_ParsePath(); - this.projection.AddItemFromIndexEntry(data); + if (data.IsSparseDirectory) + { + this.projection.AddSparseDirectoryEntry(data); + } + else + { + data.BuildingProjection_ParsePath(); + this.projection.AddItemFromIndexEntry(data); + } } else { @@ -290,15 +368,40 @@ private FileSystemTaskResult AddIndexEntryToProjection(GitIndexEntry data) /// AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfNeeded is called for all entries in the index /// filePlaceholders will contain only those placeholders that are not in the index. /// + /// + /// Receives the tree id of each sparse-directory entry that has the skip-worktree bit, by + /// the platform-relative folder path. Git sets the bit on every entry of a collapsed + /// folder, so a placeholder for a file in the tree of the entry is in the index with the bit. + /// private FileSystemTaskResult AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfNeeded( GitIndexEntry gitIndexEntry, - HashSet filePlaceholders) + HashSet filePlaceholders, + Dictionary sparseDirectories) { gitIndexEntry.BackgroundTask_ParsePath(); string placeholderRelativePath = gitIndexEntry.BackgroundTask_GetPlatformRelativePath(); FileSystemTaskResult result = FileSystemTaskResult.Success; + if (gitIndexEntry.IsSparseDirectory) + { + string folderRelativePath = placeholderRelativePath.TrimEnd(GVFSPlatform.GVFSPlatformConstants.PathSeparator); + if (gitIndexEntry.SkipWorktree) + { + sparseDirectories[folderRelativePath] = (byte[])gitIndexEntry.Sha.Clone(); + } + else + { + // Git cleared the skip-worktree bit of the collapsed folder, as it does for each + // entry under a modified folder. The folder path covers every file under it. The + // placeholders under the folder stay in filePlaceholders, so the caller removes + // them from the placeholder list, as it does for a file that is not in the index. + result = this.projection.AddModifiedPath(folderRelativePath, isFolder: true); + } + + return result; + } + if (!gitIndexEntry.SkipWorktree) { // A git command (e.g. 'git reset --mixed') may have cleared a file's skip worktree bit without @@ -324,6 +427,44 @@ private FileSystemTaskResult AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfN return result; } + /// + /// True if is under a sparse-directory entry, and the + /// file is in the tree of that entry. Such a file is in the index with the skip-worktree bit. + /// + /// + /// If a tree cannot be read, this returns false, so the caller treats the placeholder as + /// a file that is not in the index: GVFS keeps the file and adds it to the modified paths. + /// + private bool IsInSparseDirectoryTree( + ITracer tracer, + string placeholderPath, + Dictionary sparseDirectories, + SparseDirectoryTreeLookup treeLookup) + { + char separator = GVFSPlatform.GVFSPlatformConstants.PathSeparator; + for (int separatorIndex = placeholderPath.IndexOf(separator); + separatorIndex > 0; + separatorIndex = placeholderPath.IndexOf(separator, separatorIndex + 1)) + { + if (sparseDirectories.TryGetValue(placeholderPath.Substring(0, separatorIndex), out byte[] treeId)) + { + string[] relativePathParts = placeholderPath.Substring(separatorIndex + 1).Split(separator); + SparseDirectoryFileLookupResult lookupResult = treeLookup.FindFile(treeId, relativePathParts); + if (lookupResult == SparseDirectoryFileLookupResult.TreeUnreadable) + { + EventMetadata metadata = CreateEventMetadata(); + metadata.Add("PlaceholderPath", placeholderPath); + metadata.Add(TracingConstants.MessageKey.WarningMessage, "Cannot read a tree of a sparse directory. The placeholder is treated as a file that is not in the index."); + tracer.RelatedWarning(metadata, $"{nameof(this.IsInSparseDirectoryTree)}: Tree unreadable"); + } + + return lookupResult == SparseDirectoryFileLookupResult.Found; + } + } + + return false; + } + /// /// Takes an action on a GitIndexEntry using the index in indexStream /// @@ -335,13 +476,14 @@ private FileSystemTaskResult AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfN /// /// Only the AddToModifiedFiles method because it updates the modified paths file can result /// in TryIndexAction returning a FileSystemTaskResult other than Success. All other actions result in success (or an exception in the - /// case of a corrupt index). ParseIndex throws SparseIndexNotSupportedException for a sparse - /// index, before any action receives a sparse-directory entry. + /// case of a corrupt index). See for the + /// sparse-directory entries of a sparse index. /// private FileSystemTaskResult ParseIndex( ITracer tracer, Stream indexStream, GitIndexEntry resuableParsedIndexEntry, + SparseDirectoryHandling sparseDirectoryHandling, Func entryAction) { this.indexStream = indexStream; @@ -385,7 +527,7 @@ private FileSystemTaskResult ParseIndex( // 4-bit object type // valid values in binary are 1000(regular file), 1010(symbolic link) and 1110(gitlink) - // 0100(directory) is a sparse-directory entry, which FailIfSparseDirectoryEntry rejects + // 0100(directory) is a sparse-directory entry, which HandleSparseDirectoryEntry handles // 3-bit unused // 9-bit unix permission. Only 0755 and 0644 are valid for regular files. (Legacy repos can also contain 664) // Symbolic links and gitlinks have value 0 in this field. @@ -415,8 +557,8 @@ private FileSystemTaskResult ParseIndex( break; case FileType.Directory: - // A sparse-directory entry. FailIfSparseDirectoryEntry rejects it - // with an actionable message after the parser reads its path. + // A sparse-directory entry. HandleSparseDirectoryEntry handles it + // after the parser reads its path. if (typeAndMode.Mode != 0) { throw new InvalidDataException($"Invalid file mode {typeAndMode.GetModeAsOctalString()} found for sparse directory in index"); @@ -462,7 +604,7 @@ private FileSystemTaskResult ParseIndex( this.ReadPath(resuableParsedIndexEntry, resuableParsedIndexEntry.ReplaceIndex, bytesToRead); previousPathLength = resuableParsedIndexEntry.PathLength; - this.FailIfSparseDirectoryEntry(resuableParsedIndexEntry); + this.HandleSparseDirectoryEntry(resuableParsedIndexEntry, sparseDirectoryHandling, parseMode); result = entryAction.Invoke(resuableParsedIndexEntry); if (result != FileSystemTaskResult.Success) diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.LazyUTF8String.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.LazyUTF8String.cs index 973c5077a..c69f1f783 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.LazyUTF8String.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.LazyUTF8String.cs @@ -265,7 +265,8 @@ public BytePool(ITracer tracer, uint indexEntryCount) public void MakeFreeSpace(int count) { - if (this.FreeIndex + count > this.Pool.Length) + // One expansion adds 15% of the pool, which can be less than a long name + while (this.FreeIndex + count > this.Pool.Length) { this.ExpandPool(); } diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SortedFolderEntries.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SortedFolderEntries.cs index ac0aa18c2..e163f2450 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SortedFolderEntries.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SortedFolderEntries.cs @@ -2,6 +2,7 @@ using GVFS.Common.Tracing; using System; using System.Collections.Generic; +using System.IO; namespace GVFS.Virtualization.Projection { @@ -142,6 +143,31 @@ public FolderData GetOrAddFolder( return this.InsertFolder(pathParts[partIndex], ~index, isIncluded: isIncluded); } + /// + /// Returns the child folder with the given name, or adds it if no entry has the name. + /// Name matching is the same as , + /// so two folder names that differ only in case share one folder on a case-insensitive + /// file system. The new folder gets . An existing folder + /// keeps its own inclusion state. + /// + /// A file has the name + public FolderData GetOrAddFolder(LazyUTF8String name, bool isIncluded) + { + int index = this.GetSortedEntriesIndexOfName(name); + if (index >= 0) + { + FolderData existingFolder = this.sortedEntries[index] as FolderData; + if (existingFolder == null) + { + throw new InvalidDataException($"Found a file where a folder was expected: {GitIndexParser.EscapeForDisplay(name.GetString())}"); + } + + return existingFolder; + } + + return this.InsertFolder(name, ~index, isIncluded); + } + public bool TryGetValue(LazyUTF8String name, out FolderEntryData value) { int index = this.GetSortedEntriesIndexOfName(name); diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SparseDirectoryExpander.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SparseDirectoryExpander.cs new file mode 100644 index 000000000..83e25f941 --- /dev/null +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SparseDirectoryExpander.cs @@ -0,0 +1,965 @@ +using GVFS.Common; +using GVFS.Common.Git; +using GVFS.Common.Tracing; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Threading; + +namespace GVFS.Virtualization.Projection +{ + public partial class GitIndexProjection + { + /// + /// The result of . + /// + internal enum SparseDirectoryFileLookupResult + { + Found, + NotFound, + TreeUnreadable, + } + + /// + /// Reads the tree objects behind the sparse-directory entries of a sparse index. + /// + /// Implementations must be safe to use from more than one thread. + internal interface IProjectionTreeReader + { + /// + /// Reads a tree from the local object store. Does not download objects. + /// + TreeEnumerationResult TryReadTree(byte[] treeId, TreeEntryVisitor visitor); + + /// + /// Downloads a tree into the local object store. + /// + /// True if the download succeeded + bool TryDownloadTree(string treeSha); + } + + /// + /// Reads trees through the libgit2 repository of the mount, and downloads a missing tree + /// through the object requestor of the mount. + /// + internal class ProjectionTreeReader : IProjectionTreeReader + { + private readonly GitRepo repository; + private readonly GVFSGitObjects gitObjects; + private readonly CancellationToken cancellationToken; + + /// Cancels a download when the mount stops + public ProjectionTreeReader(GitRepo repository, GVFSGitObjects gitObjects, CancellationToken cancellationToken) + { + this.repository = repository; + this.gitObjects = gitObjects; + this.cancellationToken = cancellationToken; + } + + public TreeEnumerationResult TryReadTree(byte[] treeId, TreeEntryVisitor visitor) + { + return this.repository.TryEnumerateTree(treeId, visitor); + } + + public bool TryDownloadTree(string treeSha) + { + if (this.gitObjects == null) + { + return false; + } + + try + { + return this.gitObjects.TryDownloadAndSaveObject(treeSha, this.cancellationToken, GVFSGitObjects.RequestSource.ProjectionBuild) + == GitObjects.DownloadAndSaveObjectResult.Success; + } + catch (OperationCanceledException) + { + return false; + } + } + } + + /// + /// Adds the files under a sparse-directory entry to the projection. The result is the same + /// projection that the full index (one entry for each file) gives. + /// + /// + /// + /// The walk is depth first and in tree order. Git tree order is the same as index order, + /// so folders and files are added in the order that the full index adds them. Thus folder + /// names that differ only in case merge as they do for a full index, and the first name wins. + /// + /// + /// A folder is added only when a file under it is added. A full index has no entry for an + /// empty tree, so an empty tree does not add a folder. + /// + /// + /// A file is not added if the file, or a folder above it, is in the modified paths. See + /// . + /// + /// + /// If a tree is not local, the expander downloads it once. If a tree is still missing, is + /// not a tree, or cannot be read, or if an entry cannot be in a full index, the expander + /// throws . The mount never serves a projection + /// that does not contain every file. + /// + /// + /// The expander is not thread safe. Use it only on the thread that builds the projection. + /// + /// + internal class SparseDirectoryExpander + { + // A full index cannot hold a longer path: GitIndexEntry has a 4096-byte path buffer. + internal const int MaxPathLength = 4095; + + private const int ShaLength = 20; + private const uint FileTypeMask = 0xF000; + private const uint TreeFileType = 0x4000; + private const byte GitPathSeparatorByte = (byte)'/'; + private const byte BackslashByte = (byte)'\\'; + + private const string MountWithoutSparseIndexSupport = + "To mount without sparse-index support, run 'git -c core.hookspath= config gvfs.auto-sparse-index false' " + + "in the 'src' folder of the enlistment. Then run 'gvfs mount', which shows the steps that expand the index."; + + private readonly ITracer tracer; + private readonly bool platformSupportsFileMode; + private readonly bool useWindowsNameRules; + private readonly SparseFolderData rootSparseFolder; + private readonly Dictionary nonDefaultFileTypesAndModes; + private readonly TreeEntryVisitor visitor; + private readonly List children = new List(); + private readonly List childFrames = new List(); + private readonly List framesWithoutFolder = new List(); + private readonly Stack stack = new Stack(); + private readonly byte[] shaBuffer = new byte[ShaLength]; + private readonly Stopwatch expansionTime = new Stopwatch(); + + private byte[] childIds = new byte[ShaLength * 64]; + private Func> getModifiedPaths; + private ModifiedPathsFilter modifiedPathsFilter; + + // Set during Expand + private FolderData rootFolderData; + private GitIndexEntry sparseDirectoryEntry; + private TreeFrame currentFrame; + + public SparseDirectoryExpander( + ITracer tracer, + IProjectionTreeReader treeReader, + SparseFolderData rootSparseFolder, + Dictionary nonDefaultFileTypesAndModes) + { + this.tracer = tracer; + this.TreeReader = treeReader; + this.platformSupportsFileMode = GVFSPlatform.Instance.FileSystem.SupportsFileMode; + this.useWindowsNameRules = GVFSPlatform.GVFSPlatformConstants.PathSeparator == '\\'; + this.rootSparseFolder = rootSparseFolder; + this.nonDefaultFileTypesAndModes = nonDefaultFileTypesAndModes; + this.visitor = this.AddChildEntry; + } + + public IProjectionTreeReader TreeReader { get; private set; } + + public int SparseDirectoryCount { get; private set; } + public int SkippedSparseDirectoryCount { get; private set; } + public int TreesRead { get; private set; } + public int TreesDownloaded { get; private set; } + public int FilesAdded { get; private set; } + public int FilesSkippedAsModified { get; private set; } + + public long ElapsedMilliseconds + { + get { return this.expansionTime.ElapsedMilliseconds; } + } + + /// + /// Resets the statistics, and sets the source of the modified paths for the next build. + /// + /// + /// Returns the modified paths, in git format. Called at most once, when the build + /// expands its first sparse-directory entry. Null if there are no modified paths. + /// + public void StartBuild(Func> getModifiedPaths) + { + this.getModifiedPaths = getModifiedPaths; + this.modifiedPathsFilter = null; + this.SparseDirectoryCount = 0; + this.SkippedSparseDirectoryCount = 0; + this.TreesRead = 0; + this.TreesDownloaded = 0; + this.FilesAdded = 0; + this.FilesSkippedAsModified = 0; + this.expansionTime.Reset(); + } + + public void AddMetadata(EventMetadata metadata) + { + metadata.Add("SparseDirectoryCount", this.SparseDirectoryCount); + metadata.Add("SkippedSparseDirectoryCount", this.SkippedSparseDirectoryCount); + metadata.Add("SparseTreesRead", this.TreesRead); + metadata.Add("SparseTreesDownloaded", this.TreesDownloaded); + metadata.Add("SparseFilesAdded", this.FilesAdded); + metadata.Add("SparseFilesSkippedAsModified", this.FilesSkippedAsModified); + metadata.Add("SparseExpansionMilliseconds", this.ElapsedMilliseconds); + } + + /// + /// Adds the files under a sparse-directory entry to the projection. + /// + /// The root folder of the projection + /// + /// The sparse-directory entry. Its path parts must contain the path of the collapsed + /// folder (see ). + /// + public void Expand(FolderData rootFolderData, GitIndexEntry entry) + { + this.expansionTime.Start(); + try + { + this.SparseDirectoryCount++; + + if (this.modifiedPathsFilter == null) + { + this.modifiedPathsFilter = ModifiedPathsFilter.Create(this.getModifiedPaths?.Invoke()); + } + + bool trackPaths = this.platformSupportsFileMode || !this.modifiedPathsFilter.IsEmpty; + string rootGitPath = trackPaths ? entry.BuildingProjection_GetGitRelativePath() : null; + bool checkModifiedPaths = false; + if (!this.modifiedPathsFilter.IsEmpty) + { + if (this.modifiedPathsFilter.ContainsFolderOrParentFolder(rootGitPath)) + { + this.SkippedSparseDirectoryCount++; + return; + } + + checkModifiedPaths = this.modifiedPathsFilter.HasEntriesUnder(rootGitPath); + } + + byte[] rootTreeId = new byte[ShaLength]; + Buffer.BlockCopy(entry.Sha, 0, rootTreeId, 0, ShaLength); + + this.rootFolderData = rootFolderData; + this.sparseDirectoryEntry = entry; + this.stack.Clear(); + this.stack.Push(new TreeFrame( + parent: null, + name: entry.BuildingProjection_GetChildName(), + treeId: rootTreeId, + pathLength: entry.PathLength - 1, + inclusion: this.GetSparseDirectoryInclusion(entry), + gitPath: this.NeedsGitPath(checkModifiedPaths) ? rootGitPath : null, + checkModifiedPaths: checkModifiedPaths)); + + while (this.stack.Count > 0) + { + this.ExpandTree(this.stack.Pop()); + } + } + finally + { + this.rootFolderData = null; + this.sparseDirectoryEntry = null; + this.currentFrame = null; + this.stack.Clear(); + this.childFrames.Clear(); + this.framesWithoutFolder.Clear(); + this.children.Clear(); + this.expansionTime.Stop(); + } + } + + /// + /// Replaces the tree reader. For unit tests only. + /// + internal void SetTreeReaderForTests(IProjectionTreeReader reader) + { + this.TreeReader = reader; + } + + private static string GetChildGitPath(string parentGitPath, LazyUTF8String name) + { + return parentGitPath + GVFSConstants.GitPathSeparatorString + name.GetString(); + } + + /// + /// True if a tree entry name is ".git" for git on Windows (core.protectNTFS): the name + /// with trailing dots and spaces removed is ".git", or the name is the short name "git~1". + /// + private static bool IsWindowsDotGitName(string name) + { + return name.TrimEnd('.', ' ').Equals(GVFSConstants.DotGit.Root, StringComparison.OrdinalIgnoreCase) || + name.Equals("git~1", StringComparison.OrdinalIgnoreCase); + } + + /// + /// True if a folder needs its git path: to match modified paths under it, or to + /// record the file modes of its files. + /// + private bool NeedsGitPath(bool checkModifiedPaths) + { + return checkModifiedPaths || this.platformSupportsFileMode; + } + + private void ExpandTree(TreeFrame frame) + { + this.ReadTree(frame); + + // Add the children in tree order. Push the child trees in reverse order, so that + // the walk reads them in tree order. + this.childFrames.Clear(); + for (int i = 0; i < this.children.Count; i++) + { + ChildEntry child = this.children[i]; + int childPathLength = frame.PathLength + 1 + child.NameLength; + if (childPathLength > MaxPathLength) + { + this.ThrowExpansionException( + frame, + folder => $"The folder '{folder}' in the sparse index has a path that is longer than {MaxPathLength} bytes. Git cannot add this path to an index."); + } + + string childGitPath = frame.GitPath != null ? GetChildGitPath(frame.GitPath, child.Name) : null; + bool isTree = (child.FileMode & FileTypeMask) == TreeFileType; + + if (isTree) + { + bool checkModifiedPaths = false; + if (frame.CheckModifiedPaths) + { + if (this.modifiedPathsFilter.ContainsFolder(childGitPath)) + { + continue; + } + + checkModifiedPaths = this.modifiedPathsFilter.HasEntriesUnder(childGitPath); + } + + byte[] childTreeId = new byte[ShaLength]; + Buffer.BlockCopy(this.childIds, i * ShaLength, childTreeId, 0, ShaLength); + this.childFrames.Add(new TreeFrame( + frame, + child.Name, + childTreeId, + childPathLength, + this.GetChildInclusion(frame.Inclusion, child.Name), + this.NeedsGitPath(checkModifiedPaths) ? childGitPath : null, + checkModifiedPaths)); + } + else + { + if (frame.CheckModifiedPaths && this.modifiedPathsFilter.ContainsFile(childGitPath)) + { + this.FilesSkippedAsModified++; + continue; + } + + FileTypeAndMode typeAndMode = default(FileTypeAndMode); + if (this.platformSupportsFileMode) + { + typeAndMode = new FileTypeAndMode((ushort)child.FileMode); + this.ValidateFileTypeAndMode(frame, typeAndMode, childGitPath); + } + + Buffer.BlockCopy(this.childIds, i * ShaLength, this.shaBuffer, 0, ShaLength); + this.GetOrAddFolder(frame).AddChildFile(child.Name, this.shaBuffer); + this.FilesAdded++; + + if (this.platformSupportsFileMode && + (typeAndMode.Type != FileType.Regular || typeAndMode.Mode != FileMode644)) + { + this.nonDefaultFileTypesAndModes.Add(childGitPath, typeAndMode); + } + } + } + + for (int i = this.childFrames.Count - 1; i >= 0; i--) + { + this.stack.Push(this.childFrames[i]); + } + } + + /// + /// Reads the entries of the tree of into . + /// + private void ReadTree(TreeFrame frame) + { + this.currentFrame = frame; + this.children.Clear(); + TreeEnumerationResult result = this.TreeReader.TryReadTree(frame.TreeId, this.visitor); + + string treeSha = null; + if (result == TreeEnumerationResult.MissingTree) + { + treeSha = SHA1Util.HexStringFromBytes(frame.TreeId); + if (this.TreeReader.TryDownloadTree(treeSha)) + { + this.TreesDownloaded++; + this.children.Clear(); + result = this.TreeReader.TryReadTree(frame.TreeId, this.visitor); + } + } + + if (result != TreeEnumerationResult.Success) + { + this.children.Clear(); + treeSha = treeSha ?? SHA1Util.HexStringFromBytes(frame.TreeId); + string folderPath = this.GetFolderPathForDisplay(frame); + + EventMetadata metadata = CreateEventMetadata(); + metadata.Add("TreeSha", treeSha); + metadata.Add("Result", result.ToString()); + metadata.Add("FolderPath", folderPath); + this.tracer.RelatedError(metadata, $"{nameof(SparseDirectoryExpander)}: Failed to read the tree of a sparse directory"); + + string nextStep = result == TreeEnumerationResult.MissingTree || result == TreeEnumerationResult.RepositoryUnavailable + ? "Make sure that the network connection works, and run 'gvfs mount' again. If the problem continues: " + : string.Empty; + throw new SparseIndexExpansionException( + $"Cannot read tree {treeSha} for the folder '{GitIndexParser.EscapeForDisplay(folderPath)}' in the sparse index ({result}). " + + "VFS for Git cannot project the files in this folder. " + nextStep + MountWithoutSparseIndexSupport); + } + + this.TreesRead++; + } + + /// + /// The visitor for . Copies an entry into + /// . The projection does not change until the read succeeds. + /// + private unsafe void AddChildEntry(ReadOnlySpan name, ReadOnlySpan objectId, uint fileMode) + { + if (objectId.Length != ShaLength) + { + int idLength = objectId.Length; + this.ThrowExpansionException(this.currentFrame, folder => $"The folder '{folder}' in the sparse index has a tree entry with a {idLength}-byte object id."); + } + + this.ValidateName(name); + + int idOffset = this.children.Count * ShaLength; + if (idOffset + ShaLength > this.childIds.Length) + { + Array.Resize(ref this.childIds, this.childIds.Length * 2); + } + + objectId.CopyTo(new Span(this.childIds, idOffset, ShaLength)); + + LazyUTF8String childName; + fixed (byte* namePtr = name) + { + childName = LazyUTF8String.FromByteArray(namePtr, name.Length); + } + + this.children.Add(new ChildEntry(childName, name.Length, fileMode)); + } + + /// + /// Throws if a tree entry name cannot be a path component of a full index. Git does not + /// add such a path to an index, so a full index cannot project it. + /// + private void ValidateName(ReadOnlySpan name) + { + bool isValid = name.Length > 0; + for (int i = 0; isValid && i < name.Length; i++) + { + byte b = name[i]; + isValid = b != GitPathSeparatorByte && b != 0 && !(this.useWindowsNameRules && b == BackslashByte); + } + + string nameString = null; + if (isValid && !name.SequenceEqual("."u8) && !name.SequenceEqual(".."u8)) + { + nameString = Encoding.UTF8.GetString(name); + isValid = !nameString.Equals(GVFSConstants.DotGit.Root, StringComparison.OrdinalIgnoreCase) && + !(this.useWindowsNameRules && IsWindowsDotGitName(nameString)); + } + else + { + isValid = false; + } + + if (!isValid) + { + string invalidName = nameString ?? Encoding.UTF8.GetString(name); + this.ThrowExpansionException( + this.currentFrame, + folder => $"The folder '{folder}' in the sparse index has a tree entry with the name '{GitIndexParser.EscapeForDisplay(invalidName)}'. Git cannot add this name to an index."); + } + } + + /// + /// Throws if a file type and mode cannot be in a full index. These are the checks that + /// GitIndexParser.ParseIndex does for an entry of a full index. + /// + private void ValidateFileTypeAndMode(TreeFrame frame, FileTypeAndMode typeAndMode, string gitPath) + { + bool isValid; + switch (typeAndMode.Type) + { + case FileType.Regular: + isValid = typeAndMode.Mode == FileMode755 || typeAndMode.Mode == FileMode644 || typeAndMode.Mode == FileMode664; + break; + + case FileType.SymLink: + case FileType.GitLink: + isValid = typeAndMode.Mode == 0; + break; + + default: + isValid = false; + break; + } + + if (!isValid) + { + this.ThrowExpansionException( + frame, + folder => $"The file '{GitIndexParser.EscapeForDisplay(gitPath)}' in the folder '{folder}' of the sparse index has the invalid type {typeAndMode.Type} and mode {typeAndMode.GetModeAsOctalString()}."); + } + } + + /// + /// Logs and throws . + /// + /// Builds the message from the escaped folder path of + private void ThrowExpansionException(TreeFrame frame, Func buildMessage) + { + string message = buildMessage(GitIndexParser.EscapeForDisplay(this.GetFolderPathForDisplay(frame))) + + " VFS for Git cannot project the files in this folder. " + MountWithoutSparseIndexSupport; + + EventMetadata metadata = CreateEventMetadata(); + metadata.Add(TracingConstants.MessageKey.ErrorMessage, message); + this.tracer.RelatedError(metadata, $"{nameof(SparseDirectoryExpander)}: Invalid tree in a sparse directory"); + + throw new SparseIndexExpansionException(message); + } + + /// + /// Returns the folder of . Adds the folder, and the folders + /// above it, to the projection if they are not there. + /// + private FolderData GetOrAddFolder(TreeFrame frame) + { + if (frame.Folder != null) + { + return frame.Folder; + } + + // Find the frames above this one that have no folder yet, without recursion + this.framesWithoutFolder.Clear(); + TreeFrame current = frame; + while (current != null && current.Folder == null) + { + this.framesWithoutFolder.Add(current); + current = current.Parent; + } + + FolderData folder = current?.Folder; + for (int i = this.framesWithoutFolder.Count - 1; i >= 0; i--) + { + TreeFrame frameToAdd = this.framesWithoutFolder[i]; + folder = frameToAdd.Parent == null + ? this.GetOrAddSparseDirectoryFolder() + : folder.ChildEntries.GetOrAddFolder(frameToAdd.Name, frameToAdd.Inclusion.Included); + frameToAdd.Folder = folder; + } + + this.framesWithoutFolder.Clear(); + return frame.Folder; + } + + /// + /// Adds the folders of the sparse-directory entry path to the projection, as + /// AddFileToTree adds the folders of a file path. + /// + private FolderData GetOrAddSparseDirectoryFolder() + { + GitIndexEntry entry = this.sparseDirectoryEntry; + FolderData folder = this.rootFolderData; + for (int pathIndex = 0; pathIndex < entry.BuildingProjection_NumParts; ++pathIndex) + { + folder = folder.ChildEntries.GetOrAddFolder(entry.BuildingProjection_PathParts, pathIndex, folder.IsIncluded, this.rootSparseFolder); + } + + return folder; + } + + private string GetFolderPathForDisplay(TreeFrame frame) + { + if (frame.GitPath != null) + { + return frame.GitPath; + } + + List names = new List(); + for (TreeFrame current = frame; current.Parent != null; current = current.Parent) + { + names.Add(current.Name.GetString()); + } + + names.Add(this.sparseDirectoryEntry.BuildingProjection_GetGitRelativePath()); + names.Reverse(); + return string.Join(GVFSConstants.GitPathSeparatorString, names); + } + + /// + /// Computes the inclusion of the collapsed folder in the gvfs sparse folders, as + /// does. + /// + private FrameInclusion GetSparseDirectoryInclusion(GitIndexEntry entry) + { + if (this.rootSparseFolder.Children.Count == 0) + { + return FrameInclusion.AllIncluded; + } + + SparseFolderData node = this.rootSparseFolder; + for (int i = 0; i < entry.BuildingProjection_NumParts; i++) + { + if (node.IsRecursive) + { + return FrameInclusion.AllIncluded; + } + + if (!node.Children.TryGetValue(entry.BuildingProjection_PathParts[i].GetString(), out node)) + { + return FrameInclusion.Excluded; + } + } + + return new FrameInclusion(included: true, recursive: node.IsRecursive, node: node); + } + + /// + /// Computes the inclusion of a child folder from the inclusion of its parent folder. The + /// result is the same as the walk from the root in + /// . + /// + private FrameInclusion GetChildInclusion(FrameInclusion parent, LazyUTF8String childName) + { + if (this.rootSparseFolder.Children.Count == 0 || (parent.Included && parent.Recursive)) + { + return FrameInclusion.AllIncluded; + } + + if (!parent.Included) + { + return FrameInclusion.Excluded; + } + + if (parent.Node.Children.TryGetValue(childName.GetString(), out SparseFolderData childNode)) + { + return new FrameInclusion(included: true, recursive: childNode.IsRecursive, node: childNode); + } + + return FrameInclusion.Excluded; + } + + private readonly struct ChildEntry + { + public ChildEntry(LazyUTF8String name, int nameLength, uint fileMode) + { + this.Name = name; + this.NameLength = nameLength; + this.FileMode = fileMode; + } + + public LazyUTF8String Name { get; } + + // The length of the name in UTF-8 bytes + public int NameLength { get; } + public uint FileMode { get; } + } + + private class TreeFrame + { + public TreeFrame(TreeFrame parent, LazyUTF8String name, byte[] treeId, int pathLength, FrameInclusion inclusion, string gitPath, bool checkModifiedPaths) + { + this.Parent = parent; + this.Name = name; + this.TreeId = treeId; + this.PathLength = pathLength; + this.Inclusion = inclusion; + this.GitPath = gitPath; + this.CheckModifiedPaths = checkModifiedPaths; + } + + public TreeFrame Parent { get; } + public LazyUTF8String Name { get; } + public byte[] TreeId { get; } + + // The length of the git path of the folder in UTF-8 bytes + public int PathLength { get; } + public FrameInclusion Inclusion { get; } + + // The git path of the folder. Null unless the expander needs paths for this subtree. + public string GitPath { get; } + + // True if a modified path is under this folder + public bool CheckModifiedPaths { get; } + + // Null until the expander adds a file under this folder + public FolderData Folder { get; set; } + } + } + + /// + /// Finds whether a file is in the tree of a sparse-directory entry. The placeholder scan + /// uses it to decide if a placeholder under a collapsed folder is in the index. + /// + /// + /// Name matches use the path comparer, as the placeholder scan does for a full index. The + /// lookup caches each tree that it reads. Use one instance for one scan, on one thread. + /// + internal class SparseDirectoryTreeLookup + { + private readonly IProjectionTreeReader treeReader; + private readonly StringComparer pathComparer = GVFSPlatform.Instance.Constants.PathComparer; + private readonly Dictionary> trees = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + public SparseDirectoryTreeLookup(IProjectionTreeReader treeReader) + { + this.treeReader = treeReader; + } + + /// The tree of the sparse-directory entry + /// The path of the file under the collapsed folder, one name for each part + public SparseDirectoryFileLookupResult FindFile(byte[] treeId, string[] relativePathParts) + { + return this.FindFile(treeId, relativePathParts, 0); + } + + private SparseDirectoryFileLookupResult FindFile(byte[] treeId, string[] parts, int partIndex) + { + List children = this.ReadTree(treeId); + if (children == null) + { + return SparseDirectoryFileLookupResult.TreeUnreadable; + } + + bool isLastPart = partIndex == parts.Length - 1; + SparseDirectoryFileLookupResult result = SparseDirectoryFileLookupResult.NotFound; + foreach (TreeChild child in children) + { + if (child.IsTree == isLastPart || !this.pathComparer.Equals(child.Name, parts[partIndex])) + { + continue; + } + + if (isLastPart) + { + return SparseDirectoryFileLookupResult.Found; + } + + // Folder names that differ only in case are one folder in the projection, so + // look in each matching tree. + SparseDirectoryFileLookupResult childResult = this.FindFile(child.Id, parts, partIndex + 1); + if (childResult == SparseDirectoryFileLookupResult.Found) + { + return childResult; + } + + if (childResult == SparseDirectoryFileLookupResult.TreeUnreadable) + { + result = childResult; + } + } + + return result; + } + + private List ReadTree(byte[] treeId) + { + string treeSha = SHA1Util.HexStringFromBytes(treeId); + if (this.trees.TryGetValue(treeSha, out List cached)) + { + return cached; + } + + List children = new List(); + TreeEntryVisitor visitor = (name, objectId, fileMode) => + children.Add(new TreeChild(Encoding.UTF8.GetString(name), objectId.ToArray(), (fileMode & 0xF000) == 0x4000)); + + TreeEnumerationResult result = this.treeReader.TryReadTree(treeId, visitor); + if (result == TreeEnumerationResult.MissingTree && this.treeReader.TryDownloadTree(treeSha)) + { + children.Clear(); + result = this.treeReader.TryReadTree(treeId, visitor); + } + + if (result != TreeEnumerationResult.Success) + { + return null; + } + + this.trees.Add(treeSha, children); + return children; + } + + private readonly struct TreeChild + { + public TreeChild(string name, byte[] id, bool isTree) + { + this.Name = name; + this.Id = id; + this.IsTree = isTree; + } + + public string Name { get; } + public byte[] Id { get; } + public bool IsTree { get; } + } + } + + /// + /// The inclusion of a folder in the gvfs sparse folders (), + /// as the expander walks down a tree. + /// + internal readonly struct FrameInclusion + { + public static readonly FrameInclusion AllIncluded = new FrameInclusion(included: true, recursive: true, node: null); + public static readonly FrameInclusion Excluded = new FrameInclusion(included: false, recursive: false, node: null); + + public FrameInclusion(bool included, bool recursive, SparseFolderData node) + { + this.Included = included; + this.Recursive = recursive; + this.Node = node; + } + + /// True if the folder is included (). + public bool Included { get; } + + /// True if every folder under this folder is included. + public bool Recursive { get; } + + /// The sparse folder node that matches this folder. Null if Recursive or not Included. + public SparseFolderData Node { get; } + } + + /// + /// A snapshot of the modified paths, for the expansion of a sparse directory. + /// + /// + /// The virtual file system hook reports the modified paths to git. For a full index, git + /// clears the skip-worktree bit of each entry whose path is a modified file path, and of + /// each entry under a modified folder path ("folder/"). Matches ignore case on a + /// case-insensitive file system. The projection does not contain an entry without the + /// skip-worktree bit. The filter gives the same result for the files under a sparse directory. + /// + internal class ModifiedPathsFilter + { + private static readonly ModifiedPathsFilter Empty = new ModifiedPathsFilter(); + + private readonly HashSet files; + private readonly HashSet folders; + + // Every entry, sorted with the path comparer. The entries under a folder are contiguous. + private readonly List sortedEntries; + private readonly StringComparison pathComparison; + + private ModifiedPathsFilter() + { + this.IsEmpty = true; + } + + private ModifiedPathsFilter(IEnumerable modifiedPaths) + { + StringComparer comparer = GVFSPlatform.Instance.Constants.PathComparer; + this.pathComparison = GVFSPlatform.Instance.Constants.PathComparison; + this.files = new HashSet(comparer); + this.folders = new HashSet(comparer); + this.sortedEntries = new List(); + + foreach (string path in modifiedPaths) + { + if (string.IsNullOrEmpty(path)) + { + continue; + } + + this.sortedEntries.Add(path); + if (path[path.Length - 1] == GVFSConstants.GitPathSeparator) + { + this.folders.Add(path.Substring(0, path.Length - 1)); + } + else + { + this.files.Add(path); + } + } + + this.sortedEntries.Sort(comparer); + this.IsEmpty = this.sortedEntries.Count == 0; + } + + public bool IsEmpty { get; } + + /// Modified paths in git format. A folder path ends in '/'. Can be null. + public static ModifiedPathsFilter Create(IEnumerable modifiedPaths) + { + return modifiedPaths == null ? Empty : new ModifiedPathsFilter(modifiedPaths); + } + + /// True if is a modified file path. + public bool ContainsFile(string gitPath) + { + return !this.IsEmpty && this.files.Contains(gitPath); + } + + /// True if , without a trailing '/', is a modified folder path. + public bool ContainsFolder(string gitPath) + { + return !this.IsEmpty && this.folders.Contains(gitPath); + } + + /// + /// True if , or a folder above it, is a modified folder path. + /// + public bool ContainsFolderOrParentFolder(string gitPath) + { + if (this.IsEmpty || this.folders.Count == 0) + { + return false; + } + + for (int separatorIndex = gitPath.IndexOf(GVFSConstants.GitPathSeparator); + separatorIndex > 0; + separatorIndex = gitPath.IndexOf(GVFSConstants.GitPathSeparator, separatorIndex + 1)) + { + if (this.folders.Contains(gitPath.Substring(0, separatorIndex))) + { + return true; + } + } + + return this.folders.Contains(gitPath); + } + + /// + /// True if a modified path is under the folder . + /// + public bool HasEntriesUnder(string folderGitPath) + { + if (this.IsEmpty) + { + return false; + } + + string prefix = folderGitPath + GVFSConstants.GitPathSeparatorString; + int index = this.sortedEntries.BinarySearch(prefix, GVFSPlatform.Instance.Constants.PathComparer); + if (index < 0) + { + index = ~index; + } + + return index < this.sortedEntries.Count && this.sortedEntries[index].StartsWith(prefix, this.pathComparison); + } + } + } +} diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs index 66239dedd..74a0fc287 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs @@ -64,6 +64,19 @@ public partial class GitIndexProjection : IDisposable, IProfilerOnlyIndexProject private ReaderWriterLockSlim projectionReadWriteLock; private ManualResetEventSlim projectionParseComplete; + // Not null when gvfs.auto-sparse-index is true: the projection expands the sparse-directory + // entries of a sparse index. Null when it is false: the projection rejects a sparse index. + private SparseDirectoryExpander sparseDirectoryExpander; + + // True when the last projection build expanded at least one sparse-directory entry + private volatile bool projectionHasExpandedSparseDirectories; + + // Cancels tree downloads of the projection build when the mount stops + private CancellationTokenSource shutdownTokenSource = new CancellationTokenSource(); + + // True when a caller without a repository (gvfs repair) validates a sparse index + private bool acceptSparseDirectoriesWithoutExpansion; + private volatile bool projectionInvalid; private long projectionGeneration; @@ -117,6 +130,16 @@ public GitIndexProjection( this.rootSparseFolder = new SparseFolderData(); this.ClearProjectionCaches(); + if (this.context.Repository != null && + this.context.Repository.GetConfigBoolOrDefault(GVFSConstants.GitConfig.AutoSparseIndex, GVFSConstants.GitConfig.AutoSparseIndexDefault)) + { + this.sparseDirectoryExpander = new SparseDirectoryExpander( + this.context.Tracer, + new ProjectionTreeReader(this.context.Repository, this.gitObjects, this.shutdownTokenSource.Token), + this.rootSparseFolder, + this.nonDefaultFileTypesAndModes); + } + LocalGVFSConfig config = new LocalGVFSConfig(); if (config.TryGetConfig(GVFSConstants.LocalGVFSConfig.USNJournalUpdates, out string value, out string error)) { @@ -155,11 +178,14 @@ public enum PathSparseState Excluded, } - public static void ReadIndex(ITracer tracer, string indexPath) + public static void ReadIndex(ITracer tracer, string indexPath, bool acceptSparseDirectories = false) { using (FileStream indexStream = new FileStream(indexPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, IndexFileStreamBufferSize)) { - GitIndexParser.ValidateIndex(tracer, indexStream); + GitIndexParser.ValidateIndex( + tracer, + indexStream, + acceptSparseDirectories ? GitIndexParser.SparseDirectoryHandling.Accept : GitIndexParser.SparseDirectoryHandling.Reject); } } @@ -193,6 +219,25 @@ public void BuildProjectionFromPath(ITracer tracer, string indexPath) } } + /// + /// Parses the index into a projection, as + /// does. If is true and sparse-index expansion is + /// off for this projection, the method validates each sparse-directory entry, but it does + /// not add the files under it. Use the result only to check that the index can be parsed. + /// + public void BuildProjectionFromPath(ITracer tracer, string indexPath, bool acceptSparseDirectories) + { + this.acceptSparseDirectoriesWithoutExpansion = acceptSparseDirectories; + try + { + this.BuildProjectionFromPath(tracer, indexPath); + } + finally + { + this.acceptSparseDirectoriesWithoutExpansion = false; + } + } + public virtual void Initialize(BackgroundFileSystemTaskRunner backgroundFileSystemTaskRunner) { if (!File.Exists(this.indexPath)) @@ -243,6 +288,7 @@ public virtual void Initialize(BackgroundFileSystemTaskRunner backgroundFileSyst public virtual void Shutdown() { this.isStopping = true; + this.shutdownTokenSource?.Cancel(); this.wakeUpIndexParsingThread.Set(); this.indexParsingThread.Wait(); } @@ -359,6 +405,36 @@ public virtual int GetProjectedFolderCount() } } + /// + /// True when gvfs.auto-sparse-index was true when the projection was created, so + /// the projection expands the sparse-directory entries of a sparse index. + /// + public bool IsSparseIndexSupportEnabled => this.sparseDirectoryExpander != null; + + /// + /// Get the number of files in the projection, if the projection expanded the + /// sparse-directory entries of a sparse index. A sparse index has one entry for each + /// collapsed folder, so its entry count is not the number of files. + /// + /// The number of files, or -1 if the projection came from a full index + public virtual int GetProjectedFileCountIfSparseIndex() + { + if (!this.projectionHasExpandedSparseDirectories) + { + return -1; + } + + this.projectionReadWriteLock.EnterReadLock(); + try + { + return this.projectionHasExpandedSparseDirectories ? this.rootFolderData.GetRecursiveFileCount() : -1; + } + finally + { + this.projectionReadWriteLock.ExitReadLock(); + } + } + /// /// Count unique directories by parsing the index file directly. /// This is a fallback for when the in-memory projection is not available @@ -787,6 +863,12 @@ protected virtual void Dispose(bool disposing) // resources, so it is not disposed here. this.indexParsingThread = null; } + + if (this.shutdownTokenSource != null) + { + this.shutdownTokenSource.Dispose(); + this.shutdownTokenSource = null; + } } } @@ -874,7 +956,12 @@ private void AddItemFromIndexEntry(GitIndexEntry indexEntry) private FileSystemTaskResult AddModifiedPath(string path) { - bool wasAdded = this.modifiedPaths.TryAdd(path, isFolder: false, isRetryable: out bool isRetryable); + return this.AddModifiedPath(path, isFolder: false); + } + + private FileSystemTaskResult AddModifiedPath(string path, bool isFolder) + { + bool wasAdded = this.modifiedPaths.TryAdd(path, isFolder, isRetryable: out bool isRetryable); if (!wasAdded) { return isRetryable ? FileSystemTaskResult.RetryableError : FileSystemTaskResult.FatalError; @@ -883,6 +970,56 @@ private FileSystemTaskResult AddModifiedPath(string path) return FileSystemTaskResult.Success; } + /// + /// What the index parser does with a sparse-directory entry, for this projection. + /// + private GitIndexParser.SparseDirectoryHandling ProjectionSparseDirectoryHandling + { + get + { + return this.sparseDirectoryExpander != null || this.acceptSparseDirectoriesWithoutExpansion + ? GitIndexParser.SparseDirectoryHandling.Accept + : GitIndexParser.SparseDirectoryHandling.Reject; + } + } + + /// + /// Enables the expansion of sparse-directory entries, with the given tree reader. For unit tests only. + /// + internal void EnableSparseIndexExpansionForTests(IProjectionTreeReader treeReader) + { + if (this.sparseDirectoryExpander == null) + { + this.sparseDirectoryExpander = new SparseDirectoryExpander(this.context.Tracer, treeReader, this.rootSparseFolder, this.nonDefaultFileTypesAndModes); + } + else + { + this.sparseDirectoryExpander.SetTreeReaderForTests(treeReader); + } + } + + /// + /// Adds the files under a sparse-directory entry to the projection. + /// + private void AddSparseDirectoryEntry(GitIndexEntry indexEntry) + { + // The parse of the collapsed folder path does not use the same-parent state, and the + // next entry must not use the folder of this entry as its parent. + indexEntry.ClearLastParent(); + if (this.sparseDirectoryExpander != null) + { + indexEntry.BuildingProjection_ParseSparseDirectoryPath(); + this.sparseDirectoryExpander.Expand(this.rootFolderData, indexEntry); + } + + indexEntry.ClearLastParent(); + } + + private IEnumerable GetModifiedPathsForExpansion() + { + return this.modifiedPaths?.GetAllModifiedPaths(); + } + private void ClearProjectionCaches() { SortedFolderEntries.FreePool(); @@ -1285,6 +1422,13 @@ private void ParseIndexThreadMain() } } } + catch (SparseIndexExpansionException e) when (this.isStopping) + { + // A tree download that the shutdown canceled fails the build. BuildProjection + // already marked the projection invalid, so the next mount builds it again. + EventMetadata metadata = CreateEventMetadata(e); + this.context.Tracer.RelatedWarning(metadata, "ParseIndexThreadMain: Projection build stopped by shutdown"); + } catch (Exception e) { this.LogErrorAndExit("ParseIndexThreadMain caught unhandled exception, exiting process", e); @@ -1996,6 +2140,7 @@ private void BuildProjection() catch (Exception e) { EventMetadata metadata = CreateEventMetadata(e); + this.sparseDirectoryExpander?.AddMetadata(metadata); this.context.Tracer.RelatedWarning(metadata, $"{nameof(this.BuildProjection)}: Exception thrown by {nameof(GitIndexParser.RebuildProjection)}"); this.SetProjectionInvalid(true); @@ -2011,6 +2156,7 @@ private void BuildProjection() poolMetadata.Add($"{nameof(SortedFolderEntries)}_{nameof(SortedFolderEntries.FilePoolSize)}", SortedFolderEntries.FilePoolSize()); poolMetadata.Add($"{nameof(LazyUTF8String)}_{nameof(LazyUTF8String.StringPoolSize)}", LazyUTF8String.StringPoolSize()); poolMetadata.Add($"{nameof(LazyUTF8String)}_{nameof(LazyUTF8String.BytePoolSize)}", LazyUTF8String.BytePoolSize()); + this.sparseDirectoryExpander?.AddMetadata(poolMetadata); TimeSpan duration = tracer.Stop(poolMetadata); this.context.Repository.GVFSLock.Stats.RecordParseGitIndex((long)duration.TotalMilliseconds); } diff --git a/GVFS/GVFS.Virtualization/Projection/Readme.md b/GVFS/GVFS.Virtualization/Projection/Readme.md index eab35bbf8..12ca2784c 100644 --- a/GVFS/GVFS.Virtualization/Projection/Readme.md +++ b/GVFS/GVFS.Virtualization/Projection/Readme.md @@ -146,6 +146,19 @@ Class used to store the data from the index about a single entry. There is only Class that is responsible for parsing the git index based of version 4. Please see [`index-format.txt`](https://github.com/microsoft/git/blob/f5992bb185757a1654ce31424611b4d05bda3400/Documentation/technical/index-format.txt) for detailed information of this format. This is used to both validate the index and build the projection. It currently ignores all index extensions and is only for getting the paths and building the tree using the `FolderData` and `FileData` classes. The index is read in chunks of 512K which gave the best performance. +### `SparseDirectoryExpander` + +A sparse index (git `index.sparse`) stores a folder outside the sparse-checkout cone as one sparse-directory entry. The entry has mode `040000`, a path that ends in `/`, and the id of the tree of the folder. By default (`gvfs.auto-sparse-index` is false), `GitIndexParser` rejects a sparse index. When `gvfs.auto-sparse-index` is true, `SparseDirectoryExpander` reads the tree behind each sparse-directory entry through libgit2, and adds every file under it to the projection. The projection is then the same as the projection of the full index: + +- Folders and files are added in index order, so folder names that differ only in case merge as they do for a full index. +- A folder is added only when a file is added under it. A full index has no entry for an empty tree. +- A file is not added if the file, or a folder above it, is in the modified paths. For a full index, git clears the skip-worktree bit of those entries, and the projection does not contain them. +- If a tree is not in the local object store, the expander downloads it once. If the tree is still missing, is not a tree, or cannot be read, or if an entry cannot be in a full index, the projection build fails with `SparseIndexExpansionException`. The mount never serves a projection with missing files. + +The background placeholder scan treats a placeholder under a sparse-directory entry as an index entry only if the file is in the tree of that entry. + +The expansion reads every tree under every sparse-directory entry on each projection build. + ## Other classes ### `ProjectedFileInfo` diff --git a/GVFS/GVFS.Virtualization/Projection/SparseIndexExpansionException.cs b/GVFS/GVFS.Virtualization/Projection/SparseIndexExpansionException.cs new file mode 100644 index 000000000..b5b91c653 --- /dev/null +++ b/GVFS/GVFS.Virtualization/Projection/SparseIndexExpansionException.cs @@ -0,0 +1,20 @@ +using System; + +namespace GVFS.Virtualization.Projection +{ + /// + /// The projection cannot expand a sparse-directory entry of a sparse index + /// (gvfs.auto-sparse-index is true). The message tells the user what to do next. + /// + /// + /// Do not derive from IOException. The index parsing thread retries an IOException, and + /// a retry under the projection write lock does not fix a tree that cannot be read. + /// + public class SparseIndexExpansionException : Exception + { + public SparseIndexExpansionException(string message) + : base(message) + { + } + } +} diff --git a/GVFS/GVFS.Virtualization/Projection/SparseIndexNotSupportedException.cs b/GVFS/GVFS.Virtualization/Projection/SparseIndexNotSupportedException.cs index 575a25c8f..9f0193cb9 100644 --- a/GVFS/GVFS.Virtualization/Projection/SparseIndexNotSupportedException.cs +++ b/GVFS/GVFS.Virtualization/Projection/SparseIndexNotSupportedException.cs @@ -3,7 +3,8 @@ namespace GVFS.Virtualization.Projection { /// - /// The git index is a sparse index (git index.sparse), and the projection cannot use it. + /// The git index is a sparse index (git index.sparse), and sparse-index support + /// (gvfs.auto-sparse-index) is off, so the projection cannot use the index. /// The message tells the user how to expand the index. /// /// diff --git a/GVFS/GVFS/RepairJobs/RepairJob.cs b/GVFS/GVFS/RepairJobs/RepairJob.cs index 1d1ff4da3..b712a1f64 100644 --- a/GVFS/GVFS/RepairJobs/RepairJob.cs +++ b/GVFS/GVFS/RepairJobs/RepairJob.cs @@ -1,5 +1,6 @@ using GVFS.Common; using GVFS.Common.FileSystem; +using GVFS.Common.Git; using GVFS.Common.Tracing; using GVFS.Virtualization.Projection; using System; @@ -112,6 +113,12 @@ protected bool TryDeleteFolder(string filePath) protected IssueType TryParseIndex(string path, List messages) { GVFSContext context = new GVFSContext(this.Tracer, null, null, this.Enlistment); + bool sparseIndexEnabled = LibGit2Repo.GetConfigBoolOrDefault( + this.Tracer, + this.Enlistment.WorkingDirectoryBackingRoot, + GVFSConstants.GitConfig.AutoSparseIndex, + GVFSConstants.GitConfig.AutoSparseIndexDefault, + this.Enlistment.CreateGitProcess(this.Tracer).TryGetBoolFromConfig); using (GitIndexProjection index = new GitIndexProjection( context, @@ -125,7 +132,9 @@ protected IssueType TryParseIndex(string path, List messages) { try { - index.BuildProjectionFromPath(this.Tracer, path); + // When sparse-index support is on, a sparse-directory entry is valid. Repair + // checks the entry, but it does not read the trees under it. + index.BuildProjectionFromPath(this.Tracer, path, acceptSparseDirectories: sparseIndexEnabled); } catch (SparseIndexNotSupportedException ex) {