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..2fe762d46 100644
--- a/GVFS/GVFS.Common/Git/GitProcess.cs
+++ b/GVFS/GVFS.Common/Git/GitProcess.cs
@@ -831,6 +831,99 @@ 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);
+ }
+ });
+ }
+
+ /// 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;
+ }
+
public Result Status(bool allowObjectDownloads, bool useStatusCache, bool showUntracked = false)
{
string command = "status";
diff --git a/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs
index 412c9fec0..be774e38b 100644
--- a/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs
+++ b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs
@@ -16,8 +16,9 @@ public static partial class NamedPipeMessages
/// it added for that command.
///
/// The hook treats every reply other than as "not applied"
- /// and lets Git run. This includes from a mount that does
- /// not handle these messages, , no reply within the
+ /// 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.
///
///
@@ -28,11 +29,12 @@ public static partial class NamedPipeMessages
///
///
/// 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). Two Git commands can widen the
- /// same directory at the same time, because commands that do not take the GVFS lock
- /// (for example git diff -- <path>) also send widen requests. 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.
+ /// (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.
///
///
/// A body is a list of fields separated by NUL. The header and the body split on the
diff --git a/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs
new file mode 100644
index 000000000..a38e67e7c
--- /dev/null
+++ b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs
@@ -0,0 +1,706 @@
+using GVFS.Common.FileSystem;
+using GVFS.Common.Git;
+using GVFS.Common.NamedPipes;
+using GVFS.Common.Tracing;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Globalization;
+using System.Threading;
+
+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 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.
+ /// 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. The narrow arrives after the post-command hook
+ /// released the GVFS lock, so the mount cannot replace the index (see
+ /// ). The index keeps the expanded
+ /// entries, all skip-worktree, until the next widen collapses every directory outside the
+ /// cone.
+ ///
+ ///
+ /// 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.
+ ///
+ ///
+ public class AutoSparseIndexConeManager
+ {
+ /// 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";
+
+ private const string WidenEventName = "ConeWiden";
+ private const string NarrowEventName = "ConeNarrow";
+ private const int MaxTracedPaths = 10;
+
+ // The mount does not start Git for a widen later than this after it got the request:
+ // neither after a wait for earlier requests, nor after the checks before Git. The hook
+ // waits for the reply up to WidenReplyCeilingMs after it sent the request, so this leaves
+ // the other half of that time for "git sparse-checkout reapply" (measured: less than
+ // 500 ms). A refusal costs more than a slow widen: Git checks a pathspec against the cone,
+ // so "git add -- " fails for a modified path outside the cone. Thus the mount
+ // refuses only when reapply could not finish inside the ceiling.
+ internal const int DefaultMaxElapsedBeforeApplyMs = NamedPipeMessages.ConeManagement.WidenReplyCeilingMs / 2;
+
+ 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 int maxElapsedBeforeApplyMs;
+ private readonly TransientConeState transientState = new TransientConeState();
+ private readonly Lock coneLock = new Lock();
+
+ // 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);
+
+ public AutoSparseIndexConeManager(
+ ITracer tracer,
+ PhysicalFileSystem fileSystem,
+ string sparseCheckoutPath,
+ bool ignoreCase,
+ IConeManagerEnvironment environment)
+ : this(tracer, fileSystem, sparseCheckoutPath, ignoreCase, environment, DefaultMaxElapsedBeforeApplyMs)
+ {
+ }
+
+ internal AutoSparseIndexConeManager(
+ ITracer tracer,
+ PhysicalFileSystem fileSystem,
+ string sparseCheckoutPath,
+ bool ignoreCase,
+ IConeManagerEnvironment environment,
+ int maxElapsedBeforeApplyMs)
+ {
+ 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.maxElapsedBeforeApplyMs = maxElapsedBeforeApplyMs;
+ }
+
+ private enum ConeChange
+ {
+ Applied,
+ ConeUnchanged,
+ Narrowed,
+ NothingToNarrow,
+ NoCommandId,
+ InvalidRequest,
+ TooManyPaths,
+ NotLockHolder,
+ CommandEnded,
+ CommandAlreadyNarrowed,
+ InvalidPath,
+ QueueWaitTooLong,
+ TooLateToApply,
+ ExpandsModifiedPath,
+ SparseDirectoriesUnknown,
+ ConeFileLocked,
+ WriteFailed,
+ ApplyFailed,
+ UnexpectedException,
+ }
+
+ ///
+ /// 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;
+
+ 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.
+ ///
+ /// 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);
+
+ ConeChange change = this.RunAndCatch(() => this.Widen(parameters, stopwatch, metadata), 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;
+ }
+
+ ///
+ /// 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.TooLateToApply:
+ case ConeChange.SparseDirectoriesUnknown:
+ case ConeChange.ConeFileLocked:
+ case ConeChange.WriteFailed:
+ case ConeChange.ApplyFailed:
+ case ConeChange.UnexpectedException:
+ return true;
+
+ default:
+ return false;
+ }
+ }
+
+ private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parameters, 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;
+ }
+
+ // 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;
+ }
+
+ if (parameters.Paths.Count <= MaxTracedPaths)
+ {
+ metadata.Add("Paths", string.Join(";", parameters.Paths));
+ }
+
+ this.RemoveEndedCommands(metadata);
+
+ if (!this.TryGetStartTime(processId, out long startTime))
+ {
+ return ConeChange.CommandEnded;
+ }
+
+ if (this.transientState.IsNarrowed(processId, startTime))
+ {
+ return ConeChange.CommandAlreadyNarrowed;
+ }
+
+ if (stopwatch.ElapsedMilliseconds > this.maxElapsedBeforeApplyMs)
+ {
+ return ConeChange.QueueWaitTooLong;
+ }
+
+ List modifiedPaths = new List(this.environment.GetModifiedPaths());
+
+ // A modified file that exists keeps its content when Git expands its directory.
+ // A deleted file, or a modified folder, does not. Only those need the list of
+ // sparse-directory entries.
+ List unsafePaths = modifiedPaths.FindAll(
+ path => path.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal) || !this.environment.IsFileInWorkingDirectory(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(parameters.Paths);
+ 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;
+ }
+
+ // The checks above can run Git. Check again just before the child Git process
+ // takes the index lock: if the requester no longer holds the GVFS lock, or its hook
+ // can stop waiting before Git ends, the user's Git could find the index lock.
+ if (!this.environment.CanWriteIndex(processId))
+ {
+ return ConeChange.NotLockHolder;
+ }
+
+ if (stopwatch.ElapsedMilliseconds > this.maxElapsedBeforeApplyMs)
+ {
+ return ConeChange.TooLateToApply;
+ }
+
+ 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.transientState.Add(processId, startTime, parameters.Paths);
+ 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;
+ return ConeChange.ApplyFailed;
+ }
+
+ this.indexMayDifferFromCone = false;
+ this.transientState.Add(processId, startTime, parameters.Paths);
+ 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;
+ }
+
+ // Until the cone file is written, a later request must write it again.
+ this.coneFileMayBeStale = true;
+
+ List modifiedPaths = new List(this.environment.GetModifiedPaths());
+ if (!this.TryBuildCone(this.GetConePaths(modifiedPaths, this.hiddenModifiedPaths), metadata, out ConePatternSet cone))
+ {
+ return ConeChange.InvalidPath;
+ }
+
+ 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());
+
+ // The 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;
+ return ConeChange.ConeUnchanged;
+
+ default:
+ this.coneFileMayBeStale = false;
+ this.indexMayDifferFromCone = true;
+ 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))
+ {
+ paths.Add(modifiedPath);
+ }
+ }
+
+ paths.AddRange(this.transientState.GetAllPaths());
+ return paths;
+ }
+
+ 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);
+ }
+
+ if (IsFailure(change) || exceededWaitBudget || metadata.ContainsKey("DeleteBackupError"))
+ {
+ 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;
+ }
+ }
+ }
+}
diff --git a/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs b/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs
new file mode 100644
index 000000000..3676af85f
--- /dev/null
+++ b/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs
@@ -0,0 +1,50 @@
+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);
+ }
+}
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/SparseIndexGitSupportGuard.cs b/GVFS/GVFS.Common/Sparse/SparseIndexGitSupportGuard.cs
new file mode 100644
index 000000000..e41247aad
--- /dev/null
+++ b/GVFS/GVFS.Common/Sparse/SparseIndexGitSupportGuard.cs
@@ -0,0 +1,107 @@
+using System;
+using System.Collections.Generic;
+
+namespace GVFS.Common.Sparse
+{
+ ///
+ /// Decides whether a mount must refuse to start, because the enlistment uses the automatic
+ /// sparse index and the Git that the mount runs does not support it.
+ ///
+ ///
+ /// A Git without handles a
+ /// cone-mode sparse-checkout file under a virtual file system wrongly. For example,
+ /// git add -- <path outside the cone> exits 0 and stages nothing. Git applies a cone,
+ /// and writes a sparse index, only with a cone-mode sparse-checkout file. Thus that file and
+ /// gvfs.auto-sparse-index are the triggers.
+ ///
+ /// core.sparseCheckout, index.sparse, and a sparse-checkout file without the
+ /// cone header are not triggers. Without a cone-mode file, Git does not use them for a
+ /// sparse index. Versions of VFS for Git before 2018 set core.sparseCheckout to
+ /// true and wrote a non-cone sparse-checkout file, and such enlistments mount with any
+ /// supported Git. A sparse-directory entry in the index is not a trigger either: when the
+ /// feature is off, the projection refuses such an index with its own recovery steps.
+ ///
+ ///
+ public static class SparseIndexGitSupportGuard
+ {
+ /// The number of bytes of the sparse-checkout file that the cone check needs.
+ public const int ConeHeaderReadLength = 64;
+
+ [Flags]
+ public enum Triggers
+ {
+ None = 0,
+
+ /// gvfs.auto-sparse-index is true.
+ AutoSparseIndex = 1,
+
+ /// The sparse-checkout file has the cone-mode header.
+ ConeFile = 2,
+ }
+
+ ///
+ /// Return the states of the enlistment that need a Git with the sparse-index feature.
+ ///
+ /// The value of gvfs.auto-sparse-index.
+ ///
+ /// The start of the sparse-checkout file (at least
+ /// bytes, decoded), or null when the file does not exist.
+ ///
+ public static Triggers GetTriggers(bool autoSparseIndex, string coneFileStart)
+ {
+ Triggers triggers = Triggers.None;
+ if (autoSparseIndex)
+ {
+ triggers |= Triggers.AutoSparseIndex;
+ }
+
+ if (ConeCoverage.HasConeHeader(coneFileStart))
+ {
+ triggers |= Triggers.ConeFile;
+ }
+
+ return triggers;
+ }
+
+ ///
+ /// The mount error for , with the recovery steps.
+ ///
+ /// The triggers, not .
+ /// The Git that the mount runs.
+ /// The version of that Git.
+ /// The full path of the sparse-checkout file.
+ public static string GetRefusalMessage(Triggers triggers, string gitBinPath, string gitVersion, string sparseCheckoutPath)
+ {
+ if (triggers == Triggers.None)
+ {
+ throw new ArgumentException("There is no trigger", nameof(triggers));
+ }
+
+ List reasons = new List();
+ if ((triggers & Triggers.AutoSparseIndex) != 0)
+ {
+ reasons.Add($"{GVFSConstants.GitConfig.AutoSparseIndex} is true");
+ }
+
+ if ((triggers & Triggers.ConeFile) != 0)
+ {
+ reasons.Add($"'{sparseCheckoutPath}' is a cone-mode sparse-checkout file");
+ }
+
+ string newLine = Environment.NewLine;
+ return
+ $"Error: This enlistment uses a sparse index ({string.Join(", ", reasons)}), " +
+ $"but the Git that VFS for Git runs ('{gitBinPath}', version {gitVersion}) does not report " +
+ $"'{AutoSparseIndexConeManager.SparseIndexFeature}' in 'git version --build-options'. " +
+ "With this Git, commands such as 'git add' can skip files outside the sparse-checkout cone." + newLine +
+ "To mount, do one of these:" + newLine +
+ $"- Install a Git that reports '{AutoSparseIndexConeManager.SparseIndexFeature}', then run 'gvfs mount'." + newLine +
+ "- Turn the sparse index off. In the 'src' folder of the enlistment, run these commands, then run 'gvfs mount':" + newLine +
+ $" git -c core.hookspath= config --unset-all {GVFSConstants.GitConfig.AutoSparseIndex}" + newLine +
+ " git -c core.hookspath= config --unset-all index.sparse" + newLine +
+ " git -c core.hookspath= config core.sparseCheckout false" + newLine +
+ $" del \"{sparseCheckoutPath}\"" + newLine +
+ " If 'gvfs mount' then reports a sparse-directory entry in the index, do the steps in that message.";
+ }
+ }
+}
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..b8a8a1152
--- /dev/null
+++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs
@@ -0,0 +1,304 @@
+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.Text;
+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 : TestsWithEnlistmentPerFixture
+ {
+ private const string BypassGVFS = "-c core.virtualfilesystem= -c core.hookspath=";
+ private const string RootOnlyCone = "/*\n!/*/\n";
+ private const string ConeManagementPrefix = "gvfs cone-management: ";
+ private const string HookFailurePrefix = ConeManagementPrefix + "widen not applied";
+
+ private static readonly UTF8Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
+
+ // 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;
+ private int traceCount;
+
+ [OneTimeSetUp]
+ public void EnableSparseIndex()
+ {
+ 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')");
+ }
+
+ List headFiles = 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();
+ List> directories = headFiles
+ .GroupBy(path => TwoLevelDirectory(path), StringComparer.OrdinalIgnoreCase)
+ .ToList();
+ 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 => path.Substring(0, path.LastIndexOf('/')), StringComparer.OrdinalIgnoreCase))
+ .First(group => group.Count() >= 2)
+ .Take(2)
+ .ToList();
+ this.deletedFile = pair[0];
+ this.siblingOfDeletedFile = pair[1];
+
+ // 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();
+ }
+
+ private string SparseCheckoutPath => this.Enlistment.GetDotGitPath("info", "sparse-checkout");
+
+ [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);
+ ConeRequestsShouldSucceed(add);
+ 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. A narrow can reach the mount after the command ended, so the
+ // test waits for it. The index is still sparse, and it still has the entries of
+ // that directory until the next widen.
+ string[] coneLines = this.WaitForConeFile(lines => !lines.Any(line => IsConeLineFor(line, unmodifiedDirectory)));
+ coneLines.ShouldContain(line => IsConeLineFor(line, TwoLevelDirectory(modifiedFile)));
+ coneLines.ShouldNotContain(line => IsConeLineFor(line, unmodifiedDirectory));
+ string cone = File.ReadAllText(this.SparseCheckoutPath);
+ 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);
+ ConeRequestsShouldSucceed(laterAdd);
+ CountFullIndexExpansions(laterTrace).ShouldEqual(0, "git expanded the whole index: " + laterAdd.Errors);
+ this.SparseIndexEntries().ShouldNotContain(entry => entry.StartsWith(unmodifiedDirectory + "/", StringComparison.OrdinalIgnoreCase) && !entry.EndsWith("/"));
+ string.Join("\n", this.WaitForConeFile(lines => string.Join("\n", lines) == cone)).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);
+ ConeRequestsShouldSucceed(firstAdd.Result);
+ ConeRequestsShouldSucceed(secondAdd.Result);
+ 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 = File.ReadAllText(this.SparseCheckoutPath);
+
+ // 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");
+ File.ReadAllText(this.SparseCheckoutPath).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);
+ ConeRequestsShouldSucceed(add);
+ 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()
+ {
+ // Expanding the directory of a deleted file makes Git check the file out again, so
+ // the mount must not widen the cone to that directory.
+ File.Delete(this.Enlistment.GetVirtualPathTo(this.deletedFile));
+
+ ProcessResult add = this.GitWithTrace($"add -- {this.siblingOfDeletedFile}", out _);
+
+ add.ExitCode.ShouldEqual(0, add.Errors);
+ add.Errors.ShouldContain(HookFailurePrefix + ": Rejected");
+ File.Exists(this.Enlistment.GetVirtualPathTo(this.deletedFile)).ShouldBeFalse("The widen restored the deleted file");
+ }
+
+ private static void ConeRequestsShouldSucceed(ProcessResult result)
+ {
+ // The hooks print "gvfs cone-management: not applied: " for each
+ // request that the mount did not apply, for example a widen that timed out. A narrow
+ // can end after Git ends, because the hook waits for it only NarrowWaitBudgetMs.
+ result.Errors.Split('\n')
+ .Where(line => line.StartsWith(ConeManagementPrefix, StringComparison.Ordinal) &&
+ line.Contains(" not applied") &&
+ !line.StartsWith(ConeManagementPrefix + "narrow ", StringComparison.Ordinal))
+ .ShouldBeEmpty("A cone request failed: " + result.Errors);
+ }
+
+ private static string[] ConeLines(string cone)
+ {
+ return cone.Split('\n');
+ }
+
+ private string[] WaitForConeFile(Func isExpected)
+ {
+ string[] lines = ConeLines(File.ReadAllText(this.SparseCheckoutPath));
+ for (int attempt = 0; attempt < 50 && !isExpected(lines); attempt++)
+ {
+ System.Threading.Thread.Sleep(100);
+ lines = ConeLines(File.ReadAllText(this.SparseCheckoutPath));
+ }
+
+ return lines;
+ }
+
+ private static bool IsConeLineFor(string line, string directory)
+ {
+ return line.Equals("/" + directory + "/", StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static string TwoLevelDirectory(string path)
+ {
+ string[] segments = path.Split('/');
+ return segments[0] + "/" + segments[1];
+ }
+
+ private 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\""));
+ }
+
+ private ProcessResult GitWithTrace(string command, out string trace2EventFile)
+ {
+ string traceFile = Path.Combine(this.Enlistment.EnlistmentRoot, $"cone-trace2-{System.Threading.Interlocked.Increment(ref this.traceCount)}.json");
+ trace2EventFile = traceFile;
+ return GitProcess.InvokeProcess(
+ this.Enlistment.RepoRoot,
+ command,
+ new Dictionary
+ {
+ { "GIT_TRACE", "1" },
+ { "GIT_TRACE2_EVENT", traceFile },
+ });
+ }
+
+ private string GitShouldSucceed(string command)
+ {
+ ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command);
+ result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}");
+ return result.Output;
+ }
+
+ private int IndexHeaderEntryCount()
+ {
+ return GVFSHelpers.IndexHeaderEntryCount(this.Enlistment);
+ }
+
+ private List SparseDirectoryEntries()
+ {
+ return this.SparseIndexEntries().Where(line => line.EndsWith("/")).ToList();
+ }
+
+ private 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/AutoSparseIndexWithoutGitSupportTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexWithoutGitSupportTests.cs
new file mode 100644
index 000000000..f59edf8ec
--- /dev/null
+++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexWithoutGitSupportTests.cs
@@ -0,0 +1,172 @@
+using GVFS.FunctionalTests.Tools;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System;
+using System.IO;
+using System.Linq;
+using System.Text;
+
+namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture
+{
+ ///
+ /// Functional tests for the automatic sparse index with a Git that does not report
+ /// feature: vfs-sparse-index. The mount refuses such an enlistment, and the recovery
+ /// steps in its error make the enlistment work with that Git again.
+ ///
+ ///
+ /// These tests run only with such a Git, which is the Git of the PR validation build.
+ /// runs only with a Git that has the feature.
+ ///
+ [TestFixture]
+ public class AutoSparseIndexWithoutGitSupportTests : TestsWithEnlistmentPerFixture
+ {
+ private const string SparseIndexFeature = "feature: vfs-sparse-index";
+ private const string WidenEvent = "ConeWiden {";
+ private const string CommitIdentity = "-c user.name=Test -c user.email=test@example.com";
+ private const string RootOnlyCone = "/*\n!/*/\n";
+
+ // The recovery steps in the mount error. The test runs them as they are printed.
+ private static readonly string[] RecoveryGitCommands =
+ {
+ "-c core.hookspath= config --unset-all gvfs.auto-sparse-index",
+ "-c core.hookspath= config --unset-all index.sparse",
+ "-c core.hookspath= config core.sparseCheckout false",
+ };
+
+ private static readonly UTF8Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
+
+ // Files three or more levels deep, each in a different top-level directory
+ private string[] deepFiles;
+ private int fullEntryCount;
+
+ [OneTimeSetUp]
+ public void SkipWithAGitThatSupportsTheSparseIndex()
+ {
+ string buildOptions = GitProcess.Invoke(this.Enlistment.RepoRoot, "version --build-options");
+ if (buildOptions.Contains(SparseIndexFeature))
+ {
+ Assert.Ignore("This git reports 'feature: vfs-sparse-index'. AutoSparseIndexConeTests cover that git.");
+ }
+
+ string[] headFiles = this.GitShouldSucceed("-c core.quotepath=false ls-tree -r --name-only HEAD")
+ .Split('\n', StringSplitOptions.RemoveEmptyEntries)
+ .Select(path => path.Trim())
+ .ToArray();
+ this.fullEntryCount = headFiles.Length;
+ this.deepFiles = headFiles
+ .Where(path => path.Count(character => character == '/') >= 2 && !path.Contains(' '))
+ .GroupBy(path => path.Substring(0, path.IndexOf('/')), StringComparer.OrdinalIgnoreCase)
+ .Select(group => group.First())
+ .Take(2)
+ .ToArray();
+ this.deepFiles.Length.ShouldEqual(2, "HEAD has too few top-level directories with deep files");
+ }
+
+ private string SparseCheckoutPath => this.Enlistment.GetDotGitPath("info", "sparse-checkout");
+
+ [TestCase]
+ public void MountRefusesTheSparseIndexAndTheRecoveryStepsWork()
+ {
+ // The settings and the cone file that turn the feature on.
+ 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);
+
+ // A sparse index on disk, as a Git without the feature can write it. The persisted
+ // projection gets the same index, as it does when Git writes the index while the
+ // repository is mounted.
+ this.GitShouldSucceed("-c core.virtualfilesystem= -c core.hookspath= -c sparse.expectFilesOutsideOfPatterns=true update-index --force-write-index");
+ int sparseEntryCount = GVFSHelpers.IndexHeaderEntryCount(this.Enlistment);
+ (sparseEntryCount < this.fullEntryCount).ShouldBeTrue($"git did not write a sparse index: {sparseEntryCount} of {this.fullEntryCount} entries");
+ File.Copy(this.Enlistment.GetDotGitPath("index"), Path.Combine(this.Enlistment.DotGVFSRoot, "GVFS_projection"), overwrite: true);
+
+ this.Enlistment.TryMountGVFS(out string mountOutput).ShouldBeFalse("The mount accepted a git without the sparse-index feature: " + mountOutput);
+ mountOutput.ShouldContain(
+ "does not report '" + SparseIndexFeature + "'",
+ "gvfs.auto-sparse-index is true",
+ "is a cone-mode sparse-checkout file",
+ "del \"");
+ mountOutput.ShouldContain(RecoveryGitCommands.Select(command => "git " + command).ToArray());
+
+ foreach (string command in RecoveryGitCommands)
+ {
+ ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command);
+
+ // "git config --unset-all" exits with 5 when the key is not set.
+ (result.ExitCode == 0 || result.ExitCode == 5).ShouldBeTrue($"git {command} failed: {result.Errors}");
+ }
+
+ File.Delete(this.SparseCheckoutPath);
+
+ // The index is still sparse, so the projection refuses it and gives its own steps.
+ this.Enlistment.TryMountGVFS(out mountOutput).ShouldBeFalse("The mount accepted a sparse index with the feature off: " + mountOutput);
+ mountOutput.ShouldContain(
+ "contains the sparse-directory entry",
+ "git -c core.virtualfilesystem= -c core.hookspath= -c index.sparse=false update-index --force-write-index");
+ this.GitShouldSucceed("-c core.virtualfilesystem= -c core.hookspath= -c index.sparse=false update-index --force-write-index");
+ File.Delete(Path.Combine(this.Enlistment.DotGVFSRoot, "GVFS_projection"));
+
+ this.Enlistment.MountGVFS();
+
+ this.GitShouldSucceed("status");
+ this.ModifyAddAndCommit(this.deepFiles[0]);
+ this.StatusShouldBeClean();
+ GVFSHelpers.IndexHeaderEntryCount(this.Enlistment).ShouldEqual(this.fullEntryCount, "The index on disk is not full");
+ File.Exists(this.SparseCheckoutPath).ShouldBeFalse("The mount created a sparse-checkout file");
+ this.ReadMountLog().ShouldNotContain(ignoreCase: false, WidenEvent);
+ }
+
+ [TestCase]
+ public void MountAcceptsALegacySparseCheckoutFile()
+ {
+ // Versions of VFS for Git before 2018 set core.sparseCheckout to true and wrote this
+ // file. Such enlistments mount with any supported Git.
+ this.Enlistment.UnmountGVFS();
+ this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckout true");
+ File.WriteAllText(this.SparseCheckoutPath, "/.gitattributes\r\n", Utf8NoBom);
+
+ this.Enlistment.MountGVFS();
+
+ this.ModifyAddAndCommit(this.deepFiles[1]);
+ this.StatusShouldBeClean();
+ File.ReadAllText(this.SparseCheckoutPath).ShouldEqual("/.gitattributes\r\n");
+ }
+
+ private void ModifyAddAndCommit(string gitPath)
+ {
+ File.AppendAllText(this.Enlistment.GetVirtualPathTo(gitPath), Environment.NewLine + "modified by the test");
+
+ ProcessResult add = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, $"add -- {gitPath}");
+ add.ExitCode.ShouldEqual(0, add.Errors);
+ string staged = this.GitShouldSucceed("diff --cached --name-only");
+ staged.Contains(gitPath).ShouldBeTrue($"git add did not stage {gitPath}. Errors: {add.Errors}");
+
+ this.GitShouldSucceed($"{CommitIdentity} commit -m \"Change {gitPath}\"");
+ this.GitShouldSucceed("log -1 --name-only --format=").ShouldContain(gitPath);
+ }
+
+ private void StatusShouldBeClean()
+ {
+ string status = this.GitShouldSucceed("status --porcelain");
+ string.IsNullOrWhiteSpace(status).ShouldBeTrue("git status is not clean: " + status);
+ }
+
+ private string ReadMountLog()
+ {
+ return Directory.GetFiles(this.Enlistment.GVFSLogsRoot, "gvfs_mount_process_*.log")
+ .OrderByDescending(File.GetLastWriteTimeUtc)
+ .Select(GVFSHelpers.ReadAllTextFromWriteLockedFile)
+ .First();
+ }
+
+ private string GitShouldSucceed(string command)
+ {
+ ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command);
+ result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}");
+ return result.Output;
+ }
+ }
+}
diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs
index e970f42c9..4812d57e3 100644
--- a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs
+++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs
@@ -9,8 +9,8 @@ namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture
{
///
/// Functional tests for the cone requests that the hooks send when
- /// gvfs.auto-sparse-index is true. The mount does not handle these requests and
- /// answers UnknownRequest, so the tests check that Git still runs.
+ /// 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
@@ -31,7 +31,7 @@ public class ConeManagementHookTests : TestsWithEnlistmentPerFixture
};
[TestCase]
- public void GitRunsWhenTheMountDoesNotHandleConeRequests()
+ public void GitRunsWhenTheMountRepliesNotEnabled()
{
string sparseCheckoutPath = Path.Combine(this.Enlistment.RepoRoot, ".git", "info", "sparse-checkout");
string originalSparseCheckout = File.Exists(sparseCheckoutPath) ? File.ReadAllText(sparseCheckoutPath) : null;
diff --git a/GVFS/GVFS.FunctionalTests/Tools/GVFSHelpers.cs b/GVFS/GVFS.FunctionalTests/Tools/GVFSHelpers.cs
index dd485f0d7..3a604e7ff 100644
--- a/GVFS/GVFS.FunctionalTests/Tools/GVFSHelpers.cs
+++ b/GVFS/GVFS.FunctionalTests/Tools/GVFSHelpers.cs
@@ -181,6 +181,25 @@ public static string ReadAllTextFromWriteLockedFile(string filename)
}
}
+ ///
+ /// Read the entry count from the header of the index file (bytes 8 to 11, big-endian). A
+ /// sparse-directory entry counts as one entry.
+ ///
+ ///
+ /// git ls-files cannot show whether the index on disk is full or sparse: with
+ /// index.sparse true, Git collapses a full index in memory when it reads it.
+ ///
+ public static int IndexHeaderEntryCount(GVFSFunctionalTestEnlistment enlistment)
+ {
+ byte[] header = new byte[12];
+ using (FileStream stream = new FileStream(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];
+ }
+
///
/// Asserts that the modified-paths set, after replaying the on-disk
/// A/D log, contains exactly -- no more,
diff --git a/GVFS/GVFS.Hooks/Program.ConeManagement.cs b/GVFS/GVFS.Hooks/Program.ConeManagement.cs
index 27cd0c579..31353c435 100644
--- a/GVFS/GVFS.Hooks/Program.ConeManagement.cs
+++ b/GVFS/GVFS.Hooks/Program.ConeManagement.cs
@@ -14,7 +14,6 @@ namespace GVFS.Hooks
///
public partial class Program
{
- private const string CoreIgnoreCaseConfig = "core.ignorecase";
private const string GitPrefixEnvironmentVariable = "GIT_PREFIX";
// A cone file larger than this is not read. The hook then does not widen, and Git
@@ -71,7 +70,7 @@ private static bool ReadAutoSparseIndexConfig(out bool ignoreCase)
return false;
}
- ignoreCase = repo.GetConfigBool(CoreIgnoreCaseConfig) ?? false;
+ ignoreCase = repo.GetConfigBool(GitConfigSetting.CoreIgnoreCaseName) ?? false;
return true;
}
}
diff --git a/GVFS/GVFS.Mount/InProcessMount.cs b/GVFS/GVFS.Mount/InProcessMount.cs
index 91ff8c7cc..edcb99ffd 100644
--- a/GVFS/GVFS.Mount/InProcessMount.cs
+++ b/GVFS/GVFS.Mount/InProcessMount.cs
@@ -6,6 +6,7 @@
using GVFS.Common.Maintenance;
using GVFS.Common.NamedPipes;
using GVFS.Common.Prefetch;
+using GVFS.Common.Sparse;
using GVFS.Common.Tracing;
using GVFS.PlatformLoader;
using GVFS.Virtualization;
@@ -52,6 +53,10 @@ public class InProcessMount
private readonly string primaryEnlistmentId;
private FileSystemCallbacks fileSystemCallbacks;
+
+ // Handles cone widen and narrow requests. Null when gvfs.auto-sparse-index was false
+ // when the projection was created.
+ private AutoSparseIndexConeManager coneManager;
private GVFSDatabase gvfsDatabase;
private GVFSEnlistment enlistment;
private ITracer tracer;
@@ -293,6 +298,8 @@ private void MountWithLockAcquired(EventLevel verbosity, Keywords keywords)
this.ValidateGitVersion();
this.tracer.RelatedInfo("ParallelMount: ValidateGitVersion completed in {0}ms", sw.ElapsedMilliseconds);
+ this.RefuseSparseIndexWithoutGitSupport();
+
this.ValidateHooksVersion();
this.ValidateFileSystemSupportsRequiredFeatures();
@@ -944,6 +951,11 @@ private void HandleRequest(ITracer tracer, string request, NamedPipeServer.Conne
this.HandleGetHydrationStatusRequest(connection);
break;
+ case NamedPipeMessages.ConeManagement.WidenRequest:
+ case NamedPipeMessages.ConeManagement.NarrowRequest:
+ this.HandleConeRequest(message, connection);
+ break;
+
default:
EventMetadata metadata = new EventMetadata();
metadata.Add("Area", "Mount");
@@ -986,6 +998,15 @@ private void HandleGetHydrationStatusRequest(NamedPipeServer.Connection connecti
new NamedPipeMessages.Message(NamedPipeMessages.HydrationStatus.SuccessResult, response.ToBody(info)));
}
+ private void HandleConeRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection)
+ {
+ string result = this.currentState == MountState.Ready
+ ? AutoSparseIndexConeManager.HandleRequest(this.coneManager, this.tracer, message)
+ : NamedPipeMessages.MountNotReadyResult;
+
+ connection.TrySendResponse(result);
+ }
+
private void HandleDehydrateFolders(NamedPipeMessages.Message message, NamedPipeServer.Connection connection)
{
NamedPipeMessages.DehydrateFolders.Request request = NamedPipeMessages.DehydrateFolders.Request.FromMessage(message);
@@ -1770,10 +1791,126 @@ private void MountAndStartWorkingDirectoryCallbacks(CacheServerInfo cache, bool
this.FailMountAndExit("Failed to initialize src folder callbacks. {0}", e.ToString());
}
+ this.coneManager = this.CreateConeManagerIfEnabled();
+
this.heartbeat = new HeartbeatThread(this.tracer, this.fileSystemCallbacks);
this.heartbeat.Start();
}
+ private AutoSparseIndexConeManager CreateConeManagerIfEnabled()
+ {
+ // Use the value that the projection read, so that the mount never makes the index
+ // sparser than the projection can parse.
+ if (!this.fileSystemCallbacks.GitIndexProjection.IsSparseIndexSupportEnabled)
+ {
+ return null;
+ }
+
+ // Without these settings, "git sparse-checkout reapply" fails or writes a full index.
+ if (!this.context.Repository.GetConfigBoolOrDefault(GitConfigSetting.CoreSparseCheckoutName, defaultValue: false) ||
+ !this.context.Repository.GetConfigBoolOrDefault(GitConfigSetting.IndexSparseName, defaultValue: false))
+ {
+ EventMetadata metadata = new EventMetadata();
+ metadata.Add("Area", "Mount");
+ metadata.Add(
+ TracingConstants.MessageKey.WarningMessage,
+ $"{GVFSConstants.GitConfig.AutoSparseIndex} is true, but {GitConfigSetting.CoreSparseCheckoutName} or {GitConfigSetting.IndexSparseName} is not true. The mount does not change the sparse-checkout cone.");
+ this.tracer.RelatedEvent(EventLevel.Warning, nameof(this.CreateConeManagerIfEnabled), metadata, Keywords.Telemetry);
+ return null;
+ }
+
+ // A Git without the feature runs "git sparse-checkout reapply" but leaves a full index
+ // full, so the cone change would not make the index smaller.
+ GitProcess.Result buildOptions = new GitProcess(this.enlistment).VersionBuildOptions();
+ if (!AutoSparseIndexConeManager.GitSupportsSparseIndex(buildOptions))
+ {
+ EventMetadata metadata = new EventMetadata();
+ metadata.Add("Area", "Mount");
+ metadata.Add("GitBinPath", this.enlistment.GitBinPath);
+ metadata.Add("ExitCode", buildOptions.ExitCode);
+ metadata.Add(
+ TracingConstants.MessageKey.WarningMessage,
+ $"{GVFSConstants.GitConfig.AutoSparseIndex} is true, but 'git version --build-options' does not show '{AutoSparseIndexConeManager.SparseIndexFeature}'. The mount does not change the sparse-checkout cone.");
+ this.tracer.RelatedEvent(EventLevel.Warning, nameof(this.CreateConeManagerIfEnabled), metadata, Keywords.Telemetry);
+ return null;
+ }
+
+ string sparseCheckoutPath = SparseCheckoutPathResolver.GetSparseCheckoutFilePath(this.enlistment);
+ bool ignoreCase = this.context.Repository.GetConfigBoolOrDefault(GitConfigSetting.CoreIgnoreCaseName, defaultValue: false);
+ return new AutoSparseIndexConeManager(
+ this.tracer,
+ this.context.FileSystem,
+ sparseCheckoutPath,
+ ignoreCase,
+ new MountConeManagerEnvironment(this.context, this.fileSystemCallbacks, sparseCheckoutPath));
+ }
+
+ ///
+ /// Fail the mount when the enlistment uses the automatic sparse index and the Git that the
+ /// mount runs does not support it. See .
+ ///
+ private void RefuseSparseIndexWithoutGitSupport()
+ {
+ bool autoSparseIndex = LibGit2Repo.GetConfigBoolOrDefault(
+ this.tracer,
+ this.enlistment.WorkingDirectoryBackingRoot,
+ GVFSConstants.GitConfig.AutoSparseIndex,
+ GVFSConstants.GitConfig.AutoSparseIndexDefault,
+ this.enlistment.CreateGitProcess(this.tracer).TryGetBoolFromConfig);
+ string sparseCheckoutPath = SparseCheckoutPathResolver.GetSparseCheckoutFilePath(this.enlistment);
+ string coneFileStart = this.ReadConeFileStart(sparseCheckoutPath);
+
+ SparseIndexGitSupportGuard.Triggers triggers = SparseIndexGitSupportGuard.GetTriggers(autoSparseIndex, coneFileStart);
+ if (triggers == SparseIndexGitSupportGuard.Triggers.None)
+ {
+ return;
+ }
+
+ GitProcess.Result buildOptions = new GitProcess(this.enlistment).VersionBuildOptions();
+ if (AutoSparseIndexConeManager.GitSupportsSparseIndex(buildOptions))
+ {
+ return;
+ }
+
+ EventMetadata metadata = new EventMetadata();
+ metadata.Add("Area", "Mount");
+ metadata.Add("Triggers", triggers.ToString());
+ metadata.Add("GitBinPath", this.enlistment.GitBinPath);
+ metadata.Add("GitVersion", this.enlistment.GitVersion);
+ metadata.Add("BuildOptionsExitCode", buildOptions.ExitCode);
+ this.tracer.RelatedEvent(EventLevel.Warning, "SparseIndexGitNotSupported", metadata, Keywords.Telemetry);
+
+ this.FailMountAndExit(
+ "{0}",
+ SparseIndexGitSupportGuard.GetRefusalMessage(triggers, this.enlistment.GitBinPath, this.enlistment.GitVersion, sparseCheckoutPath));
+ }
+
+ ///
+ /// Read the start of the sparse-checkout file, or return null when it does not exist.
+ /// A file that cannot be read fails the mount: it could be a cone file.
+ ///
+ private string ReadConeFileStart(string sparseCheckoutPath)
+ {
+ try
+ {
+ using (FileStream stream = new FileStream(sparseCheckoutPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
+ {
+ byte[] buffer = new byte[SparseIndexGitSupportGuard.ConeHeaderReadLength];
+ int length = stream.ReadAtLeast(buffer, buffer.Length, throwOnEndOfStream: false);
+ return ConeCoverage.DecodeConeFile(buffer.AsSpan(0, length).ToArray());
+ }
+ }
+ catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException)
+ {
+ return null;
+ }
+ catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
+ {
+ this.FailMountAndExit("Failed to read the sparse-checkout file {0}: {1}", sparseCheckoutPath, e.Message);
+ return null;
+ }
+ }
+
private void ValidateGitVersion()
{
GitVersion gitVersion = null;
@@ -2202,6 +2339,8 @@ private void UnmountAndStopWorkingDirectoryCallbacks(bool willRemountInSameProce
this.heartbeat = null;
}
+ this.coneManager = null;
+
if (this.fileSystemCallbacks != null)
{
this.fileSystemCallbacks.Stop();
diff --git a/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs b/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs
new file mode 100644
index 000000000..e57cfd559
--- /dev/null
+++ b/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs
@@ -0,0 +1,120 @@
+using GVFS.Common;
+using GVFS.Common.Git;
+using GVFS.Common.NamedPipes;
+using GVFS.Common.Sparse;
+using GVFS.Virtualization;
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+namespace GVFS.Mount
+{
+ ///
+ /// The mount services that uses.
+ ///
+ internal class MountConeManagerEnvironment : IConeManagerEnvironment
+ {
+ private readonly GVFSContext context;
+ private readonly FileSystemCallbacks fileSystemCallbacks;
+ private readonly string coneFileLockPath;
+
+ public MountConeManagerEnvironment(GVFSContext context, FileSystemCallbacks fileSystemCallbacks, string sparseCheckoutPath)
+ {
+ ArgumentNullException.ThrowIfNull(context);
+ ArgumentNullException.ThrowIfNull(fileSystemCallbacks);
+ ArgumentNullException.ThrowIfNull(sparseCheckoutPath);
+
+ this.context = context;
+ this.fileSystemCallbacks = fileSystemCallbacks;
+ this.coneFileLockPath = sparseCheckoutPath + GVFSConstants.DotGit.LockExtension;
+ }
+
+ public IEnumerable GetModifiedPaths()
+ {
+ return this.fileSystemCallbacks.GetAllModifiedPaths();
+ }
+
+ public bool CanWriteIndex(int processId)
+ {
+ // While the holder waits in its pre-command hook, no other Git command writes the
+ // index. The virtualizer also blocks a rename to .git\index while no Git command
+ // holds the lock.
+ NamedPipeMessages.LockData holder = this.context.Repository.GVFSLock.GetExternalHolder();
+ return holder != null && holder.PID == processId;
+ }
+
+ public bool TryGetSparseDirectories(out IReadOnlyList sparseDirectories, out string error)
+ {
+ List directories = new List();
+ GitProcess.Result result = new GitProcess(this.context.Enlistment).ListSparseDirectories(directories.Add);
+ if (result.ExitCodeIsFailure)
+ {
+ sparseDirectories = null;
+ error = result.Errors;
+ return false;
+ }
+
+ sparseDirectories = directories;
+ error = null;
+ return true;
+ }
+
+ public bool IsFileInWorkingDirectory(string gitPath)
+ {
+ string path = Path.Combine(
+ this.context.Enlistment.WorkingDirectoryBackingRoot,
+ gitPath.Replace(GVFSConstants.GitPathSeparator, Path.DirectorySeparatorChar));
+ return this.context.FileSystem.FileExists(path);
+ }
+
+ public bool TryLockConeFile(out IDisposable coneFileLock, out Exception error)
+ {
+ coneFileLock = null;
+ error = null;
+ try
+ {
+ // Git creates the lock file with O_EXCL, so its sparse-checkout writers fail while
+ // this file exists. Windows deletes the file when the handle closes, also when the
+ // mount process ends, so a lock file never stays behind.
+ coneFileLock = this.context.FileSystem.OpenFileStream(
+ this.coneFileLockPath,
+ FileMode.CreateNew,
+ FileAccess.Write,
+ FileShare.None,
+ FileOptions.DeleteOnClose,
+ callFlushFileBuffers: false);
+ return true;
+ }
+ catch (IOException e)
+ {
+ error = e;
+ return false;
+ }
+ catch (UnauthorizedAccessException e)
+ {
+ error = e;
+ return false;
+ }
+ }
+
+ public GitProcess.Result ApplyConeToIndex()
+ {
+ // Git reports success even when it cannot replace the index (update_working_directory
+ // ignores the result of write_locked_index). A replaced index is a new file.
+ string indexPath = this.context.Enlistment.GitIndexPath;
+ DateTime before = File.GetLastWriteTimeUtc(indexPath);
+ GitProcess.Result result = new GitProcess(this.context.Enlistment).ReapplySparseCheckout();
+ if (!result.ExitCodeIsFailure && File.GetLastWriteTimeUtc(indexPath) == before)
+ {
+ return new GitProcess.Result(result.Output, "Git did not replace the index. " + result.Errors, GitProcess.Result.GenericFailureCode);
+ }
+
+ return result;
+ }
+
+ public ProcessStartTimeResult TryGetProcessStartTime(int processId, out long startTime)
+ {
+ return GVFSPlatform.Instance.TryGetActiveProcessStartTime(processId, out startTime);
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs
new file mode 100644
index 000000000..ea7f67497
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs
@@ -0,0 +1,831 @@
+using GVFS.Common;
+using GVFS.Common.Git;
+using GVFS.Common.NamedPipes;
+using GVFS.Common.Sparse;
+using GVFS.Common.Tracing;
+using GVFS.Tests.Should;
+using GVFS.UnitTests.Mock.Common;
+using GVFS.UnitTests.Mock.FileSystem;
+using NUnit.Framework;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace GVFS.UnitTests.Common.Sparse
+{
+ [TestFixture]
+ public class AutoSparseIndexConeManagerTests
+ {
+ private const string RepoRoot = @"mock:\repo";
+ private const string GitDir = @"mock:\repo\.git";
+ private const string InfoDir = @"mock:\repo\.git\info";
+ private const string SparseCheckoutPath = @"mock:\repo\.git\info\sparse-checkout";
+ private const string BackupPath = SparseCheckoutPath + ConeFileWriter.BackupExtension;
+ private const string Header = "/*\n!/*/\n";
+ private const string ConeWithAB = Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n";
+ private const string ConeWithC = Header + "/C/\n!/C/*/\n";
+
+ private const int FirstGit = 100;
+ private const int SecondGit = 200;
+
+ private MockTracer tracer;
+ private TestFileSystem fileSystem;
+ private MockEnvironment environment;
+ private AutoSparseIndexConeManager manager;
+
+ [SetUp]
+ public void SetUp()
+ {
+ this.tracer = new MockTracer();
+ this.fileSystem = new TestFileSystem();
+ this.fileSystem.WriteAllText(SparseCheckoutPath, Header);
+ this.environment = new MockEnvironment(this.fileSystem);
+ this.environment.RunningProcesses[FirstGit] = 1;
+ this.environment.RunningProcesses[SecondGit] = 2;
+ this.manager = new AutoSparseIndexConeManager(this.tracer, this.fileSystem, SparseCheckoutPath, ignoreCase: false, this.environment);
+ }
+
+ [TestCase("git version 2.56.1.vfs.0.0.6\nfeature: fsmonitor--daemon\nfeature: vfs-sparse-index\n", 0, true)]
+ [TestCase("git version 2.56.1.vfs.0.0.6\r\nfeature: vfs-sparse-index\r\n", 0, true)]
+ [TestCase("git version 2.56.1.vfs.0.1\nfeature: fsmonitor--daemon\n", 0, false)]
+ [TestCase("feature: vfs-sparse-index-v2\nfeatures: vfs-sparse-index\n", 0, false)]
+ [TestCase("feature: vfs-sparse-index\n", 1, false)]
+ [TestCase(null, 0, false)]
+ public void GitSupportsSparseIndexOnlyWithTheFeatureLine(string output, int exitCode, bool expected)
+ {
+ AutoSparseIndexConeManager.GitSupportsSparseIndex(new GitProcess.Result(output, string.Empty, exitCode)).ShouldEqual(expected);
+ }
+
+ [TestCase]
+ public void WidenWritesTheConeAndAppliesItToTheIndex()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(ConeWithAB);
+ this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB);
+ this.fileSystem.FileExists(BackupPath).ShouldBeFalse("The backup must be deleted");
+ this.LastEvent("ConeWiden").Level.ShouldEqual(EventLevel.Informational);
+ }
+
+ [TestCase]
+ public void NarrowWritesTheConeOfTheModifiedPathsWithoutRunningGit()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.ConeFile.ShouldEqual(Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n/C/\n!/C/*/\n");
+
+ this.Narrow(FirstGit).ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(ConeWithC);
+ this.environment.ConeFilesAtApply.Count.ShouldEqual(1, "The narrow must not run Git");
+ this.fileSystem.FileExists(BackupPath).ShouldBeFalse("The backup must be deleted");
+ }
+
+ [TestCase]
+ public void WidenAfterANarrowAppliesTheConeEvenWhenTheConeFileDoesNotChange()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.Narrow(FirstGit).ShouldBeTrue();
+
+ // A root file adds no directory, so the cone file stays the same. The index still
+ // has the entries that the first widen expanded, so Git must collapse them.
+ this.Widen(SecondGit, "root.txt").ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB, Header);
+ }
+
+ [TestCase]
+ public void WidenDoesNotRunGitWhenTheConeAlreadyIncludesThePaths()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+
+ this.Widen(SecondGit, "A/B/other.txt").ShouldBeTrue();
+
+ this.environment.ConeFilesAtApply.Count.ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void DirectoryStaysInTheConeUntilTheLastCommandThatNeedsItNarrows()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.Widen(SecondGit, "A/B/other.txt").ShouldBeTrue();
+
+ this.Narrow(FirstGit).ShouldBeTrue();
+ this.ConeFile.ShouldEqual(ConeWithAB);
+
+ this.Narrow(SecondGit).ShouldBeTrue();
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void EntriesOfACommandThatEndedWithoutANarrowAreRemovedAtTheNextRequest()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.environment.RunningProcesses.Remove(FirstGit);
+
+ this.Widen(SecondGit, "C/c.txt").ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(ConeWithC);
+ }
+
+ [TestCase]
+ public void NarrowOfAnotherCommandRemovesTheEntriesOfACommandThatEnded()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.environment.RunningProcesses.Remove(FirstGit);
+
+ this.Narrow(SecondGit).ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void EntriesOfAProcessIdThatAnotherProcessReusesAreRemoved()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.environment.RunningProcesses[FirstGit] = 99;
+
+ this.Narrow(SecondGit).ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void WidenThatArrivesAfterTheNarrowOfTheSameCommandIsRefused()
+ {
+ this.Narrow(FirstGit).ShouldBeTrue();
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenFromACommandThatEndedIsRefused()
+ {
+ this.environment.RunningProcesses.Remove(FirstGit);
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void WidenWithoutACommandIdIsRefused()
+ {
+ this.manager.TryWiden(new NamedPipeMessages.ConeManagement.WidenParameters(string.Empty, new[] { "A/B/b.txt" })).ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenIsRefusedWhenGitCannotReplaceTheIndex()
+ {
+ this.environment.IndexWriteAllowed = false;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenIsRefusedWhenGitHoldsTheConeFileLock()
+ {
+ this.environment.ConeFileLocked = true;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ this.LastEvent("ConeWiden").Level.ShouldEqual(EventLevel.Warning);
+ }
+
+ [TestCase]
+ public void ConeFileLockIsReleasedAfterEachRequest()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.Narrow(FirstGit).ShouldBeTrue();
+
+ this.environment.LockCount.ShouldEqual(2);
+ this.environment.IsConeFileLockHeld.ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void WidenWithAPathThatIsNotValidIsRefused()
+ {
+ this.manager.TryWiden(new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "../outside.txt" })).ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void ModifiedPathThatAConeFileCannotContainKeepsTheConeFileAndTheIndex()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.environment.ModifiedPaths.Add("D/*/d.txt");
+
+ this.Widen(SecondGit, "C/c.txt").ShouldBeFalse();
+ this.LastEvent("ConeWiden").Metadata["InvalidPathException"].ToString().ShouldContain("D/*");
+
+ this.Narrow(FirstGit).ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(ConeWithAB);
+ this.environment.ConeFilesAtApply.Count.ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void ConeFileWriteFailureLeavesTheConeFileAndTheCommandEntriesUnchanged()
+ {
+ this.fileSystem.FailRenameTo = SparseCheckoutPath;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ this.fileSystem.FileExists(BackupPath).ShouldBeFalse("The backup must be deleted");
+
+ this.fileSystem.FailRenameTo = null;
+ this.Widen(SecondGit, "C/c.txt").ShouldBeTrue();
+ this.ConeFile.ShouldEqual(ConeWithC);
+ }
+
+ [TestCase]
+ public void ApplyFailureRestoresThePreviousConeFile()
+ {
+ this.environment.ApplyExitCode = 128;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.fileSystem.FileExists(BackupPath).ShouldBeFalse("The backup must be deleted");
+ this.LastEvent("ConeWiden").Metadata["Restored"].ShouldEqual(true);
+
+ // The failed command has no entries, and the next widen applies the cone again.
+ this.environment.ApplyExitCode = 0;
+ this.Widen(SecondGit, "root.txt").ShouldBeTrue();
+ this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB, Header);
+ }
+
+ [TestCase]
+ public void ApplyExceptionRestoresThePreviousConeFile()
+ {
+ this.environment.ApplyException = new InvalidOperationException("Injected failure");
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.LastEvent("ConeWiden").Metadata["Result"].ShouldEqual("ApplyFailed");
+
+ this.environment.ApplyException = null;
+ this.Widen(SecondGit, "root.txt").ShouldBeTrue();
+ this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB, Header);
+ }
+
+ [TestCase]
+ public void NarrowWithoutEntriesDoesNotWriteTheConeFile()
+ {
+ // The first request of a mount writes the cone file, which can be stale.
+ this.Narrow(FirstGit).ShouldBeTrue();
+ this.environment.LockCount.ShouldEqual(1);
+
+ this.Narrow(SecondGit).ShouldBeTrue();
+
+ this.environment.LockCount.ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void WidenIsRefusedForACommandThatDoesNotHoldTheGVFSLock()
+ {
+ this.environment.LockHolder = SecondGit;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ this.LastEvent("ConeWiden").Metadata["Result"].ShouldEqual("NotLockHolder");
+ }
+
+ [TestCase]
+ public void WidenWithTooManyPathsIsRefused()
+ {
+ string[] paths = Enumerable.Range(0, AutoSparseIndexConeManager.MaxWidenPaths + 1).Select(i => $"D{i}/f.txt").ToArray();
+
+ this.Widen(FirstGit, paths).ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenThatWaitedTooLongForEarlierRequestsDoesNotRunGit()
+ {
+ this.UseMaxElapsedBeforeApply(500);
+ this.environment.CanWriteIndexDelayMs = 600;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ this.LastEvent("ConeWiden").Metadata["Result"].ShouldEqual("QueueWaitTooLong");
+ }
+
+ [TestCase]
+ public void WidenIsRefusedWhenTheRequesterLosesTheGVFSLockBeforeGitRuns()
+ {
+ // A deleted file makes the manager list the sparse directories with Git first.
+ this.environment.ModifiedPaths.Add("D/deleted.txt");
+ this.environment.DeletedFiles.Add("D/deleted.txt");
+ this.environment.DuringListSparseDirectories = () => this.environment.LockHolder = SecondGit;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ this.LastEvent("ConeWiden").Metadata["Result"].ShouldEqual("NotLockHolder");
+ }
+
+ [TestCase]
+ public void WidenIsRefusedWhenItCannotStartGitInTime()
+ {
+ this.UseMaxElapsedBeforeApply(500);
+ this.environment.ModifiedPaths.Add("D/deleted.txt");
+ this.environment.DeletedFiles.Add("D/deleted.txt");
+ this.environment.DuringListSparseDirectories = () => Thread.Sleep(600);
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ this.LastEvent("ConeWiden").Metadata["Result"].ShouldEqual("TooLateToApply");
+ }
+
+ [TestCase]
+ public void WidenIsRefusedWhenTheSparseDirectoriesAreNotKnown()
+ {
+ this.environment.ModifiedPaths.Add("D/deleted.txt");
+ this.environment.DeletedFiles.Add("D/deleted.txt");
+ this.environment.SparseDirectoriesFail = true;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenDoesNotListSparseDirectoriesWithoutADeletedFileOrModifiedFolder()
+ {
+ this.environment.ModifiedPaths.Add("C/edited.txt");
+ this.environment.SparseDirectoriesFail = true;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void WidenThatExpandsASparseDirectoryWithADeletedFileIsRefused()
+ {
+ // Git checks the deleted file out again when it expands A/.
+ this.environment.SparseDirectories.Add("A/");
+ this.environment.ModifiedPaths.Add("A/B/deleted.txt");
+ this.environment.DeletedFiles.Add("A/B/deleted.txt");
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ this.LastEvent("ConeWiden").Metadata["UnsafeModifiedPath"].ShouldEqual("A/B/deleted.txt");
+ }
+
+ [TestCase]
+ public void WidenOfASiblingDirectoryOfADeletedFileIsApplied()
+ {
+ // A/X stays a sparse-directory entry, so Git does not check the deleted file out.
+ this.environment.SparseDirectories.Add("A/");
+ this.environment.ModifiedPaths.Add("A/X/deleted.txt");
+ this.environment.DeletedFiles.Add("A/X/deleted.txt");
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(ConeWithAB);
+ }
+
+ [TestCase]
+ public void WidenThatExpandsASparseDirectoryWithAModifiedFolderIsRefused()
+ {
+ this.environment.SparseDirectories.Add("A/");
+ this.environment.ModifiedPaths.Add("A/B/");
+
+ this.Widen(FirstGit, "A/B/C/c.txt").ShouldBeFalse();
+
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void ModifiedFileThatExistsInsideASparseDirectoryIsInTheCone()
+ {
+ // An existing file keeps its content when Git expands its directory.
+ this.environment.SparseDirectories.Add("A/");
+ this.environment.ModifiedPaths.Add("A/B/edited.txt");
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.Narrow(FirstGit).ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(ConeWithAB);
+ }
+
+ [TestCase]
+ public void DeletedFileInsideASparseDirectoryStaysOutOfTheCone()
+ {
+ this.environment.SparseDirectories.Add("D/");
+ this.environment.ModifiedPaths.Add("D/d.txt");
+ this.environment.DeletedFiles.Add("D/d.txt");
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.ConeFile.ShouldEqual(ConeWithAB);
+
+ this.Narrow(FirstGit).ShouldBeTrue();
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void ModifiedPathWithItsOwnIndexEntryIsInTheCone()
+ {
+ this.environment.SparseDirectories.Add("D/");
+ this.environment.ModifiedPaths.Add("C/c.txt");
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n/C/\n!/C/*/\n");
+ }
+
+ [TestCase]
+ public void NarrowAfterAFailedNarrowWritesTheConeFile()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.environment.ConeFileLocked = true;
+ this.Narrow(FirstGit).ShouldBeFalse();
+ this.ConeFile.ShouldEqual(ConeWithAB);
+
+ this.environment.ConeFileLocked = false;
+ this.Narrow(SecondGit).ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void ApplyFailureDeletesAConeFileThatDidNotExistBefore()
+ {
+ this.fileSystem.DeleteFile(SparseCheckoutPath);
+ this.environment.ApplyExitCode = 128;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.fileSystem.FileExists(SparseCheckoutPath).ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void FailedRestoreKeepsTheBackupAndTheNextRequestWritesTheConeFile()
+ {
+ this.environment.ApplyExitCode = 128;
+ this.environment.DuringApply = () => this.fileSystem.FailRenameTo = SparseCheckoutPath;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.LastEvent("ConeWiden").Metadata["Restored"].ShouldEqual(false);
+ this.fileSystem.FileExists(BackupPath).ShouldBeTrue("The backup must stay when the restore fails");
+ this.ConeFile.ShouldEqual(ConeWithAB);
+
+ this.fileSystem.FailRenameTo = null;
+ this.Narrow(SecondGit).ShouldBeTrue();
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void ApplyFailureAfterASuccessfulWidenMakesTheNextWidenRunGit()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.environment.ApplyExitCode = 128;
+ this.Widen(SecondGit, "C/c.txt").ShouldBeFalse();
+ this.ConeFile.ShouldEqual(ConeWithAB);
+
+ // The cone file does not change, but Git may have changed the index before it failed.
+ this.environment.ApplyExitCode = 0;
+ this.Widen(FirstGit, "A/B/other.txt").ShouldBeTrue();
+
+ this.environment.ConeFilesAtApply.Count.ShouldEqual(3);
+ }
+
+ [TestCase]
+ public void WidenFromAProcessThatTheMountCannotOpenIsRefused()
+ {
+ this.environment.StartTimeResults[FirstGit] = ProcessStartTimeResult.Inaccessible;
+
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeFalse();
+
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void EntriesOfAProcessThatBecameInaccessibleAreRemoved()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.environment.StartTimeResults[FirstGit] = ProcessStartTimeResult.Inaccessible;
+
+ this.Narrow(SecondGit).ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void EntriesOfAProcessWithAnIndeterminateStateAreKept()
+ {
+ this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue();
+ this.environment.StartTimeResults[FirstGit] = ProcessStartTimeResult.Indeterminate;
+
+ this.Narrow(SecondGit).ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(ConeWithAB);
+ }
+
+ [TestCase]
+ public void HandleRequestRepliesFailureForARefusedWiden()
+ {
+ this.environment.LockHolder = SecondGit;
+ NamedPipeMessages.Message widen = new NamedPipeMessages.Message(
+ NamedPipeMessages.ConeManagement.WidenRequest,
+ new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "A/B/b.txt" }).ToBody());
+
+ AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, widen).ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult);
+ }
+
+ [TestCase]
+ public void ConcurrentWidensAndNarrowsEndWithTheConeOfTheModifiedPaths()
+ {
+ const int CommandCount = 16;
+ for (int i = 0; i < CommandCount; i++)
+ {
+ this.environment.RunningProcesses[1000 + i] = i;
+ }
+
+ Parallel.For(0, CommandCount, i =>
+ {
+ int processId = 1000 + i;
+ this.Widen(processId, $"Dir{i % 4}/file{i}.txt").ShouldBeTrue();
+ this.Narrow(processId).ShouldBeTrue();
+ });
+
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void HandleRequestRepliesNotEnabledWhenTheFeatureIsOff()
+ {
+ NamedPipeMessages.Message widen = new NamedPipeMessages.Message(
+ NamedPipeMessages.ConeManagement.WidenRequest,
+ new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "A/B/b.txt" }).ToBody());
+
+ AutoSparseIndexConeManager.HandleRequest(null, this.tracer, widen).ShouldEqual(NamedPipeMessages.ConeManagement.NotEnabledResult);
+ AutoSparseIndexConeManager.HandleRequest(null, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.NarrowRequest, FirstGit.ToString()))
+ .ShouldEqual(NamedPipeMessages.ConeManagement.NotEnabledResult);
+
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void HandleRequestAppliesValidRequests()
+ {
+ NamedPipeMessages.Message widen = new NamedPipeMessages.Message(
+ NamedPipeMessages.ConeManagement.WidenRequest,
+ new NamedPipeMessages.ConeManagement.WidenParameters(FirstGit.ToString(), new[] { "A/B/b.txt" }).ToBody());
+
+ AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, widen).ShouldEqual(NamedPipeMessages.ConeManagement.SuccessResult);
+ this.ConeFile.ShouldEqual(ConeWithAB);
+
+ AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.NarrowRequest, FirstGit.ToString()))
+ .ShouldEqual(NamedPipeMessages.ConeManagement.SuccessResult);
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase("100\0C:\\outside.txt")]
+ [TestCase("100\0/abs/path.txt")]
+ [TestCase("100\0A/../../outside.txt")]
+ [TestCase("not-a-pid\0A/a.txt")]
+ [TestCase("100")]
+ public void HandleRequestRepliesFailureForAWidenBodyThatIsNotValid(string body)
+ {
+ AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.WidenRequest, body))
+ .ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult);
+
+ this.ConeFile.ShouldEqual(Header);
+ this.environment.ConeFilesAtApply.ShouldBeEmpty();
+ this.tracer.RelatedWarningEvents.ShouldContain(message => message.Contains("not valid"));
+ }
+
+ [TestCase]
+ public void HandleRequestRepliesFailureForANarrowBodyThatIsNotValid()
+ {
+ AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.NarrowRequest, "12345678901"))
+ .ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult);
+ }
+
+ private string ConeFile => this.fileSystem.ReadAllText(SparseCheckoutPath);
+
+ private void UseMaxElapsedBeforeApply(int milliseconds)
+ {
+ this.manager = new AutoSparseIndexConeManager(this.tracer, this.fileSystem, SparseCheckoutPath, ignoreCase: false, this.environment, milliseconds);
+ }
+
+ private bool Widen(int processId, params string[] paths)
+ {
+ return this.manager.TryWiden(new NamedPipeMessages.ConeManagement.WidenParameters(processId.ToString(), paths));
+ }
+
+ private bool Narrow(int processId)
+ {
+ return this.manager.TryNarrow(new NamedPipeMessages.ConeManagement.NarrowParameters(processId.ToString()));
+ }
+
+ private MockTracer.RecordedEvent LastEvent(string name)
+ {
+ return this.tracer.SnapshotRelatedEvents().Last(recorded => recorded.Name == name);
+ }
+
+ private sealed class TestFileSystem : MockFileSystem
+ {
+ public TestFileSystem()
+ : base(CreateRoot())
+ {
+ }
+
+ public string FailRenameTo { get; set; }
+
+ public override void MoveAndOverwriteFile(string sourcePath, string destinationPath)
+ {
+ if (string.Equals(destinationPath, this.FailRenameTo, StringComparison.OrdinalIgnoreCase))
+ {
+ throw new IOException("Injected rename failure");
+ }
+
+ base.MoveAndOverwriteFile(sourcePath, destinationPath);
+ }
+
+ private static MockDirectory CreateRoot()
+ {
+ MockDirectory info = new MockDirectory(InfoDir, folders: null, files: null);
+ MockDirectory git = new MockDirectory(GitDir, new[] { info }, files: null);
+ return new MockDirectory(RepoRoot, new[] { git }, files: null);
+ }
+ }
+
+ private sealed class MockEnvironment : IConeManagerEnvironment
+ {
+ private readonly MockFileSystem fileSystem;
+ private int lockHeld;
+
+ public MockEnvironment(MockFileSystem fileSystem)
+ {
+ this.fileSystem = fileSystem;
+ }
+
+ public List ModifiedPaths { get; } = new List { ".gitattributes" };
+
+ public Dictionary RunningProcesses { get; } = new Dictionary();
+
+ public List ConeFilesAtApply { get; } = new List();
+
+ public List SparseDirectories { get; } = new List();
+
+ public HashSet DeletedFiles { get; } = new HashSet();
+
+ public bool SparseDirectoriesFail { get; set; }
+
+ public Dictionary StartTimeResults { get; } = new Dictionary();
+
+ public bool IndexWriteAllowed { get; set; } = true;
+
+ public int? LockHolder { get; set; }
+
+ public int CanWriteIndexDelayMs { get; set; }
+
+ public bool ConeFileLocked { get; set; }
+
+ public int ApplyExitCode { get; set; }
+
+ public Exception ApplyException { get; set; }
+
+ public Action DuringApply { get; set; }
+
+ public Action DuringListSparseDirectories { get; set; }
+
+ public int LockCount { get; private set; }
+
+ public bool IsConeFileLockHeld => this.lockHeld != 0;
+
+ public IEnumerable GetModifiedPaths()
+ {
+ return this.ModifiedPaths.ToList();
+ }
+
+ public bool CanWriteIndex(int processId)
+ {
+ if (this.CanWriteIndexDelayMs > 0)
+ {
+ Thread.Sleep(this.CanWriteIndexDelayMs);
+ }
+
+ return this.IndexWriteAllowed && (this.LockHolder == null || this.LockHolder == processId);
+ }
+
+ public bool TryGetSparseDirectories(out IReadOnlyList sparseDirectories, out string error)
+ {
+ this.DuringListSparseDirectories?.Invoke();
+ if (this.SparseDirectoriesFail)
+ {
+ sparseDirectories = null;
+ error = "fatal: injected failure";
+ return false;
+ }
+
+ sparseDirectories = this.SparseDirectories.ToList();
+ error = null;
+ return true;
+ }
+
+ public bool IsFileInWorkingDirectory(string gitPath)
+ {
+ return !this.DeletedFiles.Contains(gitPath);
+ }
+
+ public bool TryLockConeFile(out IDisposable coneFileLock, out Exception error)
+ {
+ if (this.ConeFileLocked)
+ {
+ coneFileLock = null;
+ error = new IOException("sparse-checkout.lock: File exists");
+ return false;
+ }
+
+ // The manager must serialize requests, so the lock is never held twice.
+ Interlocked.Exchange(ref this.lockHeld, 1).ShouldEqual(0, "The cone file lock is already held");
+ this.LockCount++;
+ coneFileLock = new Releaser(() => Interlocked.Exchange(ref this.lockHeld, 0));
+ error = null;
+ return true;
+ }
+
+ public GitProcess.Result ApplyConeToIndex()
+ {
+ this.ConeFilesAtApply.Add(this.fileSystem.ReadAllText(SparseCheckoutPath));
+ this.DuringApply?.Invoke();
+ if (this.ApplyException != null)
+ {
+ throw this.ApplyException;
+ }
+
+ return new GitProcess.Result(string.Empty, this.ApplyExitCode == 0 ? string.Empty : "fatal: Unable to write new index file", this.ApplyExitCode);
+ }
+
+ public ProcessStartTimeResult TryGetProcessStartTime(int processId, out long startTime)
+ {
+ lock (this.RunningProcesses)
+ {
+ if (this.StartTimeResults.TryGetValue(processId, out ProcessStartTimeResult result))
+ {
+ startTime = 0;
+ return result;
+ }
+
+ if (this.RunningProcesses.TryGetValue(processId, out startTime))
+ {
+ return ProcessStartTimeResult.Success;
+ }
+ }
+
+ return ProcessStartTimeResult.ProcessNotFound;
+ }
+
+ private sealed class Releaser : IDisposable
+ {
+ private readonly Action release;
+
+ public Releaser(Action release)
+ {
+ this.release = release;
+ }
+
+ public void Dispose()
+ {
+ this.release();
+ }
+ }
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/SparseDirectoryExpansionGuardTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/SparseDirectoryExpansionGuardTests.cs
new file mode 100644
index 000000000..ae92d28d9
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Common/Sparse/SparseDirectoryExpansionGuardTests.cs
@@ -0,0 +1,51 @@
+using GVFS.Common.Sparse;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System.Collections.Generic;
+
+namespace GVFS.UnitTests.Common.Sparse
+{
+ [TestFixture]
+ public class SparseDirectoryExpansionGuardTests
+ {
+ [TestCase("A/B/f.txt", "A/", true)]
+ [TestCase("A/f.txt", "A/", true)]
+ [TestCase("A/", "A/", true)]
+ [TestCase("B/f.txt", "A/", false)]
+ [TestCase("AB/f.txt", "A/", false)]
+ [TestCase("f.txt", "A/", false)]
+ [TestCase("A/", "A/B/", true)]
+ [TestCase("A/f.txt", "A/B/", false)]
+ [TestCase("a/b/f.txt", "A/", true)]
+ public void FindHiddenModifiedPathsFindsPathsInsideOrAroundASparseDirectory(string modifiedPath, string sparseDirectory, bool hidden)
+ {
+ List result = SparseDirectoryExpansionGuard.FindHiddenModifiedPaths(new[] { modifiedPath }, new[] { sparseDirectory }, ignoreCase: true);
+
+ (result.Count == 1).ShouldEqual(hidden);
+ }
+
+ [TestCase]
+ public void FindHiddenModifiedPathsUsesTheCaseRule()
+ {
+ SparseDirectoryExpansionGuard.FindHiddenModifiedPaths(new[] { "a/f.txt" }, new[] { "A/" }, ignoreCase: false).ShouldBeEmpty();
+ }
+
+ [TestCase("A/B/b.txt", "A/B/deleted.txt", true)]
+ [TestCase("A/B/", "A/B/C/deleted.txt", true)]
+ [TestCase("A/B/b.txt", "A/X/deleted.txt", false)]
+ [TestCase("A/B/b.txt", "A/deleted.txt", true)]
+ [TestCase("A/b.txt", "A/B/", false)]
+ [TestCase("A/B/C/c.txt", "A/B/", true)]
+ [TestCase("A/", "A/B/", true)]
+ [TestCase("C/c.txt", "A/B/deleted.txt", false)]
+ public void FindReachedPathReturnsAPathWhoseDirectoryTheConeIncludes(string conePath, string unsafePath, bool reached)
+ {
+ ConePatternSet cone = ConeBuilder.BuildFromModifiedPaths(new[] { conePath }, ignoreCase: false);
+
+ string result = SparseDirectoryExpansionGuard.FindReachedPath(cone, new[] { unsafePath }, ignoreCase: false);
+
+ (result == unsafePath).ShouldEqual(reached);
+ (result == null).ShouldEqual(!reached);
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/SparseIndexGitSupportGuardTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/SparseIndexGitSupportGuardTests.cs
new file mode 100644
index 000000000..12568e352
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Common/Sparse/SparseIndexGitSupportGuardTests.cs
@@ -0,0 +1,90 @@
+using GVFS.Common.Sparse;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System;
+
+namespace GVFS.UnitTests.Common.Sparse
+{
+ [TestFixture]
+ public class SparseIndexGitSupportGuardTests
+ {
+ private const string ConeFile = "/*\n!/*/\n/A/\n";
+ private const string SparseCheckoutPath = @"C:\repo\src\.git\info\sparse-checkout";
+
+ [TestCase]
+ public void NoSettingAndNoFileIsNotATrigger()
+ {
+ SparseIndexGitSupportGuard.GetTriggers(autoSparseIndex: false, coneFileStart: null)
+ .ShouldEqual(SparseIndexGitSupportGuard.Triggers.None);
+ }
+
+ [TestCase]
+ public void AutoSparseIndexIsATrigger()
+ {
+ SparseIndexGitSupportGuard.GetTriggers(autoSparseIndex: true, coneFileStart: null)
+ .ShouldEqual(SparseIndexGitSupportGuard.Triggers.AutoSparseIndex);
+ }
+
+
+
+ [TestCase(ConeFile)]
+ [TestCase("/*\r\n!/*/\r\n")]
+ [TestCase("/*\n!/*/")]
+ public void ConeFileIsATrigger(string content)
+ {
+ SparseIndexGitSupportGuard.GetTriggers(autoSparseIndex: false, coneFileStart: content)
+ .ShouldEqual(SparseIndexGitSupportGuard.Triggers.ConeFile);
+ }
+
+ [TestCase("/.gitattributes\r\n")]
+ [TestCase("")]
+ [TestCase("/*\n")]
+ [TestCase("!/*/\n/*\n")]
+ public void LegacyOrEmptySparseCheckoutFileIsNotATrigger(string content)
+ {
+ // Versions of VFS for Git before 2018 wrote "/.gitattributes" to this file.
+ SparseIndexGitSupportGuard.GetTriggers(autoSparseIndex: false, coneFileStart: content)
+ .ShouldEqual(SparseIndexGitSupportGuard.Triggers.None);
+ }
+
+ [TestCase]
+ public void AllTriggersAreReported()
+ {
+ SparseIndexGitSupportGuard.Triggers triggers = SparseIndexGitSupportGuard.GetTriggers(autoSparseIndex: true, coneFileStart: ConeFile);
+
+ triggers.ShouldEqual(
+ SparseIndexGitSupportGuard.Triggers.AutoSparseIndex |
+ SparseIndexGitSupportGuard.Triggers.ConeFile);
+ string message = SparseIndexGitSupportGuard.GetRefusalMessage(triggers, @"C:\Program Files\Git\cmd\git.exe", "2.56.1.vfs.0.1", SparseCheckoutPath);
+ message.ShouldContain(
+ "gvfs.auto-sparse-index is true",
+ $"'{SparseCheckoutPath}' is a cone-mode sparse-checkout file");
+ }
+
+ [TestCase]
+ public void RefusalMessageNamesTheGitAndTheRecoverySteps()
+ {
+ string message = SparseIndexGitSupportGuard.GetRefusalMessage(
+ SparseIndexGitSupportGuard.Triggers.ConeFile,
+ @"C:\Program Files\Git\cmd\git.exe",
+ "2.56.1.vfs.0.1",
+ SparseCheckoutPath);
+
+ message.ShouldContain(
+ @"'C:\Program Files\Git\cmd\git.exe', version 2.56.1.vfs.0.1",
+ "'feature: vfs-sparse-index'",
+ "git -c core.hookspath= config --unset-all gvfs.auto-sparse-index",
+ "git -c core.hookspath= config --unset-all index.sparse",
+ "git -c core.hookspath= config core.sparseCheckout false",
+ $"del \"{SparseCheckoutPath}\"",
+ "gvfs mount");
+ message.ShouldNotContain(ignoreCase: false, "gvfs.auto-sparse-index is true");
+ }
+
+ [TestCase]
+ public void RefusalMessageNeedsATrigger()
+ {
+ Assert.Throws(() => SparseIndexGitSupportGuard.GetRefusalMessage(SparseIndexGitSupportGuard.Triggers.None, "git", "1", SparseCheckoutPath));
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/TransientConeStateTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/TransientConeStateTests.cs
new file mode 100644
index 000000000..0d4006d9e
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Common/Sparse/TransientConeStateTests.cs
@@ -0,0 +1,93 @@
+using GVFS.Common.Sparse;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace GVFS.UnitTests.Common.Sparse
+{
+ [TestFixture]
+ public class TransientConeStateTests
+ {
+ [TestCase]
+ public void PathsOfAllCommandsAreKeptUntilEachCommandIsRemoved()
+ {
+ TransientConeState state = new TransientConeState();
+ state.Add(100, startTime: 1, new[] { "A/a.txt", "B/" });
+ state.Add(200, startTime: 2, new[] { "A/a.txt", "C/c.txt" });
+
+ Sorted(state.GetAllPaths()).ShouldMatchInOrder("A/a.txt", "B/", "C/c.txt");
+
+ state.Remove(100, startTime: 1).ShouldBeTrue();
+ Sorted(state.GetAllPaths()).ShouldMatchInOrder("A/a.txt", "C/c.txt");
+
+ state.Remove(200, startTime: 2).ShouldBeTrue();
+ state.GetAllPaths().ShouldBeEmpty();
+ state.CommandCount.ShouldEqual(0);
+ }
+
+ [TestCase]
+ public void RepeatedAddOfOneCommandKeepsThePathsOfBothRequests()
+ {
+ TransientConeState state = new TransientConeState();
+ state.Add(100, startTime: 1, new[] { "A/a.txt" });
+ state.Add(100, startTime: 1, new[] { "B/b.txt" });
+
+ Sorted(state.GetAllPaths()).ShouldMatchInOrder("A/a.txt", "B/b.txt");
+ state.CommandCount.ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void AddForAReusedProcessIdReplacesThePathsOfTheEndedProcess()
+ {
+ TransientConeState state = new TransientConeState();
+ state.Add(100, startTime: 1, new[] { "A/a.txt" });
+ state.Add(100, startTime: 2, new[] { "B/b.txt" });
+
+ state.GetAllPaths().ShouldMatchInOrder("B/b.txt");
+ }
+
+ [TestCase]
+ public void RemoveOfACommandWithoutPathsRecordsItAsNarrowed()
+ {
+ TransientConeState state = new TransientConeState();
+
+ state.Remove(100, startTime: 1).ShouldBeFalse();
+
+ state.IsNarrowed(100, startTime: 1).ShouldBeTrue();
+ state.IsNarrowed(100, startTime: null).ShouldBeTrue();
+ state.IsNarrowed(100, startTime: 2).ShouldBeFalse("Another process has this id");
+ state.IsNarrowed(200, startTime: 1).ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void RemoveWithoutAStartTimeRecordsNoNarrowedCommand()
+ {
+ TransientConeState state = new TransientConeState();
+
+ state.Remove(100, startTime: null).ShouldBeFalse();
+
+ state.IsNarrowed(100, startTime: 1).ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void RemoveEndedRemovesThePathsAndNarrowedRecordsOfEndedProcesses()
+ {
+ TransientConeState state = new TransientConeState();
+ state.Add(100, startTime: 1, new[] { "A/a.txt" });
+ state.Add(200, startTime: 2, new[] { "B/b.txt" });
+ state.Remove(300, startTime: 3);
+ HashSet running = new HashSet { 200 };
+
+ state.RemoveEnded((processId, startTime) => running.Contains(processId)).ShouldEqual(1);
+
+ state.GetAllPaths().ShouldMatchInOrder("B/b.txt");
+ state.IsNarrowed(300, startTime: 3).ShouldBeFalse();
+ }
+
+ private static IEnumerable Sorted(IEnumerable paths)
+ {
+ return paths.OrderBy(path => path, System.StringComparer.Ordinal);
+ }
+ }
+}
diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs
index f469a24b9..74a0fc287 100644
--- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs
+++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs
@@ -405,6 +405,12 @@ public virtual int GetProjectedFolderCount()
}
}
+ ///
+ /// True when gvfs.auto-sparse-index was true when the projection was created, so
+ /// the projection expands the sparse-directory entries of a sparse index.
+ ///
+ public bool IsSparseIndexSupportEnabled => this.sparseDirectoryExpander != null;
+
///
/// Get the number of files in the projection, if the projection expanded the
/// sparse-directory entries of a sparse index. A sparse index has one entry for each