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