diff --git a/GVFS/GVFS.Common/FileSystem/PhysicalFileSystem.cs b/GVFS/GVFS.Common/FileSystem/PhysicalFileSystem.cs
index b1f7bd97ac..7002ea5790 100644
--- a/GVFS/GVFS.Common/FileSystem/PhysicalFileSystem.cs
+++ b/GVFS/GVFS.Common/FileSystem/PhysicalFileSystem.cs
@@ -174,6 +174,15 @@ public virtual void FlushFileBuffers(string path)
GVFSPlatform.Instance.FileSystem.FlushFileBuffers(path);
}
+ ///
+ /// Return true when names the file that
+ /// has open, and no delete of that file is pending. Return false when this is not known.
+ ///
+ public virtual bool IsOpenFileAtPath(Stream stream, string path)
+ {
+ return stream is FileStream fileStream && NativeMethods.IsOpenFileAtPath(fileStream.SafeFileHandle, path);
+ }
+
public virtual void CreateDirectory(string path)
{
Directory.CreateDirectory(path);
diff --git a/GVFS/GVFS.Common/Git/GitProcess.cs b/GVFS/GVFS.Common/Git/GitProcess.cs
index edcbd728b6..76259c0720 100644
--- a/GVFS/GVFS.Common/Git/GitProcess.cs
+++ b/GVFS/GVFS.Common/Git/GitProcess.cs
@@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
+using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
@@ -962,6 +963,203 @@ internal static bool HasBuildOption(string buildOptionsOutput, string option)
}
///
+ /// Read the blob of each path in the index (stage 0) with git ls-files --sparse -s
+ /// and in HEAD with git ls-tree -l. Add each path that has the same regular-file
+ /// blob in both to , and each path that the index does not
+ /// have to .
+ ///
+ ///
+ /// Neither command writes the index. --sparse stops ls-files from expanding
+ /// a sparse index. --literal-pathspecs makes Git match each path exactly. The
+ /// commands need no skip-worktree bits, so the virtual file system is off, and Git does
+ /// not run its hook. sparse.expectFilesOutsideOfPatterns stops Git from looking
+ /// for projected files outside the cone. The paths
+ /// go on the command line, in several commands when they are too long for one, so Git
+ /// does not read standard input and the output streams while Git runs. The read-object
+ /// hook stays on, because the HEAD tree can be not local yet. COMMAND_HOOK_LOCK
+ /// makes Git skip the pre-command and post-command hooks.
+ ///
+ /// The time that all the commands together can take.
+ public Result GetBlobsThatMatchHead(IReadOnlyList gitPaths, StringComparer pathComparer, IDictionary matchingBlobs, ICollection notInIndex, int timeoutMs)
+ {
+ ArgumentNullException.ThrowIfNull(gitPaths);
+ ArgumentNullException.ThrowIfNull(pathComparer);
+ ArgumentNullException.ThrowIfNull(matchingBlobs);
+ ArgumentNullException.ThrowIfNull(notInIndex);
+
+ Dictionary indexBlobs = new Dictionary(pathComparer);
+ Dictionary headBlobs = new Dictionary(pathComparer);
+ Result result = new Result(string.Empty, string.Empty, Result.SuccessCode);
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ Result timedOut = new Result(string.Empty, "The blob lookup took longer than " + timeoutMs + " ms", Result.GenericFailureCode);
+ foreach (string pathspecs in GetPathspecArguments(gitPaths))
+ {
+ int remainingMs = timeoutMs - (int)stopwatch.ElapsedMilliseconds;
+ if (remainingMs <= 0)
+ {
+ return timedOut;
+ }
+
+ result = this.InvokeGitImpl(
+ "-c core.virtualfilesystem= -c sparse.expectFilesOutsideOfPatterns=true --literal-pathspecs ls-files --sparse -s -z -- " + pathspecs,
+ workingDirectory: this.workingDirectoryRoot,
+ dotGitDirectory: null,
+ useReadObjectHook: false,
+ writeStdIn: null,
+ parseStdOutLine: null,
+ timeoutMs: remainingMs,
+ usePreCommandHook: false,
+ parseStdOutToken: record =>
+ {
+ if (TryParseLsFilesStageRecord(record, out string path, out string sha))
+ {
+ indexBlobs[path] = sha;
+ }
+ });
+ if (result.ExitCodeIsFailure)
+ {
+ return result;
+ }
+
+ remainingMs = timeoutMs - (int)stopwatch.ElapsedMilliseconds;
+ if (remainingMs <= 0)
+ {
+ return timedOut;
+ }
+
+ result = this.InvokeGitImpl(
+ "-c core.virtualfilesystem= -c sparse.expectFilesOutsideOfPatterns=true --literal-pathspecs ls-tree -l -z HEAD -- " + pathspecs,
+ workingDirectory: this.workingDirectoryRoot,
+ dotGitDirectory: null,
+ useReadObjectHook: true,
+ writeStdIn: null,
+ parseStdOutLine: null,
+ timeoutMs: remainingMs,
+ usePreCommandHook: false,
+ parseStdOutToken: record =>
+ {
+ if (TryParseLsTreeLongRecord(record, out string path, out HeadBlob blob))
+ {
+ headBlobs[path] = blob;
+ }
+ });
+ if (result.ExitCodeIsFailure)
+ {
+ return result;
+ }
+ }
+
+ foreach (string path in gitPaths)
+ {
+ if (!indexBlobs.TryGetValue(path, out string indexSha))
+ {
+ notInIndex.Add(path);
+ }
+ else if (headBlobs.TryGetValue(path, out HeadBlob headBlob) &&
+ string.Equals(indexSha, headBlob.Sha, StringComparison.Ordinal))
+ {
+ matchingBlobs[path] = headBlob;
+ }
+ }
+
+ return result;
+ }
+
+ ///
+ /// Quote the paths for a command line, and split them into groups that fit in one command.
+ ///
+ internal static IEnumerable GetPathspecArguments(IReadOnlyList gitPaths, int maxLength = 24000)
+ {
+ StringBuilder arguments = new StringBuilder();
+ foreach (string path in gitPaths)
+ {
+ string quoted = QuoteGitPath(path);
+ if (arguments.Length > 0 && arguments.Length + quoted.Length + 1 > maxLength)
+ {
+ yield return arguments.ToString();
+ arguments.Clear();
+ }
+
+ if (arguments.Length > 0)
+ {
+ arguments.Append(' ');
+ }
+
+ arguments.Append(quoted);
+ }
+
+ if (arguments.Length > 0)
+ {
+ yield return arguments.ToString();
+ }
+ }
+
+ ///
+ /// Parse a git ls-files -s -z record of a regular file at stage 0:
+ /// "<mode> <oid> 0\t<path>". Return false for any other record, for
+ /// example a sparse-directory entry, a symbolic link, or a conflict stage.
+ ///
+ internal static bool TryParseLsFilesStageRecord(string record, out string path, out string sha)
+ {
+ path = null;
+ sha = null;
+ int tab = record?.IndexOf('\t') ?? -1;
+ if (tab <= 0 || tab == record.Length - 1)
+ {
+ return false;
+ }
+
+ string[] fields = record.Substring(0, tab).Split(' ');
+ if (fields.Length != 3 || !IsRegularFileMode(fields[0]) || !IsSha(fields[1]) || fields[2] != "0")
+ {
+ return false;
+ }
+
+ path = record.Substring(tab + 1);
+ sha = fields[1].ToLowerInvariant();
+ return true;
+ }
+
+ ///
+ /// Parse a git ls-tree -l -z record of a regular file:
+ /// "<mode> blob <oid> <size>\t<path>" (Git pads the size with spaces).
+ /// Return false for any other record.
+ ///
+ internal static bool TryParseLsTreeLongRecord(string record, out string path, out HeadBlob blob)
+ {
+ path = null;
+ blob = default;
+ int tab = record?.IndexOf('\t') ?? -1;
+ if (tab <= 0 || tab == record.Length - 1)
+ {
+ return false;
+ }
+
+ string[] fields = record.Substring(0, tab).Split(' ', StringSplitOptions.RemoveEmptyEntries);
+ if (fields.Length != 4 ||
+ !IsRegularFileMode(fields[0]) ||
+ fields[1] != "blob" ||
+ !IsSha(fields[2]) ||
+ !long.TryParse(fields[3], NumberStyles.None, CultureInfo.InvariantCulture, out long size))
+ {
+ return false;
+ }
+
+ path = record.Substring(tab + 1);
+ blob = new HeadBlob(fields[2].ToLowerInvariant(), size);
+ return true;
+ }
+
+ private static bool IsRegularFileMode(string mode)
+ {
+ return mode == "100644" || mode == "100755";
+ }
+
+ private static bool IsSha(string value)
+ {
+ return value.Length == GVFSConstants.ShaStringLength && SHA1Util.IsValidShaFormat(value);
+ }
+
/// Return the path of a git status --porcelain=v2 -z record for a changed,
/// unmerged, or untracked entry, or null for any other record. The path of an untracked
/// folder ends with '/'.
diff --git a/GVFS/GVFS.Common/Git/HeadBlob.cs b/GVFS/GVFS.Common/Git/HeadBlob.cs
new file mode 100644
index 0000000000..cb14c0bd60
--- /dev/null
+++ b/GVFS/GVFS.Common/Git/HeadBlob.cs
@@ -0,0 +1,7 @@
+namespace GVFS.Common.Git
+{
+ /// A blob that the index and HEAD both have for a path.
+ /// The object id of the blob.
+ /// The size of the blob in bytes.
+ public readonly record struct HeadBlob(string Sha, long Size);
+}
diff --git a/GVFS/GVFS.Common/NativeMethods.cs b/GVFS/GVFS.Common/NativeMethods.cs
index 1fae6876df..8c5e03ad9a 100644
--- a/GVFS/GVFS.Common/NativeMethods.cs
+++ b/GVFS/GVFS.Common/NativeMethods.cs
@@ -20,6 +20,10 @@ public static partial class NativeMethods
private const int ERROR_FILE_NOT_FOUND = 0x2;
private const int ERROR_PATH_NOT_FOUND = 0x3;
+ // FILE_INFO_BY_HANDLE_CLASS values.
+ private const int FileStandardInfoClass = 1;
+ private const int FileIdInfoClass = 18;
+
[Flags]
public enum MoveFileFlags : uint
{
@@ -202,6 +206,55 @@ public static DateTime GetLastRebootTime()
return DateTime.Now - uptime;
}
+ ///
+ /// Return true when names the file that
+ /// refers to, and no delete of that file is pending. Return false when this is not known.
+ ///
+ public static bool IsOpenFileAtPath(SafeFileHandle openHandle, string path)
+ {
+ if (!GetFileInformationByHandleEx(openHandle, FileStandardInfoClass, out FileStandardInfo standardInfo, (uint)Marshal.SizeOf()) ||
+ standardInfo.DeletePending != 0 ||
+ !GetFileInformationByHandleEx(openHandle, FileIdInfoClass, out FileIdInfo openId, (uint)Marshal.SizeOf()))
+ {
+ return false;
+ }
+
+ // The prefix allows a path longer than MAX_PATH. FILE_FLAG_OPEN_REPARSE_POINT: a link
+ // at the path is not the file that it points to.
+ using (SafeFileHandle pathHandle = CreateFile(
+ ToExtendedLengthPath(path),
+ FileAccess.FILE_READ_ATTRIBUTES,
+ FileShare.ReadWrite | FileShare.Delete,
+ IntPtr.Zero,
+ FileMode.Open,
+ FileAttributes.FILE_FLAG_OPEN_REPARSE_POINT,
+ IntPtr.Zero))
+ {
+ if (pathHandle.IsInvalid ||
+ !GetFileInformationByHandleEx(pathHandle, FileIdInfoClass, out FileIdInfo pathId, (uint)Marshal.SizeOf()))
+ {
+ return false;
+ }
+
+ return openId.VolumeSerialNumber == pathId.VolumeSerialNumber &&
+ openId.FileIdLow == pathId.FileIdLow &&
+ openId.FileIdHigh == pathId.FileIdHigh;
+ }
+ }
+
+ private static string ToExtendedLengthPath(string path)
+ {
+ string fullPath = Path.GetFullPath(path);
+ if (fullPath.StartsWith(@"\\?\", StringComparison.Ordinal))
+ {
+ return fullPath;
+ }
+
+ return fullPath.StartsWith(@"\\", StringComparison.Ordinal)
+ ? @"\\?\UNC\" + fullPath.Substring(2)
+ : @"\\?\" + fullPath;
+ }
+
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool MoveFileEx(
string existingFileName,
@@ -211,6 +264,14 @@ private static extern bool MoveFileEx(
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FlushFileBuffers(SafeFileHandle hFile);
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool GetFileInformationByHandleEx(SafeFileHandle hFile, int fileInformationClass, out FileStandardInfo fileInformation, uint bufferSize);
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ private static extern bool GetFileInformationByHandleEx(SafeFileHandle hFile, int fileInformationClass, out FileIdInfo fileInformation, uint bufferSize);
+
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool GetVolumeInformation(
string rootPathName,
@@ -336,5 +397,23 @@ private struct OSVersionInfo
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string CSDVersion;
}
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct FileStandardInfo
+ {
+ public long AllocationSize;
+ public long EndOfFile;
+ public uint NumberOfLinks;
+ public byte DeletePending;
+ public byte Directory;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ private struct FileIdInfo
+ {
+ public ulong VolumeSerialNumber;
+ public ulong FileIdLow;
+ public ulong FileIdHigh;
+ }
}
}
diff --git a/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs
index 8ddf4452b8..a9efb0c56c 100644
--- a/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs
+++ b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs
@@ -45,7 +45,7 @@ namespace GVFS.Common.Sparse
/// 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.
+ /// does not change. Only a dehydrate (see below) can make the manager invalidate it.
///
///
/// Every failure lets Git run, because the hook treats any reply other than success as
@@ -54,7 +54,8 @@ namespace GVFS.Common.Sparse
///
/// Working-tree changes: Git sees a change to a file only when the index has an entry for
/// it, and git add takes a path only when the cone includes it. The file system
- /// callbacks report every created, written, renamed, or deleted path (see
+ /// callbacks report every created, written, renamed, or deleted path, and the unstage
+ /// preparation reports every staged file that it adds to the modified paths (see
/// ). When the applied cone does not include the
/// path, the manager creates the pending file (see
/// ). The callback does not
@@ -73,6 +74,31 @@ namespace GVFS.Common.Sparse
/// path, because the virtual file system hook clears its skip-worktree bit, so the index
/// keeps its entry. The next change to the file makes it a candidate again.
///
+ ///
+ /// Dehydrate clean files: a clean file stays a modified path until the next apply. The check
+ /// also reads the blob of each clean file in the index and in HEAD, and records it with the
+ /// repository stamp (see ). Then it
+ /// makes a cone change pending, so the next Git command that holds the GVFS lock sends an
+ /// apply. The apply uses a recorded blob only while the stamp is the same, so the index
+ /// entry and HEAD still name that blob. A file whose blob is not valid any more waits for
+ /// the check after that Git command. The apply (not a widen, which is on the path of the Git command) returns each clean
+ /// file to a placeholder and removes it from the modified
+ /// paths (see ), and then runs Git
+ /// even when the cone file does not change. Git then sets the skip-worktree bit of the file,
+ /// because the hook no longer reports it, and collapses its directory when the cone does not
+ /// include it. A modified path cannot only be removed: a later in-place or memory-mapped
+ /// write to a full file that is not a modified path does not make it a modified path again,
+ /// so Git would not see the write. A placeholder becomes a modified path at its first write,
+ /// also before the projection has the file again. The apply does this only for a file whose index entry and HEAD have the same blob, and
+ /// whose bytes on disk are exactly that blob, because the conversion discards the bytes on
+ /// disk. It does nothing while a merge, rebase, cherry-pick, or revert is in progress, or
+ /// while gvfs dehydrate works on folders. If Git fails, the files become modified
+ /// paths again: they are placeholders with the content of HEAD, so nothing is lost. A file
+ /// that fails for a reason that can pass, for example an open handle, waits before the next
+ /// attempt (see ). The lookup and the conversions
+ /// stop early when the request approaches the wait of the hook. The lookup runs in the check,
+ /// so no Git command waits for it.
+ ///
///
public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver
{
@@ -92,6 +118,41 @@ public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver
///
public const int DefaultChangeCheckDelayMs = 2000;
+ /// One apply attempts at most this many clean files.
+ public const int MaxDehydrateFiles = 128;
+
+ /// One background check reads the blobs of at most this many clean files.
+ public const int MaxDehydrateLookupFiles = 4 * MaxDehydrateFiles;
+
+ ///
+ /// A clean file that is larger than this stays a modified path, so that one apply does
+ /// not read a very large file while the Git command waits.
+ ///
+ public const long MaxDehydrateFileSize = 64L * 1024 * 1024;
+
+ ///
+ /// After this long, an apply stops returning clean files to placeholders, and the next
+ /// apply continues. Each apply that starts the conversions attempts at least one file, so
+ /// the applies make progress. The Git command waits for the apply in its hook.
+ ///
+ internal const int DehydrateTimeBudgetMs = 250;
+
+ ///
+ /// After a clean file did not return to a placeholder for a reason that can pass, for
+ /// example a process had it open, the next attempt for the file waits this long. Each
+ /// further failure doubles the wait, up to .
+ ///
+ public const int DefaultDehydrateRetryDelayMs = 5000;
+
+ internal const int MaxDehydrateRetryDelayMs = 5 * 60 * 1000;
+
+ // The background check reads the blobs, and no Git command waits for it.
+ internal const int DehydrateLookupTimeoutMs = 60 * 1000;
+
+ // The conversions stop after this part of the wait of the hook. Git then still has time
+ // to write the index.
+ internal const int DehydrateRequestBudgetMs = NamedPipeMessages.ConeManagement.ApplyWaitBudgetMs / 2;
+
private const string WidenEventName = "ConeWiden";
private const string NarrowEventName = "ConeNarrow";
private const string ApplyEventName = "ConeApply";
@@ -123,6 +184,8 @@ public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver
private readonly StringComparer pathComparer;
private readonly int changeCheckDelayMs;
private readonly Timer changeCheckTimer;
+ private readonly int dehydrateRetryDelayMs;
+ private readonly Timer dehydrateRetryTimer;
// The working-tree paths that changed since an apply or a check last used them.
private readonly ConcurrentDictionary changedPaths;
@@ -149,6 +212,27 @@ public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver
// ConsumeChanges). The cone includes them. Guarded by coneLock.
private HashSet unconfirmedPaths;
+ // Clean files that an apply did not return to placeholders, and that an apply does not
+ // try again until they change: for example, the bytes on disk differ from the blob.
+ // Guarded by coneLock.
+ private HashSet notDehydratablePaths;
+
+ // Clean files that an apply did not return to placeholders for a reason that can pass,
+ // with the time of the next attempt. Guarded by coneLock.
+ private Dictionary dehydrateRetries;
+
+ // The blobs that a background check read for clean files, with the repository stamp at
+ // that time. An apply uses a blob only while the stamp is the same. Guarded by coneLock.
+ private Dictionary recordedBlobs;
+
+ // True when a deferred file is due and has no blob for the current stamp, so the next
+ // check must run even when nothing else changed. Guarded by coneLock.
+ private bool dehydrateLookupRequested;
+
+ // True when the last apply did not return clean files to placeholders because of a
+ // merge, rebase, or another blocker. Guarded by coneLock.
+ private bool dehydrateBlocked;
+
// The directories that the cone file includes and the index expands, or null when that
// is not known.
private AppliedConeSnapshot appliedCone;
@@ -174,7 +258,8 @@ public AutoSparseIndexConeManager(
string sparseCheckoutPath,
bool ignoreCase,
IConeManagerEnvironment environment,
- int changeCheckDelayMs = DefaultChangeCheckDelayMs)
+ int changeCheckDelayMs = DefaultChangeCheckDelayMs,
+ int dehydrateRetryDelayMs = DefaultDehydrateRetryDelayMs)
{
ArgumentNullException.ThrowIfNull(tracer);
ArgumentNullException.ThrowIfNull(fileSystem);
@@ -191,8 +276,13 @@ public AutoSparseIndexConeManager(
this.changedPaths = new ConcurrentDictionary(this.pathComparer);
this.cleanPaths = new HashSet(this.pathComparer);
this.unconfirmedPaths = new HashSet(this.pathComparer);
+ this.notDehydratablePaths = new HashSet(this.pathComparer);
+ this.dehydrateRetries = new Dictionary(this.pathComparer);
+ this.recordedBlobs = new Dictionary(this.pathComparer);
this.changeCheckDelayMs = changeCheckDelayMs;
this.changeCheckTimer = new Timer(_ => this.ScheduleReconcile(), state: null, Timeout.Infinite, Timeout.Infinite);
+ this.dehydrateRetryDelayMs = dehydrateRetryDelayMs;
+ this.dehydrateRetryTimer = new Timer(_ => this.OnDehydrateRetryDue(), state: null, Timeout.Infinite, Timeout.Infinite);
}
private enum ConeChange
@@ -331,7 +421,7 @@ public bool TryApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters
ApplyAttempt attempt = new ApplyAttempt();
ConeChange change = this.RunAndCatch(
() => TryGetProcessId(parameters.CommandId, out int processId)
- ? this.ApplyCone(processId, NoPaths, NamedPipeMessages.ConeManagement.ApplyWaitBudgetMs / 2, attempt, stopwatch, metadata)
+ ? this.ApplyCone(processId, NoPaths, NamedPipeMessages.ConeManagement.ApplyWaitBudgetMs / 2, attempt, stopwatch, metadata, dehydrateCleanFiles: true)
: ConeChange.NoCommandId,
metadata);
this.RearmPendingAfterAttempt(attempt, change, requestHasPaths: false, metadata);
@@ -355,6 +445,7 @@ public void Stop()
{
this.isStopped = true;
this.changeCheckTimer.Dispose();
+ this.dehydrateRetryTimer.Dispose();
}
///
@@ -414,10 +505,34 @@ public void OnGitCommandCompleted()
this.ScheduleReconcile();
}
+ ///
+ /// Make the next Git command that reads the index apply the cone, for example after
+ /// gvfs dehydrate removed modified paths. Its git reset can expand the
+ /// folders in the index, and a narrow does not collapse them.
+ ///
+ public void RequestApply()
+ {
+ if (this.isStopped)
+ {
+ return;
+ }
+
+ lock (this.coneLock)
+ {
+ // Another Git command wrote the index, so the apply must run Git even when the
+ // cone file does not change.
+ this.indexMayDifferFromCone = true;
+ }
+
+ this.SetPending();
+ }
+
///
/// Ask Git which paths differ from HEAD, and write a cone file without the modified files
/// that match HEAD. A clean file that differs again goes back into the cone. Git does not
- /// write the index, and the manager does not wait for the GVFS lock.
+ /// write the index, and the manager does not wait for the GVFS lock. When clean files can
+ /// return to placeholders, make a cone change pending, so that the next Git command sends
+ /// an apply that does it.
///
/// True when the check ran or was not needed.
public bool TryReconcile()
@@ -559,15 +674,16 @@ private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parame
metadata.Add("Paths", string.Join(";", parameters.Paths));
}
- return this.ApplyCone(processId, parameters.Paths, MaxQueueWaitBeforeApplyMs, attempt, stopwatch, metadata);
+ return this.ApplyCone(processId, parameters.Paths, MaxQueueWaitBeforeApplyMs, attempt, stopwatch, metadata, dehydrateCleanFiles: false);
}
///
/// Write the cone of the modified paths, the transient paths, and
/// , and apply it to the index for the Git process that
- /// holds the GVFS lock.
+ /// holds the GVFS lock. With , first return clean
+ /// files to placeholders (see ).
///
- private ConeChange ApplyCone(int processId, IReadOnlyList requestPaths, int maxQueueWaitMs, ApplyAttempt attempt, Stopwatch stopwatch, EventMetadata metadata)
+ private ConeChange ApplyCone(int processId, IReadOnlyList requestPaths, int maxQueueWaitMs, ApplyAttempt attempt, Stopwatch stopwatch, EventMetadata metadata, bool dehydrateCleanFiles)
{
// 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.
@@ -608,115 +724,157 @@ private ConeChange ApplyCone(int processId, IReadOnlyList requestPaths,
List modifiedPaths = new List(this.environment.GetModifiedPaths());
this.ConsumeChanges(consumedSequence, modifiedPaths, metadata);
- // A modified file that exists keeps its content when Git expands its directory.
- // A deleted file, or a modified folder, does not, unless Git changes only the
- // index. Only those need the list of sparse-directory entries, and only when the
- // applied cone does not already expand them. A clean path has no index entry that
- // differs from the working tree.
- AppliedConeSnapshot applied = Volatile.Read(ref this.appliedCone);
- List unsafePaths = new List();
- if (!this.environment.SparsityChangeIsIndexOnly)
+ List<(string Path, HeadBlob Blob)> dehydratedPaths = dehydrateCleanFiles
+ ? this.DehydrateCleanFiles(modifiedPaths, stopwatch, metadata)
+ : new List<(string Path, HeadBlob Blob)>();
+ if (dehydratedPaths.Count > 0)
{
- foreach (string path in modifiedPaths.Concat(this.unconfirmedPaths))
- {
- if ((IsFolderPath(path) || !this.environment.IsFileInWorkingDirectory(path)) &&
- !this.cleanPaths.Contains(path) &&
- (applied == null || !applied.IsCovered(path)))
- {
- unsafePaths.Add(path);
- }
- }
+ modifiedPaths = new List(this.environment.GetModifiedPaths());
}
- List hidden = new List();
- if (unsafePaths.Count > 0)
+ ConeChange change = ConeChange.UnexpectedException;
+ try
+ {
+ // Git must write the index even when the cone does not change, so that it
+ // sets the skip-worktree bit of each file that is no longer a modified path.
+ change = this.WriteAndApplyCone(processId, startTime, requestPaths, modifiedPaths, mustRunGit: dehydratedPaths.Count > 0, metadata);
+ }
+ finally
{
- Stopwatch listStopwatch = Stopwatch.StartNew();
- if (!this.environment.TryGetSparseDirectories(out IReadOnlyList sparseDirectories, out string sparseDirectoriesError))
+ if (dehydratedPaths.Count > 0)
{
- metadata.Add("SparseDirectoriesError", sparseDirectoriesError);
- return ConeChange.SparseDirectoriesUnknown;
+ this.FinishDehydrate(dehydratedPaths, indexWritten: change == ConeChange.Applied, metadata);
}
-
- metadata.Add("ListSparseDirectoriesMs", listStopwatch.ElapsedMilliseconds);
- hidden = SparseDirectoryExpansionGuard.FindHiddenModifiedPaths(unsafePaths, sparseDirectories, this.ignoreCase);
}
- HashSet hiddenSet = new HashSet(hidden, StringComparer.Ordinal);
- if (hidden.Count > 0)
+ if (change == ConeChange.Applied || change == ConeChange.ConeUnchanged)
{
- metadata.Add("HiddenModifiedPathCount", hidden.Count);
+ // Only an apply returns clean files to placeholders, and the next Git command
+ // sends one. When Git wrote the index, the blobs are not valid any more, and
+ // the check after this command reads them again.
+ this.SetPendingIfDehydrateIsReady(metadata);
}
- List conePaths = this.GetConePaths(modifiedPaths, hiddenSet);
- conePaths.AddRange(requestPaths);
- if (!this.TryBuildCone(conePaths, metadata, out ConePatternSet cone))
- {
- return ConeChange.InvalidPath;
- }
+ return change;
+ }
+ }
- string unsafePath = SparseDirectoryExpansionGuard.FindReachedPath(cone, hidden, this.ignoreCase);
- if (unsafePath != null)
+ ///
+ /// The part of after the changes are consumed: check the cone of
+ /// and , write it, and run
+ /// Git when the cone file or the index changes, or when .
+ /// The caller holds .
+ ///
+ private ConeChange WriteAndApplyCone(int processId, long startTime, IReadOnlyList requestPaths, List modifiedPaths, bool mustRunGit, EventMetadata metadata)
+ {
+ // A modified file that exists keeps its content when Git expands its directory.
+ // A deleted file, or a modified folder, does not, unless Git changes only the
+ // index. Only those need the list of sparse-directory entries, and only when the
+ // applied cone does not already expand them. A clean path has no index entry that
+ // differs from the working tree.
+ AppliedConeSnapshot applied = Volatile.Read(ref this.appliedCone);
+ List unsafePaths = new List();
+ if (!this.environment.SparsityChangeIsIndexOnly)
+ {
+ foreach (string path in modifiedPaths.Concat(this.unconfirmedPaths))
{
- metadata.Add("UnsafeModifiedPath", unsafePath);
- return ConeChange.ExpandsModifiedPath;
+ if ((IsFolderPath(path) || !this.environment.IsFileInWorkingDirectory(path)) &&
+ !this.cleanPaths.Contains(path) &&
+ (applied == null || !applied.IsCovered(path)))
+ {
+ unsafePaths.Add(path);
+ }
}
+ }
- if (!this.environment.TryLockConeFile(out IDisposable coneFileLock, out Exception lockError))
+ List hidden = new List();
+ if (unsafePaths.Count > 0)
+ {
+ Stopwatch listStopwatch = Stopwatch.StartNew();
+ if (!this.environment.TryGetSparseDirectories(out IReadOnlyList sparseDirectories, out string sparseDirectoriesError))
{
- metadata.Add("LockError", lockError?.ToString());
- return ConeChange.ConeFileLocked;
+ metadata.Add("SparseDirectoriesError", sparseDirectoriesError);
+ return ConeChange.SparseDirectoriesUnknown;
}
- 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;
- }
+ metadata.Add("ListSparseDirectoriesMs", listStopwatch.ElapsedMilliseconds);
+ hidden = SparseDirectoryExpansionGuard.FindHiddenModifiedPaths(unsafePaths, sparseDirectories, this.ignoreCase);
+ }
- this.hiddenModifiedPaths = hiddenSet;
- this.coneFileMayBeStale = false;
- if (writeResult == ConeFileWriteResult.Unchanged && !this.indexMayDifferFromCone)
- {
- this.AddTransientPaths(processId, startTime, requestPaths);
- this.PublishCone(cone);
- return ConeChange.ConeUnchanged;
- }
+ HashSet hiddenSet = new HashSet(hidden, StringComparer.Ordinal);
+ if (hidden.Count > 0)
+ {
+ metadata.Add("HiddenModifiedPathCount", hidden.Count);
+ }
- // Until Git succeeds, the index can differ from the cone file.
- this.indexMayDifferFromCone = true;
- if (!this.TryApplyConeToIndex(metadata))
- {
- keepBackup = !this.TryRollBack(writeResult, coneFileExisted, backupPath, metadata);
- this.coneFileMayBeStale = keepBackup;
- if (keepBackup)
- {
- // The cone file now has directories that the index did not expand.
- this.PublishCone(null);
- }
+ List conePaths = this.GetConePaths(modifiedPaths, hiddenSet);
+ conePaths.AddRange(requestPaths);
+ if (!this.TryBuildCone(conePaths, metadata, out ConePatternSet cone))
+ {
+ return ConeChange.InvalidPath;
+ }
- return ConeChange.ApplyFailed;
- }
+ string unsafePath = SparseDirectoryExpansionGuard.FindReachedPath(cone, hidden, this.ignoreCase);
+ if (unsafePath != null)
+ {
+ metadata.Add("UnsafeModifiedPath", unsafePath);
+ return ConeChange.ExpandsModifiedPath;
+ }
+
+ if (!this.environment.TryLockConeFile(out IDisposable coneFileLock, out Exception lockError))
+ {
+ metadata.Add("LockError", lockError?.ToString());
+ return ConeChange.ConeFileLocked;
+ }
- this.indexMayDifferFromCone = false;
+ 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 && !mustRunGit)
+ {
this.AddTransientPaths(processId, startTime, requestPaths);
this.PublishCone(cone);
- return ConeChange.Applied;
+ return ConeChange.ConeUnchanged;
}
- finally
+
+ // Until Git succeeds, the index can differ from the cone file.
+ this.indexMayDifferFromCone = true;
+ if (!this.TryApplyConeToIndex(metadata))
{
- if (!keepBackup)
+ keepBackup = !this.TryRollBack(writeResult, coneFileExisted, backupPath, metadata);
+ this.coneFileMayBeStale = keepBackup;
+ if (keepBackup)
{
- this.DeleteBackup(backupPath, metadata);
+ // The cone file now has directories that the index did not expand.
+ this.PublishCone(null);
}
+
+ return ConeChange.ApplyFailed;
+ }
+
+ this.indexMayDifferFromCone = false;
+ this.AddTransientPaths(processId, startTime, requestPaths);
+ this.PublishCone(cone);
+ return ConeChange.Applied;
+ }
+ finally
+ {
+ if (!keepBackup)
+ {
+ this.DeleteBackup(backupPath, metadata);
}
}
}
@@ -943,6 +1101,7 @@ private void ConsumeChanges(long sequence, List modifiedPaths, EventMeta
((ICollection>)this.changedPaths).Remove(change))
{
this.cleanPaths.Remove(change.Key);
+ this.ForgetDehydrateAttempts(change.Key);
if (!IsModifiedPathOrUnderModifiedFolder(change.Key, modified))
{
this.unconfirmedPaths.Add(change.Key);
@@ -986,9 +1145,422 @@ private void RemoveConfirmedAndStalePaths(HashSet modified)
{
// A dehydrated file leaves the modified paths. It is not clean or dirty any more.
this.cleanPaths.RemoveWhere(path => !modified.Contains(path));
+ this.notDehydratablePaths.RemoveWhere(path => !modified.Contains(path));
+ foreach (string path in this.dehydrateRetries.Keys.Where(path => !modified.Contains(path)).ToList())
+ {
+ this.dehydrateRetries.Remove(path);
+ }
+
+ foreach (string path in this.recordedBlobs.Keys.Where(path => !modified.Contains(path)).ToList())
+ {
+ this.recordedBlobs.Remove(path);
+ }
+
this.unconfirmedPaths.RemoveWhere(path => IsModifiedPathOrUnderModifiedFolder(path, modified));
}
+ ///
+ /// Return the clean files that an apply can return to placeholders: files that are
+ /// modified paths, that no earlier attempt found unsuitable since they last changed, and
+ /// that do not wait for a retry. The caller holds .
+ ///
+ private List GetDehydrateCandidates(HashSet modified)
+ {
+ long now = MonotonicMs();
+ List candidates = new List();
+ foreach (string path in this.cleanPaths)
+ {
+ if (!IsFolderPath(path) &&
+ modified.Contains(path) &&
+ !this.notDehydratablePaths.Contains(path) &&
+ !this.hiddenModifiedPaths.Contains(path) &&
+ !(this.dehydrateRetries.TryGetValue(path, out DehydrateRetry retry) && retry.DueTicks > now))
+ {
+ candidates.Add(path);
+ }
+ }
+
+ candidates.Sort(StringComparer.Ordinal);
+ return candidates;
+ }
+
+ ///
+ /// Return true when an apply can return a clean file to a placeholder now: a candidate
+ /// has a blob that a check read at the current repository stamp. The caller holds
+ /// .
+ ///
+ private bool HasDehydrateCandidates()
+ {
+ if (this.dehydrateBlocked || this.cleanPaths.Count == 0 || this.recordedBlobs.Count == 0)
+ {
+ return false;
+ }
+
+ long stamp = this.environment.GetRepositoryStamp();
+ return this.GetDehydrateCandidates(new HashSet(this.environment.GetModifiedPaths(), this.pathComparer))
+ .Any(path => this.TryGetValidBlob(path, stamp, out _));
+ }
+
+ private bool TryGetValidBlob(string path, long stamp, out HeadBlob blob)
+ {
+ if (this.recordedBlobs.TryGetValue(path, out RecordedBlob recorded) && recorded.Stamp == stamp)
+ {
+ blob = recorded.Blob;
+ return true;
+ }
+
+ blob = default;
+ return false;
+ }
+
+ private void SetPendingIfDehydrateIsReady(EventMetadata metadata)
+ {
+ if (this.HasDehydrateCandidates())
+ {
+ metadata.Add("DehydratePending", true);
+ this.SetPending();
+ }
+ }
+
+ ///
+ /// Return clean files to placeholders, and remove them from the modified paths. The
+ /// caller holds , and the Git command that holds the GVFS lock waits
+ /// for the reply, so Git does not change the index or HEAD meanwhile.
+ ///
+ ///
+ /// The apply uses only the blobs that a background check read while the repository
+ /// stamp was the same as now. So the index entry and HEAD still name the blob, and the
+ /// hash of the bytes proves that the file has its content. A file without such a blob
+ /// waits for the check that runs after this Git command.
+ ///
+ /// The modified paths before this step.
+ /// Started when the request arrived.
+ /// Receives the counts.
+ /// The files that are placeholders now and are no longer modified paths, with their blobs.
+ private List<(string Path, HeadBlob Blob)> DehydrateCleanFiles(List modifiedPaths, Stopwatch requestStopwatch, EventMetadata metadata)
+ {
+ List<(string Path, HeadBlob Blob)> dehydrated = new List<(string Path, HeadBlob Blob)>();
+ List candidates = this.GetDehydrateCandidates(new HashSet(modifiedPaths, this.pathComparer));
+ if (candidates.Count == 0)
+ {
+ // The timer can end shortly before a file is due.
+ this.ScheduleDehydrateRetry();
+ return dehydrated;
+ }
+
+ string blocker = this.environment.GetDehydrateBlocker();
+ this.dehydrateBlocked = blocker != null;
+ if (blocker != null)
+ {
+ metadata.Add("DehydrateBlocker", blocker);
+ return dehydrated;
+ }
+
+ long stamp = this.environment.GetRepositoryStamp();
+ List<(string Path, HeadBlob Blob)> ready = new List<(string Path, HeadBlob Blob)>();
+ foreach (string path in candidates)
+ {
+ if (this.TryGetValidBlob(path, stamp, out HeadBlob blob))
+ {
+ ready.Add((path, blob));
+ }
+ }
+
+ if (ready.Count < candidates.Count)
+ {
+ metadata.Add("DehydrateStaleCount", candidates.Count - ready.Count);
+ }
+
+ if (ready.Count == 0)
+ {
+ return dehydrated;
+ }
+
+ if (ready.Count > MaxDehydrateFiles)
+ {
+ ready.RemoveRange(MaxDehydrateFiles, ready.Count - MaxDehydrateFiles);
+ }
+
+ metadata.Add("DehydrateCandidateCount", ready.Count);
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ int attempted = 0;
+ Dictionary skipped = new Dictionary(StringComparer.Ordinal);
+ foreach ((string path, HeadBlob blob) in ready)
+ {
+ if (requestStopwatch.ElapsedMilliseconds > DehydrateRequestBudgetMs ||
+ (attempted > 0 && stopwatch.ElapsedMilliseconds > DehydrateTimeBudgetMs))
+ {
+ break;
+ }
+
+ attempted++;
+ CleanFileDehydrateResult result = this.environment.TryDehydrateCleanFile(path, blob);
+ switch (result)
+ {
+ case CleanFileDehydrateResult.Dehydrated:
+ dehydrated.Add((path, blob));
+ this.cleanPaths.Remove(path);
+ this.dehydrateRetries.Remove(path);
+ break;
+
+ case CleanFileDehydrateResult.ContentDiffers:
+ case CleanFileDehydrateResult.NotFound:
+ case CleanFileDehydrateResult.NotModifiedPath:
+ // Try again only after the file changes.
+ this.notDehydratablePaths.Add(path);
+ this.dehydrateRetries.Remove(path);
+ CountSkip(skipped, result.ToString());
+ break;
+
+ default:
+ // InUse, Replaced, PlaceholderUpdateFailed, ModifiedPathNotRemoved, or
+ // Failed: the cause can pass, so an apply tries again later.
+ this.DeferDehydrate(path);
+ CountSkip(skipped, result.ToString());
+ break;
+ }
+ }
+
+ this.ScheduleDehydrateRetry();
+
+ metadata.Add("DehydrateMs", stopwatch.ElapsedMilliseconds);
+ metadata.Add("DehydratedCount", dehydrated.Count);
+ if (skipped.Count > 0)
+ {
+ metadata.Add("DehydrateSkipped", string.Join(";", skipped.OrderBy(entry => entry.Key, StringComparer.Ordinal).Select(entry => entry.Key + "=" + entry.Value)));
+ }
+
+ return dehydrated;
+ }
+
+ ///
+ /// Return the clean files whose blobs a check must read: candidates without a blob for
+ /// . Return none while a merge or another blocker is in progress.
+ /// The caller holds .
+ ///
+ private List GetDehydrateLookupPaths(long stamp, EventMetadata metadata)
+ {
+ List lookup = new List();
+ List candidates = this.GetDehydrateCandidates(new HashSet(this.environment.GetModifiedPaths(), this.pathComparer));
+ if (candidates.Count == 0)
+ {
+ return lookup;
+ }
+
+ string blocker = this.environment.GetDehydrateBlocker();
+ this.dehydrateBlocked = blocker != null;
+ if (blocker != null)
+ {
+ metadata.Add("DehydrateBlocker", blocker);
+ return lookup;
+ }
+
+ foreach (string path in candidates)
+ {
+ if (this.TryGetValidBlob(path, stamp, out _))
+ {
+ continue;
+ }
+
+ // The path goes on a command line, which cannot have a line break.
+ if (path.IndexOfAny(new[] { '\n', '\r' }) >= 0)
+ {
+ this.notDehydratablePaths.Add(path);
+ continue;
+ }
+
+ lookup.Add(path);
+ if (lookup.Count == MaxDehydrateLookupFiles)
+ {
+ break;
+ }
+ }
+
+ return lookup;
+ }
+
+ ///
+ /// Record the blobs of a lookup that a check ran at . The caller
+ /// holds and has checked that the stamp did not change.
+ ///
+ private void RecordBlobs(List lookup, long stamp, IReadOnlyDictionary blobs, IReadOnlyCollection notInIndex, EventMetadata metadata)
+ {
+ HashSet notInIndexSet = new HashSet(notInIndex, this.pathComparer);
+ Dictionary skipped = new Dictionary(StringComparer.Ordinal);
+ int recorded = 0;
+ bool differs = false;
+ foreach (string path in lookup)
+ {
+ if (blobs.TryGetValue(path, out HeadBlob blob))
+ {
+ if (blob.Size > MaxDehydrateFileSize)
+ {
+ this.notDehydratablePaths.Add(path);
+ CountSkip(skipped, "TooLarge");
+ }
+ else
+ {
+ this.recordedBlobs[path] = new RecordedBlob(blob, stamp);
+ recorded++;
+ }
+ }
+ else if (notInIndexSet.Contains(path))
+ {
+ // For example, an ignored file. Git does not report it, so it stays clean.
+ this.notDehydratablePaths.Add(path);
+ CountSkip(skipped, "NotInIndex");
+ }
+ else if (this.cleanPaths.Remove(path))
+ {
+ // The index entry and HEAD have other blobs, so the cone must include it.
+ differs = true;
+ CountSkip(skipped, "IndexDiffersFromHead");
+ }
+ }
+
+ metadata.Add("RecordedBlobCount", recorded);
+ if (skipped.Count > 0)
+ {
+ metadata.Add("DehydrateSkipped", string.Join(";", skipped.OrderBy(entry => entry.Key, StringComparer.Ordinal).Select(entry => entry.Key + "=" + entry.Value)));
+ }
+
+ if (differs)
+ {
+ this.SetPending();
+ }
+ }
+
+ private static void CountSkip(Dictionary skipped, string reason)
+ {
+ skipped.TryGetValue(reason, out int count);
+ skipped[reason] = count + 1;
+ }
+
+ ///
+ /// Wait before the next attempt for , longer after each failure.
+ /// The caller holds .
+ ///
+ private void DeferDehydrate(string path)
+ {
+ this.dehydrateRetries.TryGetValue(path, out DehydrateRetry previous);
+ int failures = previous.Failures + 1;
+ long delayMs = Math.Min((long)this.dehydrateRetryDelayMs << Math.Min(failures - 1, 16), MaxDehydrateRetryDelayMs);
+ this.dehydrateRetries[path] = new DehydrateRetry(MonotonicMs() + delayMs, failures);
+ }
+
+ ///
+ /// Make a cone change pending when the next deferred file is due. A file that is due
+ /// already was a candidate of this apply. The caller holds .
+ ///
+ private void ScheduleDehydrateRetry()
+ {
+ long now = MonotonicMs();
+ List future = this.dehydrateRetries.Values.Select(retry => retry.DueTicks).Where(due => due > now).ToList();
+ if (future.Count == 0 || this.isStopped)
+ {
+ return;
+ }
+
+ try
+ {
+ this.dehydrateRetryTimer.Change(future.Min() - now, Timeout.Infinite);
+ }
+ catch (ObjectDisposedException) when (this.isStopped)
+ {
+ }
+ }
+
+ // Environment.TickCount64 changes only every 10 to 16 ms, so a short wait can look not due.
+ private static long MonotonicMs()
+ {
+ return (long)Stopwatch.GetElapsedTime(0).TotalMilliseconds;
+ }
+
+ private void OnDehydrateRetryDue()
+ {
+ if (this.isStopped)
+ {
+ return;
+ }
+
+ bool ready;
+ lock (this.coneLock)
+ {
+ // A due file whose blob is not valid any more needs a check before an apply.
+ ready = this.HasDehydrateCandidates();
+ this.dehydrateLookupRequested |= !ready;
+ }
+
+ if (ready)
+ {
+ this.SetPending();
+ }
+ else
+ {
+ this.ScheduleReconcile();
+ }
+ }
+
+ ///
+ /// The file changed, so an apply can try it again at once. The caller holds
+ /// .
+ ///
+ private void ForgetDehydrateAttempts(string path)
+ {
+ this.notDehydratablePaths.Remove(path);
+ this.dehydrateRetries.Remove(path);
+ }
+
+ ///
+ /// After the apply: when Git wrote the index, make sure that the projection has the
+ /// files. Otherwise make the files modified paths again, so that Git sees them as it did
+ /// before. They are placeholders with the content of HEAD, so nothing is lost.
+ ///
+ ///
+ /// A projection rebuild reads the whole index, which takes seconds for a large
+ /// repository. The projection still has a file as it was before the file became a
+ /// modified path, unless a command rebuilt the projection since then (for example a
+ /// checkout or a hard reset). Only then does the apply rebuild it, once.
+ ///
+ private void FinishDehydrate(List<(string Path, HeadBlob Blob)> dehydrated, bool indexWritten, EventMetadata metadata)
+ {
+ if (indexWritten)
+ {
+ bool rebuild = dehydrated.Any(file => !this.environment.IsProjectedFile(file.Path, file.Blob.Sha));
+ metadata.Add("ProjectionInvalidated", rebuild);
+ if (rebuild)
+ {
+ this.environment.InvalidateProjection();
+ }
+
+ return;
+ }
+
+ int restoreFailures = 0;
+ foreach ((string path, HeadBlob _) in dehydrated)
+ {
+ if (this.environment.TryRestoreModifiedPath(path))
+ {
+ this.cleanPaths.Add(path);
+ }
+ else
+ {
+ restoreFailures++;
+ }
+ }
+
+ metadata.Add("DehydrateRestoredCount", dehydrated.Count - restoreFailures);
+ if (restoreFailures > 0)
+ {
+ // Until the next validation of the modified paths adds them (their index entries
+ // do not have the skip-worktree bit), only their first write makes Git see them.
+ metadata.Add("DehydrateRestoreFailureCount", restoreFailures);
+ EventMetadata errorMetadata = this.CreateMetadata(commandId: null);
+ errorMetadata.Add("DehydrateRestoreFailureCount", restoreFailures);
+ this.tracer.RelatedError(errorMetadata, "Could not make dehydrated files modified paths again", Keywords.Telemetry);
+ }
+ }
+
///
/// Record that the index has entries for every directory of , and
/// that the cone file is . Null means that this is not known.
@@ -1170,6 +1742,8 @@ private ConeChange Reconcile(EventMetadata metadata)
AppliedConeSnapshot cone;
List candidates;
(long, long, long) state;
+ ConeChange checkResult;
+ List lookup;
lock (this.coneLock)
{
// A pending change can be in a directory that the index does not expand, so Git
@@ -1183,13 +1757,15 @@ private ConeChange Reconcile(EventMetadata metadata)
startSequence = Interlocked.Read(ref this.changeSequence);
epoch = this.consumeEpoch;
state = (startSequence, epoch, this.environment.GetRepositoryStamp());
- if (this.lastReconcileState == state)
+ if (this.lastReconcileState == state && !this.dehydrateLookupRequested)
{
// A failed write leaves the cone file stale. The clean paths are known, so
// write the file again without Git.
return this.coneFileMayBeStale ? this.WriteNarrowerCone(metadata) : ConeChange.NothingChanged;
}
+ this.dehydrateLookupRequested = false;
+
// Only a file that the index has an entry for can be clean: one in an applied
// directory, or one that an earlier check found clean while its directory was
// applied. Folders stay in the cone.
@@ -1228,6 +1804,7 @@ private ConeChange Reconcile(EventMetadata metadata)
}
HashSet differing = new HashSet(differingPaths, this.pathComparer);
+ long stamp = state.Item3;
List untrackedFolders = differingPaths.Where(IsFolderPath).ToList();
// A file is clean when Git lists neither the file nor an untracked folder that
@@ -1260,6 +1837,9 @@ private ConeChange Reconcile(EventMetadata metadata)
// that Git wrote), so it leaves the cone without becoming a clean path.
if (this.unconfirmedPaths.Remove(result.Key) || this.cleanPaths.Add(result.Key))
{
+ // An earlier apply could not dehydrate it, because the index or HEAD
+ // differed. Git changed them, so the next apply tries again.
+ this.ForgetDehydrateAttempts(result.Key);
newlyClean++;
}
}
@@ -1273,9 +1853,11 @@ private ConeChange Reconcile(EventMetadata metadata)
// expands, so the result above already includes it.
foreach (KeyValuePair change in this.changedPaths)
{
- if (change.Value.Sequence <= startSequence && change.Value.WasCovered)
+ if (change.Value.Sequence <= startSequence && change.Value.WasCovered &&
+ ((ICollection>)this.changedPaths).Remove(change))
{
- ((ICollection>)this.changedPaths).Remove(change);
+ // The file changed since an attempt kept it.
+ this.ForgetDehydrateAttempts(change.Key);
}
}
@@ -1292,12 +1874,61 @@ private ConeChange Reconcile(EventMetadata metadata)
return ConeChange.CleanPathChanged;
}
- if (newlyClean == 0)
+ checkResult = newlyClean == 0 ? ConeChange.ConeUnchanged : this.WriteNarrowerCone(metadata);
+ if (IsFailure(checkResult))
{
- return ConeChange.ConeUnchanged;
+ // A pending change would stop the next check, which writes the cone file
+ // again. The check after that reads the blobs.
+ return checkResult;
}
- return this.WriteNarrowerCone(metadata);
+ // Read the blobs of the clean files here, so that an apply does not run Git for
+ // them while a Git command waits. After a blocker such as a merge ends, the files
+ // that it kept are candidates again.
+ lookup = this.GetDehydrateLookupPaths(stamp, metadata);
+ if (lookup.Count == 0)
+ {
+ this.SetPendingIfDehydrateIsReady(metadata);
+ return checkResult;
+ }
+ }
+
+ metadata.Add("DehydrateLookupCount", lookup.Count);
+ Stopwatch blobStopwatch = Stopwatch.StartNew();
+ bool found = this.environment.TryGetBlobsThatMatchHead(lookup, DehydrateLookupTimeoutMs, out IReadOnlyDictionary blobs, out IReadOnlyCollection notInIndex, out string blobError);
+ metadata.Add("DehydrateBlobMs", blobStopwatch.ElapsedMilliseconds);
+
+ lock (this.coneLock)
+ {
+ if (this.consumeEpoch != epoch || this.isStopped)
+ {
+ // An apply ran meanwhile. The next check reads the blobs again.
+ return checkResult;
+ }
+
+ if (!found)
+ {
+ metadata.Add("DehydrateBlobError", blobError);
+ foreach (string path in lookup)
+ {
+ this.DeferDehydrate(path);
+ }
+
+ this.ScheduleDehydrateRetry();
+ return checkResult;
+ }
+
+ // Git does not hold the GVFS lock for the lookup, so a Git command can write the
+ // index or move HEAD meanwhile. Then the blobs can be wrong.
+ if (this.environment.GetRepositoryStamp() != stamp)
+ {
+ metadata.Add("DehydrateBlobStale", true);
+ return checkResult;
+ }
+
+ this.RecordBlobs(lookup, stamp, blobs, notInIndex, metadata);
+ this.SetPendingIfDehydrateIsReady(metadata);
+ return checkResult;
}
}
@@ -1385,10 +2016,15 @@ private void TraceResult(string eventName, ConeChange change, long durationMs, i
}
// A hidden modified path stays invisible to Git, so it is a warning too.
- if (IsFailure(change) || exceededWaitBudget || metadata.ContainsKey("DeleteBackupError") || metadata.ContainsKey("HiddenModifiedPathCount"))
+ if (IsFailure(change) || exceededWaitBudget || metadata.ContainsKey("DeleteBackupError") || metadata.ContainsKey("HiddenModifiedPathCount") || metadata.ContainsKey("DehydrateRestoreFailureCount"))
{
this.tracer.RelatedEvent(EventLevel.Warning, eventName, metadata, Keywords.Telemetry);
}
+ else if (metadata.ContainsKey("DehydrateCandidateCount") || metadata.ContainsKey("DehydrateLookupCount"))
+ {
+ // A dehydrate discards bytes on disk, so its results go to telemetry.
+ this.tracer.RelatedEvent(EventLevel.Informational, eventName, metadata, Keywords.Telemetry);
+ }
else
{
this.tracer.RelatedEvent(EventLevel.Informational, eventName, metadata);
@@ -1406,6 +2042,12 @@ private int GetTransientCommandCount()
/// A working-tree change: its order, and if the applied cone included the path then.
private readonly record struct PathChange(long Sequence, bool WasCovered);
+ /// The time of the next dehydrate attempt for a file (), and the failures so far.
+ private readonly record struct DehydrateRetry(long DueTicks, int Failures);
+
+ /// A blob that a check read, and the repository stamp at that time.
+ private readonly record struct RecordedBlob(HeadBlob Blob, long Stamp);
+
/// Records whether a request cleared the pending file.
private sealed class ApplyAttempt
{
diff --git a/GVFS/GVFS.Common/Sparse/CleanFileDehydrateResult.cs b/GVFS/GVFS.Common/Sparse/CleanFileDehydrateResult.cs
new file mode 100644
index 0000000000..1ff9d6bbf8
--- /dev/null
+++ b/GVFS/GVFS.Common/Sparse/CleanFileDehydrateResult.cs
@@ -0,0 +1,48 @@
+namespace GVFS.Common.Sparse
+{
+ ///
+ /// The result of an attempt to return a modified file that matches HEAD to a placeholder.
+ ///
+ public enum CleanFileDehydrateResult
+ {
+ ///
+ /// The file is a placeholder for the expected blob again, and it is not a modified path.
+ ///
+ Dehydrated,
+
+ /// The modified paths do not have the file. Nothing changed.
+ NotModifiedPath,
+
+ /// The working tree does not have the file. Nothing changed.
+ NotFound,
+
+ ///
+ /// Another process has the file open in a way that prevents the check. Nothing changed.
+ ///
+ InUse,
+
+ ///
+ /// The path no longer names the file that was checked, or a delete of the file is
+ /// pending: for example, a process renamed another file over it. Nothing changed.
+ ///
+ Replaced,
+
+ /// The bytes on disk are not the expected blob. Nothing changed.
+ ContentDiffers,
+
+ ///
+ /// The virtualization layer did not convert the file. The file and its modified path
+ /// did not change.
+ ///
+ PlaceholderUpdateFailed,
+
+ ///
+ /// The file is a placeholder for the expected blob, but it is still a modified path. Git
+ /// still sees the file, so nothing is lost.
+ ///
+ ModifiedPathNotRemoved,
+
+ /// An unexpected error. The file is unchanged or matches the expected blob.
+ Failed,
+ }
+}
diff --git a/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs b/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs
index 867ed212e1..37a2019832 100644
--- a/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs
+++ b/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs
@@ -71,8 +71,52 @@ public interface IConeManagerEnvironment
///
/// Return a value that changes when Git writes the index or moves HEAD, so that the
- /// manager can skip a check when nothing changed.
+ /// manager can skip a check when nothing changed, and can tell whether a blob that a
+ /// check read is still the blob of the index entry and HEAD.
///
long GetRepositoryStamp();
+
+ ///
+ /// Return why modified files cannot return to placeholders now, or null when they can.
+ /// For example, a merge, rebase, cherry-pick, or revert is in progress, or
+ /// gvfs dehydrate is working on folders.
+ ///
+ string GetDehydrateBlocker();
+
+ ///
+ /// Read the blob of each path in the index and in HEAD. Return in
+ /// only the paths that have the same blob in both, and in
+ /// the paths that the index does not have. The caller does not hold the GVFS lock, so it
+ /// compares before and after the lookup. Fail after
+ /// .
+ ///
+ bool TryGetBlobsThatMatchHead(IReadOnlyList gitPaths, int timeoutMs, out IReadOnlyDictionary blobs, out IReadOnlyCollection notInIndex, out string error);
+
+ ///
+ /// Return the modified file to a placeholder for
+ /// , and remove it from the modified paths. This happens only when
+ /// the bytes on disk are exactly the blob, because the conversion discards them.
+ ///
+ CleanFileDehydrateResult TryDehydrateCleanFile(string gitPath, HeadBlob blob);
+
+ ///
+ /// Add a file that removed back to the modified paths,
+ /// so that Git sees it again when the index cannot change.
+ ///
+ bool TryRestoreModifiedPath(string gitPath);
+
+ ///
+ /// Return true when the projection has the file for the blob
+ /// . The projection leaves out every index entry without the
+ /// skip-worktree bit. It still has a file that had the bit when the projection was last
+ /// parsed, also after the file became a modified path.
+ ///
+ bool IsProjectedFile(string gitPath, string sha);
+
+ ///
+ /// Make the mount read the index again, because Git set the skip-worktree bit of files
+ /// that the projection does not have. Returns at once.
+ ///
+ void InvalidateProjection();
}
}
diff --git a/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs b/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs
index 6d3dcb9ab1..216f6c275f 100644
--- a/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs
+++ b/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs
@@ -1,13 +1,15 @@
namespace GVFS.Common.Sparse
{
///
- /// Receives the working-tree changes that the file system callbacks of the mount see.
+ /// Receives the working-tree changes that the file system callbacks of the mount see, and
+ /// the staged files that the mount adds to the modified paths before an unstage.
///
public interface IWorkingDirectoryChangeObserver
{
///
- /// A file or folder was created, written, renamed, or deleted. This runs in a file system
- /// callback, so it must be fast, it must not wait for a Git command, and it must not throw.
+ /// A file or folder was created, written, renamed, or deleted, or a staged file became a
+ /// modified path. This runs in a file system callback or a pipe request handler, so it
+ /// must be fast, it must not wait for a Git command, and it must not throw.
///
/// The path relative to the working-tree root, with either separator.
/// True for a folder.
diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs
index 35e6ff3c72..3d168d3643 100644
--- a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs
+++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs
@@ -172,19 +172,5 @@ public void WidenDoesNotRestoreADeletedFile()
this.GitShouldSucceed("status --porcelain").ShouldContain(" D " + this.deletedFile);
File.Exists(this.Enlistment.GetVirtualPathTo(this.deletedFile)).ShouldBeFalse("The widen restored the deleted file");
}
-
- private int IndexHeaderEntryCount()
- {
- // Bytes 8 to 11 of the index file are its entry count (big-endian). A sparse-directory
- // entry counts as one entry. ls-files cannot show the count on disk, because Git
- // collapses a full index in memory when it reads it with index.sparse true.
- byte[] header = new byte[12];
- using (FileStream stream = new FileStream(this.Enlistment.GetDotGitPath("index"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
- {
- stream.ReadExactly(header, 0, header.Length);
- }
-
- return (header[8] << 24) | (header[9] << 16) | (header[10] << 8) | header[11];
- }
}
}
diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexDehydrateTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexDehydrateTests.cs
new file mode 100644
index 0000000000..69b40d0bd3
--- /dev/null
+++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexDehydrateTests.cs
@@ -0,0 +1,610 @@
+using GVFS.FunctionalTests.FileSystemRunners;
+using GVFS.FunctionalTests.Should;
+using GVFS.FunctionalTests.Tools;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.IO.MemoryMappedFiles;
+using System.Linq;
+using System.Text;
+using System.Threading;
+
+namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture
+{
+ ///
+ /// Functional tests for modified files outside the sparse-index cone that have the content of
+ /// HEAD again: the mount returns them to placeholders, so that Git can collapse their
+ /// directories, and a later write is still visible to Git.
+ ///
+ [TestFixture]
+ public class AutoSparseIndexDehydrateTests : AutoSparseIndexTestsBase
+ {
+ private const string Edit = "edited after the dehydrate";
+
+ private static readonly TimeSpan WaitTime = TimeSpan.FromSeconds(30);
+
+ private readonly FileSystemRunner fileSystem = new SystemIORunner();
+
+ // Files of HEAD, each in a different two-level directory outside the root-only cone
+ private Queue unusedFiles;
+
+ [OneTimeSetUp]
+ public void SelectFiles()
+ {
+ // One file in each directory, so that the tests do not share a cone line.
+ this.unusedFiles = new Queue(this.DeepHeadFiles
+ .GroupBy(ParentDirectory, StringComparer.OrdinalIgnoreCase)
+ .Select(group => group.First()));
+ this.unusedFiles.Count.ShouldBeAtLeast(24, "HEAD has too few directories that are two or more levels deep");
+ }
+
+ [TestCase]
+ public void DehydrateCollapsesTheDirectoryAndTheFileHasTheContentOfHead()
+ {
+ // In a directory with one file, the collapse does not change the entry count.
+ string file = this.TakeFileWhere(candidate => this.DeepHeadFiles.Count(other => ParentDirectory(other).Equals(ParentDirectory(candidate), StringComparison.OrdinalIgnoreCase)) > 1);
+ byte[] headContent = this.MakeFileModifiedThenClean(file);
+
+ // While the file is a modified path, the hook clears its skip-worktree bit, so Git
+ // keeps its own index entry, also in the index file on disk.
+ this.SparseIndexEntries().ShouldContain(entry => entry.Equals(file, StringComparison.OrdinalIgnoreCase));
+ int expandedCount = this.IndexHeaderEntryCount();
+
+ this.RunGitAndWaitForTheDehydrate(file);
+
+ int collapsedCount = this.IndexHeaderEntryCount();
+ (collapsedCount < expandedCount).ShouldBeTrue($"The index on disk did not shrink: {collapsedCount} of {expandedCount} entries");
+ List entries = this.SparseIndexEntries();
+ entries.ShouldNotContain(entry => entry.Equals(file, StringComparison.OrdinalIgnoreCase));
+ entries.ShouldContain(entry => entry.EndsWith("/") && file.StartsWith(entry, StringComparison.OrdinalIgnoreCase));
+ this.GitShouldSucceed("status --porcelain").ShouldNotContain(ignoreCase: true, file);
+ File.ReadAllBytes(this.Enlistment.GetVirtualPathTo(file)).ShouldMatchInOrder(headContent);
+ GVFSHelpers.ModifiedPathsShouldNotContain(this.Enlistment, this.fileSystem, file);
+ }
+
+ [TestCase]
+ public void InPlaceWriteAfterTheDehydrateIsVisibleToGit()
+ {
+ string file = this.TakeDehydratedFile();
+
+ using (FileStream stream = new FileStream(this.Enlistment.GetVirtualPathTo(file), FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
+ {
+ stream.Seek(0, SeekOrigin.End);
+ byte[] edit = Encoding.UTF8.GetBytes(Environment.NewLine + Edit + Environment.NewLine);
+ stream.Write(edit, 0, edit.Length);
+ }
+
+ this.GitShouldSeeTheEdit(file, Edit);
+ }
+
+ [TestCase]
+ public void MemoryMappedWriteAfterTheDehydrateIsVisibleToGit()
+ {
+ string file = this.TakeDehydratedFile();
+ string path = this.Enlistment.GetVirtualPathTo(file);
+
+ byte replaced;
+ using (MemoryMappedFile mapping = MemoryMappedFile.CreateFromFile(path, FileMode.Open, mapName: null, capacity: 0, MemoryMappedFileAccess.ReadWrite))
+ using (MemoryMappedViewAccessor view = mapping.CreateViewAccessor(0, 0, MemoryMappedFileAccess.ReadWrite))
+ {
+ byte first = view.ReadByte(0);
+ replaced = first == (byte)'#' ? (byte)'$' : (byte)'#';
+ view.Write(0, replaced);
+ view.Flush();
+ }
+
+ this.GitShouldSeeTheEdit(file, ((char)replaced).ToString());
+ }
+
+ [TestCase]
+ public void TruncatingOverwriteAfterTheDehydrateIsVisibleToGit()
+ {
+ string file = this.TakeDehydratedFile();
+
+ File.WriteAllText(this.Enlistment.GetVirtualPathTo(file), Edit + Environment.NewLine);
+
+ this.GitShouldSeeTheEdit(file, Edit);
+ }
+
+ [TestCase]
+ public void RenameOverSaveAfterTheDehydrateIsVisibleToGit()
+ {
+ string file = this.TakeDehydratedFile();
+ string path = this.Enlistment.GetVirtualPathTo(file);
+ string temporaryPath = path + ".save-tmp";
+
+ File.WriteAllText(temporaryPath, Edit + Environment.NewLine);
+ File.Move(temporaryPath, path, overwrite: true);
+
+ this.GitShouldSeeTheEdit(file, Edit);
+ }
+
+ [TestCase]
+ public void FileWithOtherBytesButTheSameSizeAndTimeIsNotDehydrated()
+ {
+ string file = this.TakeFile();
+ string directory = ParentDirectory(file);
+ string path = this.Enlistment.GetVirtualPathTo(file);
+ byte[] headContent = File.ReadAllBytes(path);
+ this.AppendTo(file);
+ this.GitShouldSucceed("status --porcelain").ShouldContain(file);
+
+ // Make the stat data of the index entry match the file, then change the bytes and
+ // keep the size and the time. These steps take less time than the wait before the
+ // mount checks the file.
+ DateTimeOffset written = DateTimeOffset.Now;
+ File.WriteAllBytes(path, headContent);
+
+ // Other modified files can need an update, which makes the exit code 1.
+ GitProcess.InvokeProcess(this.Enlistment.RepoRoot, "update-index -q --refresh");
+ DateTime lastWriteTime = File.GetLastWriteTimeUtc(path);
+ byte[] otherContent = (byte[])headContent.Clone();
+ otherContent[0] = otherContent[0] == (byte)'#' ? (byte)'$' : (byte)'#';
+ File.WriteAllBytes(path, otherContent);
+ File.SetLastWriteTimeUtc(path, lastWriteTime);
+
+ // Git compares only the stat data, so the check of the mount finds the file clean.
+ this.WaitForTheCheckToFindTheFileClean(directory, written);
+
+ DateTimeOffset applied = DateTimeOffset.Now;
+ this.GitShouldSucceed("status --porcelain");
+ this.WaitForAnApplyThatSkipped(applied, "ContentDiffers=1");
+
+ File.ReadAllBytes(path).ShouldMatchInOrder(otherContent);
+ this.IsPlaceholder(file).ShouldBeFalse();
+ GVFSHelpers.ModifiedPathsShouldContain(this.Enlistment, this.fileSystem, file);
+ File.WriteAllBytes(path, headContent);
+ }
+
+ [TestCase(FileAccess.Read, FileShare.Read)]
+ [TestCase(FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete)]
+ public void FileThatIsOpenIsNotDehydrated(FileAccess access, FileShare share)
+ {
+ string file = this.TakeFile();
+ FileStream handle = null;
+ try
+ {
+ // Open the file before the mount can check it.
+ this.MakeFileModifiedThenClean(file, () => handle = new FileStream(this.Enlistment.GetVirtualPathTo(file), FileMode.Open, access, share));
+ DateTimeOffset applied = DateTimeOffset.Now;
+ this.GitShouldSucceed("status --porcelain");
+ this.WaitForAnApplyThatSkipped(applied, "DehydrateSkipped");
+
+ this.IsPlaceholder(file).ShouldBeFalse();
+ GVFSHelpers.ModifiedPathsShouldContain(this.Enlistment, this.fileSystem, file);
+ }
+ finally
+ {
+ handle?.Dispose();
+ }
+ }
+
+ [TestCase]
+ public void NoDehydrateDuringAMergeConflict()
+ {
+ string head = this.GitShouldSucceed("rev-parse HEAD").Trim();
+ string ours = this.CommitWithoutTheWorkingTree(head, "ours");
+ string theirs = this.CommitWithoutTheWorkingTree(head, "theirs");
+ this.GitShouldSucceed("merge --ff-only " + ours);
+ GitProcess.InvokeProcess(this.Enlistment.RepoRoot, "merge --no-edit " + theirs).ExitCode.ShouldNotEqual(0, "The merge must stop with a conflict");
+ File.Exists(this.Enlistment.GetDotGitPath("MERGE_HEAD")).ShouldBeTrue();
+
+ string file = this.TakeFile();
+ try
+ {
+ DateTimeOffset start = DateTimeOffset.Now;
+ this.MakeFileModifiedThenClean(file);
+ this.WaitForTheCheckToFindTheFileClean(ParentDirectory(file), start, requiredMetadata: "\"DehydrateBlocker\":\"MERGE_HEAD\"");
+ this.GitShouldSucceed("status --porcelain");
+
+ this.IsPlaceholder(file).ShouldBeFalse();
+ GVFSHelpers.ModifiedPathsShouldContain(this.Enlistment, this.fileSystem, file);
+ }
+ finally
+ {
+ this.GitShouldSucceed("merge --abort");
+ this.GitShouldSucceed("reset --hard " + head);
+ }
+
+ // The commands above change the index and HEAD, so the mount checks again, and the
+ // next command dehydrates the file.
+ this.RunGitAndWaitForTheDehydrate(file);
+ }
+
+ [TestCase("reset --hard", "append")]
+ [TestCase("reset --hard", "replace")]
+ [TestCase("reset --hard", "deletecreate")]
+ [TestCase("checkout -f", "append")]
+ [TestCase("restore --staged --worktree -- {0}", "append")]
+ public void FileThatADiscardRestoredIsDehydratedAndItsDirectoryCollapses(string discardCommand, string editStyle)
+ {
+ string file = this.TakeFile();
+ string directory = ParentDirectory(file);
+ string path = this.Enlistment.GetVirtualPathTo(file);
+ byte[] headContent = File.ReadAllBytes(path);
+ switch (editStyle)
+ {
+ case "append":
+ this.AppendTo(file);
+ break;
+
+ case "replace":
+ // The save pattern of many editors: write a new file, then rename it over the old one.
+ File.WriteAllText(path + ".save-tmp", "replaced" + Environment.NewLine);
+ File.Move(path + ".save-tmp", path, overwrite: true);
+ break;
+
+ default:
+ File.Delete(path);
+ File.WriteAllText(path, "created again" + Environment.NewLine);
+ break;
+ }
+
+ this.GitShouldSucceed("add -- " + file);
+
+ // The discard writes the content of HEAD and can rebuild the projection. The file
+ // stays a modified path, and the check must still find it clean.
+ DateTimeOffset discarded = DateTimeOffset.Now;
+ this.GitShouldSucceed(string.Format(discardCommand, file));
+ File.ReadAllBytes(path).ShouldMatchInOrder(headContent);
+ this.WaitForTheCheckToFindTheFileClean(directory, discarded);
+ int expandedCount = this.IndexHeaderEntryCount();
+
+ this.RunGitAndWaitForTheDehydrate(file);
+
+ this.IndexHeaderEntryCount().ShouldBeAtMost(expandedCount, "The index on disk grew");
+ this.SparseIndexEntries().ShouldContain(entry => entry.EndsWith("/") && file.StartsWith(entry, StringComparison.OrdinalIgnoreCase));
+ this.GitShouldSucceed("status --porcelain").ShouldNotContain(ignoreCase: true, file);
+ File.ReadAllBytes(path).ShouldMatchInOrder(headContent);
+
+ // A folder dehydrate afterwards keeps the content of HEAD and a clean status.
+ ProcessResult dehydrate = this.RunGVFS($"dehydrate --confirm --no-status --folders {directory}");
+ dehydrate.ExitCode.ShouldEqual(0, dehydrate.Output + dehydrate.Errors);
+ File.ReadAllBytes(path).ShouldMatchInOrder(headContent);
+ this.GitShouldSucceed("status --porcelain").ShouldNotContain(ignoreCase: true, file);
+ GVFSHelpers.ModifiedPathsShouldNotContain(this.Enlistment, this.fileSystem, file);
+ }
+
+ [TestCase]
+ public void FolderDehydrateLeavesASparseIndexAndAConeWithTheOtherModifiedPaths()
+ {
+ // The folder dehydrate moves every file of the folder and its subfolders to its
+ // backup, so the dirty file must be outside them.
+ string cleanFile = this.TakeFile();
+ string folder = ParentDirectory(cleanFile);
+ string dirtyFile = this.TakeFileOutside(folder);
+ this.AppendTo(dirtyFile);
+ this.GitShouldSucceed("status --porcelain").ShouldContain(dirtyFile);
+
+ byte[] headContent = this.MakeFileModifiedThenClean(cleanFile);
+ int expandedCount = this.IndexHeaderEntryCount();
+
+ ProcessResult dehydrate = this.RunGVFS($"dehydrate --confirm --no-status --folders {folder}");
+ dehydrate.ExitCode.ShouldEqual(0, dehydrate.Output + dehydrate.Errors);
+
+ this.IsPlaceholder(cleanFile).ShouldBeTrue();
+ GVFSHelpers.ModifiedPathsShouldNotContain(this.Enlistment, this.fileSystem, cleanFile);
+ GVFSHelpers.ModifiedPathsShouldContain(this.Enlistment, this.fileSystem, dirtyFile);
+ this.GitShouldSucceed("status --porcelain").ShouldContain(" M " + dirtyFile);
+ ConeLines(this.ReadConeFile()).ShouldContain(line => IsConeLineFor(line, ParentDirectory(dirtyFile)));
+ this.IndexHeaderEntryCount().ShouldBeAtMost(expandedCount, "The folder dehydrate left more entries in the index on disk");
+ List entries = this.SparseIndexEntries();
+ entries.ShouldContain(entry => entry.EndsWith("/") && cleanFile.StartsWith(entry, StringComparison.OrdinalIgnoreCase));
+ File.ReadAllBytes(this.Enlistment.GetVirtualPathTo(cleanFile)).ShouldMatchInOrder(headContent);
+
+ this.GitShouldSucceed("checkout -- " + dirtyFile);
+ }
+
+ [TestCase]
+ public void FileWithAMappedViewIsNotDehydratedAndAWriteThroughTheViewStaysOnDisk()
+ {
+ string file = this.TakeFile();
+ string path = this.Enlistment.GetVirtualPathTo(file);
+
+ // Map the file before the mount can check it. After the handle closes, only the
+ // mapped view refers to the file, so the share mode of the check does not see it.
+ MemoryMappedFile mapping = null;
+ byte[] headContent = this.MakeFileModifiedThenClean(file, () =>
+ {
+ using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete))
+ {
+ mapping = MemoryMappedFile.CreateFromFile(stream, mapName: null, capacity: 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, leaveOpen: true);
+ }
+ });
+
+ byte replaced;
+ using (mapping)
+ using (MemoryMappedViewAccessor view = mapping.CreateViewAccessor(0, 0, MemoryMappedFileAccess.ReadWrite))
+ {
+ this.GitShouldSucceed("status --porcelain");
+
+ this.IsPlaceholder(file).ShouldBeFalse();
+ GVFSHelpers.ModifiedPathsShouldContain(this.Enlistment, this.fileSystem, file);
+
+ byte first = view.ReadByte(0);
+ replaced = first == (byte)'#' ? (byte)'$' : (byte)'#';
+ view.Write(0, replaced);
+ view.Flush();
+ }
+
+ // A write through a view whose handle is closed does not change the time of the file,
+ // so Git's stat check can miss it. The write is on disk, and the file is still a
+ // modified path, so Git sees it once the stat data changes.
+ File.ReadAllBytes(path)[0].ShouldEqual(replaced);
+ this.IsPlaceholder(file).ShouldBeFalse();
+ GVFSHelpers.ModifiedPathsShouldContain(this.Enlistment, this.fileSystem, file);
+ File.WriteAllBytes(path, headContent);
+ }
+
+ private string TakeFile()
+ {
+ while (true)
+ {
+ // The length of a placeholder does not hydrate it.
+ string file = this.unusedFiles.Dequeue();
+ if (new FileInfo(this.Enlistment.GetVirtualPathTo(file)).Length > 0)
+ {
+ return file;
+ }
+ }
+ }
+
+ private string TakeFileOutside(string directory)
+ {
+ return this.TakeFileWhere(file => !file.StartsWith(directory + "/", StringComparison.OrdinalIgnoreCase));
+ }
+
+ private string TakeFileWhere(Func predicate)
+ {
+ List skipped = new List();
+ try
+ {
+ while (true)
+ {
+ string file = this.TakeFile();
+ if (predicate(file))
+ {
+ return file;
+ }
+
+ skipped.Add(file);
+ }
+ }
+ finally
+ {
+ foreach (string file in skipped)
+ {
+ this.unusedFiles.Enqueue(file);
+ }
+ }
+ }
+
+ private ProcessResult RunGVFS(string arguments)
+ {
+ ProcessStartInfo processInfo = new ProcessStartInfo(GVFSTestConfig.PathToGVFS);
+ processInfo.Arguments = arguments + " " + TestConstants.InternalUseOnlyFlag + " " + GVFSHelpers.GetInternalParameter();
+ processInfo.WindowStyle = ProcessWindowStyle.Hidden;
+ processInfo.WorkingDirectory = this.Enlistment.EnlistmentRoot;
+ processInfo.UseShellExecute = false;
+ processInfo.RedirectStandardOutput = true;
+ processInfo.RedirectStandardError = true;
+ return ProcessHelper.Run(processInfo);
+ }
+
+ private string TakeDehydratedFile()
+ {
+ string file = this.TakeFile();
+ this.MakeFileModifiedThenClean(file);
+ this.RunGitAndWaitForTheDehydrate(file);
+ return file;
+ }
+
+ ///
+ /// Edit a file outside the cone, let Git see the edit, and write the content of HEAD back.
+ /// Return when the check of the mount found the file clean. Before the check,
+ /// runs.
+ ///
+ private byte[] MakeFileModifiedThenClean(string file, Action afterHeadContentIsWritten = null)
+ {
+ string directory = ParentDirectory(file);
+ string path = this.Enlistment.GetVirtualPathTo(file);
+ byte[] headContent = File.ReadAllBytes(path);
+ headContent.Length.ShouldBeAtLeast(1, file + " is empty");
+
+ this.AppendTo(file);
+ this.GitShouldSucceed("status --porcelain").ShouldContain(file);
+ ConeLines(this.ReadConeFile()).ShouldContain(line => IsConeLineFor(line, directory));
+
+ DateTimeOffset written = DateTimeOffset.Now;
+ File.WriteAllBytes(path, headContent);
+ afterHeadContentIsWritten?.Invoke();
+ this.WaitForTheCheckToFindTheFileClean(directory, written);
+
+ // A Git command that runs in the background (for example the status cache of the
+ // mount) can dehydrate the file from here on.
+ return headContent;
+ }
+
+ ///
+ /// The check made an apply pending. Run a Git command, which sends the apply, and wait
+ /// until the file is a placeholder and not a modified path.
+ ///
+ private void RunGitAndWaitForTheDehydrate(string file)
+ {
+ this.GitShouldSucceed("status --porcelain");
+
+ DateTime end = DateTime.UtcNow + WaitTime;
+ while (true)
+ {
+ bool isModifiedPath = GVFSHelpers.GetCurrentModifiedPaths(this.Enlistment, this.fileSystem)
+ .Contains(file);
+ bool isPlaceholder = this.IsPlaceholder(file);
+ if (!isModifiedPath && isPlaceholder)
+ {
+ return;
+ }
+
+ if (DateTime.UtcNow > end)
+ {
+ Assert.Fail($"{file} was not dehydrated: modified path {isModifiedPath}, placeholder {isPlaceholder}. Last cone events:\n{this.LastConeEvents()}");
+ }
+
+ Thread.Sleep(250);
+ this.GitShouldSucceed("status --porcelain");
+ }
+ }
+
+ ///
+ /// Wait until the cone no longer includes , or until the
+ /// mount log has a check after that found a clean file. A
+ /// narrow can fail while another Git process reads the cone file; the next apply then
+ /// writes it.
+ ///
+ private void WaitForTheCheckToFindTheFileClean(string directory, DateTimeOffset since, string requiredMetadata = null)
+ {
+ DateTime end = DateTime.UtcNow + WaitTime;
+ while (DateTime.UtcNow < end)
+ {
+ bool narrowed = requiredMetadata == null && !ConeLines(this.ReadConeFile()).Any(line => IsConeLineFor(line, directory));
+ if (narrowed || this.ConeEvents(since).Any(line => line.Contains("] ConeReconcile ") && !line.Contains("\"NewlyCleanCount\":0") && line.Contains("NewlyCleanCount") && (requiredMetadata == null || line.Contains(requiredMetadata))))
+ {
+ return;
+ }
+
+ Thread.Sleep(100);
+ }
+
+ Assert.Fail($"The mount did not find the file in {directory} clean. Last cone events:\n{this.LastConeEvents()}");
+ }
+
+ ///
+ /// Wait until the mount log has an apply after that skipped a
+ /// clean file, and whose skip reasons contain . The check that
+ /// makes the apply pending can come after a Git command, so run Git until it comes.
+ ///
+ private void WaitForAnApplyThatSkipped(DateTimeOffset since, string reason)
+ {
+ DateTime end = DateTime.UtcNow + WaitTime;
+ while (DateTime.UtcNow < end)
+ {
+ if (this.ConeEvents(since).Any(line => line.Contains("] ConeApply ") && line.Contains("\"DehydrateSkipped\":\"") && line.Contains(reason)))
+ {
+ return;
+ }
+
+ Thread.Sleep(250);
+ this.GitShouldSucceed("status --porcelain");
+ }
+
+ Assert.Fail($"No apply skipped a clean file for '{reason}'. Last cone events:\n{this.LastConeEvents()}");
+ }
+
+ private List ConeEvents(DateTimeOffset since)
+ {
+ List events = new List();
+ foreach (string line in this.ConeEventLines())
+ {
+ // "[2026-11-17 14:25:56.6848 -08:00] ConeReconcile {...}"
+ int close = line.IndexOf(']');
+ if (line.StartsWith("[") && close > 0 &&
+ DateTimeOffset.TryParse(line.Substring(1, close - 1), System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTimeOffset time) &&
+ time >= since)
+ {
+ events.Add(line);
+ }
+ }
+
+ return events;
+ }
+
+ private string LastConeEvents()
+ {
+ List lines = this.ConeEventLines();
+ return string.Join("\n", lines.Skip(Math.Max(0, lines.Count - 12)));
+ }
+
+ private List ConeEventLines()
+ {
+ string logs = Path.Combine(this.Enlistment.DotGVFSRoot, "logs");
+ string log = Directory.Exists(logs)
+ ? Directory.GetFiles(logs, "*mount_process*").OrderBy(File.GetLastWriteTimeUtc).LastOrDefault()
+ : null;
+ List lines = new List();
+ if (log == null)
+ {
+ return lines;
+ }
+
+ using (StreamReader reader = new StreamReader(new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)))
+ {
+ string line;
+ while ((line = reader.ReadLine()) != null)
+ {
+ if (line.Contains("] Cone") || line.Contains("TryDehydrateCleanFile"))
+ {
+ lines.Add(line);
+ }
+ }
+
+ return lines;
+ }
+ }
+
+ private void GitShouldSeeTheEdit(string file, string editText)
+ {
+ this.GitShouldSucceed("status --porcelain").ShouldContain(" M " + file);
+ this.GitShouldSucceed("diff -- " + file).ShouldContain(editText);
+ GVFSHelpers.ModifiedPathsShouldContain(this.Enlistment, this.fileSystem, file);
+ this.GitShouldSucceed("checkout -- " + file);
+ }
+
+ private bool IsPlaceholder(string file)
+ {
+ return ((int)File.GetAttributes(this.Enlistment.GetVirtualPathTo(file)) & FileSystemShouldExtensions.FileAttributeRecallOnDataAccess) != 0;
+ }
+
+ private void AppendTo(string file)
+ {
+ File.AppendAllText(this.Enlistment.GetVirtualPathTo(file), Environment.NewLine + "edited outside the cone" + Environment.NewLine);
+ }
+
+ ///
+ /// Commit a new root file with on top of
+ /// with a separate index and without the virtual file system,
+ /// so that the working tree, the index, and the cone do not change.
+ ///
+ private string CommitWithoutTheWorkingTree(string parent, string content)
+ {
+ string indexFile = Path.Combine(this.Enlistment.EnlistmentRoot, "commit-" + Guid.NewGuid().ToString("N") + ".index");
+ string plainGit = BypassGVFS + " -c core.sparseCheckout=false -c index.sparse=false";
+ Dictionary environment = new Dictionary { { "GIT_INDEX_FILE", indexFile } };
+ try
+ {
+ this.PlainGitShouldSucceed($"{plainGit} read-tree {parent}", environment);
+ string blob;
+ using (MemoryStream input = new MemoryStream(Encoding.UTF8.GetBytes(content + "\n")))
+ {
+ blob = this.PlainGitShouldSucceed("hash-object -w --no-filters --stdin", environment, input).Trim();
+ }
+
+ this.PlainGitShouldSucceed($"{plainGit} update-index --add --cacheinfo 100644,{blob},dehydrate-merge-conflict.txt", environment);
+ string tree = this.PlainGitShouldSucceed($"{plainGit} write-tree", environment).Trim();
+ return this.PlainGitShouldSucceed($"{plainGit} commit-tree {tree} -p {parent} -m \"Commit beside the working tree\"", environment).Trim();
+ }
+ finally
+ {
+ File.Delete(indexFile);
+ }
+ }
+
+ private string PlainGitShouldSucceed(string command, Dictionary environment, Stream input = null)
+ {
+ ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command, environment, input);
+ result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}");
+ return result.Output;
+ }
+ }
+}
diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs
index 5eb4a16be7..21c3e5a4c5 100644
--- a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs
+++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs
@@ -133,6 +133,23 @@ protected string ReadConeFile()
}
}
+ ///
+ /// Read the entry count from the header of the index file on disk. A sparse-directory
+ /// entry counts as one entry. ls-files cannot show the count on disk, because Git
+ /// collapses a full index in memory when it reads it with index.sparse true.
+ ///
+ protected int IndexHeaderEntryCount()
+ {
+ // Bytes 8 to 11 of the index file are its entry count (big-endian).
+ byte[] header = new byte[12];
+ using (FileStream stream = new FileStream(this.Enlistment.GetDotGitPath("index"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
+ {
+ stream.ReadExactly(header, 0, header.Length);
+ }
+
+ return (header[8] << 24) | (header[9] << 16) | (header[10] << 8) | header[11];
+ }
+
protected ProcessResult GitWithTrace(string command, out string trace2EventFile, bool takeOptionalLocks = false)
{
string traceFile = Path.Combine(this.Enlistment.EnlistmentRoot, $"cone-trace2-{System.Threading.Interlocked.Increment(ref this.traceCount)}.json");
diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexUnstageTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexUnstageTests.cs
new file mode 100644
index 0000000000..91435c4d00
--- /dev/null
+++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexUnstageTests.cs
@@ -0,0 +1,170 @@
+using GVFS.FunctionalTests.Tools;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+
+namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture
+{
+ ///
+ /// Functional tests for files that "git reset --soft" stages outside the sparse-index cone.
+ /// No file system write stages them, so only the unstage preparation of the hook can bring
+ /// them into the cone before Git unstages them.
+ ///
+ [TestFixture]
+ public class AutoSparseIndexUnstageTests : AutoSparseIndexTestsBase
+ {
+ private const string ConeManagementPrefix = "gvfs cone-management:";
+ private const string ChangedLine = "changed by a commit";
+
+ // Files of HEAD, each in a different two-level directory outside the root-only cone
+ private Queue unusedFiles;
+ private int branchCount;
+
+ [OneTimeSetUp]
+ public void SelectFiles()
+ {
+ this.unusedFiles = new Queue(this.GroupByTwoLevelDirectory().Select(group => group.First()));
+ this.unusedFiles.Count.ShouldBeAtLeast(4, "HEAD has too few directories that are two levels deep");
+ }
+
+ [TestCase]
+ public void RestoreStagedPathKeepsTheChangeVisible()
+ {
+ this.UnstageAfterSoftResetShouldKeepTheChange(file => "restore --staged -- " + file);
+ }
+
+ [TestCase]
+ public void RestoreStagedDotKeepsTheChangeVisible()
+ {
+ this.UnstageAfterSoftResetShouldKeepTheChange(file => "restore --staged .");
+ }
+
+ [TestCase]
+ public void ResetPathKeepsTheChangeVisible()
+ {
+ this.UnstageAfterSoftResetShouldKeepTheChange(file => "reset --quiet -- " + file);
+ }
+
+ [TestCase]
+ public void ResetKeepsTheChangeVisible()
+ {
+ this.UnstageAfterSoftResetShouldKeepTheChange(file => "reset --quiet");
+ }
+
+ [TestCase("restore --staged -- ")]
+ [TestCase("reset --quiet -- ")]
+ public void UnstageKeepsUnstagedEditsOfANewFile(string unstageCommand)
+ {
+ // The unstage preparation writes the staged content of an added file that has no
+ // placeholder. It must not overwrite a file that the user created and edited again.
+ string file = $"unstage-new-file-{this.branchCount++}.txt";
+ string path = this.Enlistment.GetVirtualPathTo(file);
+ try
+ {
+ File.WriteAllText(path, "staged\n");
+ this.GitShouldSucceed("add -- " + file);
+ File.AppendAllText(path, "not staged\n");
+
+ this.GitShouldSucceed(unstageCommand + file);
+
+ File.ReadAllText(path).ShouldEqual("staged\nnot staged\n");
+ this.GitShouldSucceed("status --porcelain -- " + file).ShouldContain("?? " + file);
+ }
+ finally
+ {
+ GitProcess.InvokeProcess(this.Enlistment.RepoRoot, "reset --quiet -- " + file);
+ File.Delete(path);
+ }
+ }
+
+ ///
+ /// Check out a commit that changes a file outside the cone, without a write to that file
+ /// in the working tree. Then "git reset --soft HEAD~1" stages the change, and
+ /// unstages it. The change must stay in the working
+ /// tree, and Git must report it.
+ ///
+ private void UnstageAfterSoftResetShouldKeepTheChange(Func getUnstageCommand)
+ {
+ string file = this.unusedFiles.Dequeue();
+ try
+ {
+ this.UnstageAfterSoftResetShouldKeepTheChange(file, getUnstageCommand(file));
+ }
+ finally
+ {
+ // Leave a clean working tree and index for the next test, also after a failure.
+ GitProcess.InvokeProcess(this.Enlistment.RepoRoot, "reset --hard --quiet");
+ }
+
+ this.GitShouldSucceed("status --porcelain").ShouldNotContain(ignoreCase: true, file);
+ }
+
+ private void UnstageAfterSoftResetShouldKeepTheChange(string file, string unstageCommand)
+ {
+ this.CheckOutACommitThatChanges(file);
+ this.SparseDirectoryEntries().ShouldBeNonEmpty();
+ ConeLines(this.ReadConeFile())
+ .ShouldNotContain(line => line.StartsWith("/" + TwoLevelDirectory(file) + "/", StringComparison.OrdinalIgnoreCase));
+
+ ProcessResult softReset = this.GitWithTrace("reset --soft HEAD~1", out string softResetTrace);
+ softReset.ExitCode.ShouldEqual(0, softReset.Errors);
+ CountFullIndexExpansions(softResetTrace).ShouldEqual(0, "reset --soft expanded the whole index");
+ this.GitShouldSucceed("diff --cached --name-only").ShouldContain(file);
+
+ ProcessResult unstage = this.GitWithTrace(unstageCommand, out string unstageTrace);
+ unstage.ExitCode.ShouldEqual(0, $"git {unstageCommand} failed: {unstage.Errors}");
+ unstage.Errors.ShouldNotContain(ignoreCase: false, ConeManagementPrefix + " widen not applied", ConeManagementPrefix + " apply");
+ CountFullIndexExpansions(unstageTrace).ShouldEqual(0, $"git {unstageCommand} expanded the whole index: {unstage.Errors}");
+
+ this.GitShouldSucceed("diff --cached --name-only").ShouldNotContain(ignoreCase: true, file);
+ ProcessResult status = this.GitWithTrace("status --porcelain", out string statusTrace);
+ status.ExitCode.ShouldEqual(0, status.Errors);
+ status.Output.ShouldContain(" M " + file);
+ CountFullIndexExpansions(statusTrace).ShouldEqual(0, "status expanded the whole index");
+ this.GitShouldSucceed("ls-files -v -- " + file).ShouldContain("H " + file);
+ File.ReadAllText(this.Enlistment.GetVirtualPathTo(file)).ShouldContain(ChangedLine);
+ this.SparseDirectoryEntries().ShouldBeNonEmpty();
+ }
+
+ ///
+ /// Create a commit on top of HEAD that adds to
+ /// , and check it out. The commit is made in a temporary index, so
+ /// the working tree and the modified paths do not see the change before the checkout.
+ ///
+ private void CheckOutACommitThatChanges(string file)
+ {
+ string changedContent = this.GitShouldSucceed("cat-file blob HEAD:" + file) + ChangedLine + "\n";
+ ProcessResult hash = GitProcess.InvokeProcess(
+ this.Enlistment.RepoRoot,
+ "hash-object -w --stdin",
+ inputStream: new MemoryStream(Encoding.UTF8.GetBytes(changedContent)));
+ hash.ExitCode.ShouldEqual(0, hash.Errors);
+ string blob = hash.Output.Trim();
+
+ string temporaryIndex = Path.Combine(this.Enlistment.EnlistmentRoot, $"unstage-test-index-{this.branchCount}");
+ Dictionary environment = new Dictionary { { "GIT_INDEX_FILE", temporaryIndex } };
+ string plainIndex = $"{BypassGVFS} -c index.sparse=false -c core.sparseCheckout=false";
+ this.GitShouldSucceed(environment, $"{plainIndex} read-tree HEAD");
+ this.GitShouldSucceed(environment, $"{plainIndex} update-index --cacheinfo 100644,{blob},{file}");
+ string tree = this.GitShouldSucceed(environment, $"{plainIndex} write-tree").Trim();
+ File.Delete(temporaryIndex);
+
+ string commit = this.GitShouldSucceed($"commit-tree {tree} -p HEAD -m \"Change {file}\"").Trim();
+ string branch = $"tests/functional/unstage-{this.branchCount++}";
+ this.GitShouldSucceed($"branch {branch} {commit}");
+ this.GitShouldSucceed("checkout " + branch);
+ this.GitShouldSucceed("status --porcelain").ShouldNotContain(ignoreCase: true, file);
+ }
+
+ private string GitShouldSucceed(Dictionary environment, string command)
+ {
+ ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command, environment);
+ result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}");
+ return result.Output;
+ }
+ }
+}
diff --git a/GVFS/GVFS.FunctionalTests/Tools/GVFSHelpers.cs b/GVFS/GVFS.FunctionalTests/Tools/GVFSHelpers.cs
index dd485f0d77..cb5bb8b604 100644
--- a/GVFS/GVFS.FunctionalTests/Tools/GVFSHelpers.cs
+++ b/GVFS/GVFS.FunctionalTests/Tools/GVFSHelpers.cs
@@ -262,7 +262,7 @@ private static string GetModifiedPathsContents(GVFSFunctionalTestEnlistment enli
/// does on mount to
/// observe a consistent state.
///
- private static HashSet GetCurrentModifiedPaths(GVFSFunctionalTestEnlistment enlistment, FileSystemRunner fileSystem)
+ public static HashSet GetCurrentModifiedPaths(GVFSFunctionalTestEnlistment enlistment, FileSystemRunner fileSystem)
{
string contents = GetModifiedPathsContents(enlistment, fileSystem);
HashSet paths = new HashSet(FileSystemHelpers.PathComparer);
diff --git a/GVFS/GVFS.Hooks/ConeManagementHook.cs b/GVFS/GVFS.Hooks/ConeManagementHook.cs
index f8194b787c..46545aa6bd 100644
--- a/GVFS/GVFS.Hooks/ConeManagementHook.cs
+++ b/GVFS/GVFS.Hooks/ConeManagementHook.cs
@@ -175,33 +175,60 @@ internal static string GetCommandId(string[] args)
return string.Empty;
}
+ ///
+ /// Return true when GVFS manages a sparse-index cone for this worktree: the cone file is in
+ /// cone mode, and gvfs.auto-sparse-index is true. A widen and a narrow use the same
+ /// checks.
+ ///
+ public bool IsSparseIndexConeManaged()
+ {
+ return this.GetUnmanagedOutcome(out _, out _) == null;
+ }
+
private static bool IsStash(ParsedGitCommand parsed)
{
return string.Equals(parsed.Command, StashCommand, StringComparison.Ordinal);
}
- private ConeRequestOutcome Widen(string[] args, int waitBudgetMs, int replyCeilingMs)
+ ///
+ /// Return null when GVFS manages a sparse-index cone, or the outcome that ends a request
+ /// when it does not.
+ ///
+ private ConeRequestOutcome? GetUnmanagedOutcome(out string coneFileContent, out bool ignoreCase)
{
- ParsedGitCommand parsed = GitPathspecParser.ParseHookArgs(args);
- if (!parsed.NamesPaths)
- {
- return ConeRequestOutcome.NoPathsNamed;
- }
+ ignoreCase = false;
// Check the cone file before the config. Git can use a sparse index only in cone
// mode, and a file read costs much less than the repository open that a config
// read needs. GVFS does not write a cone-mode file unless the feature is on.
- string coneFileContent = this.readConeFile();
+ coneFileContent = this.readConeFile();
if (!ConeCoverage.HasConeHeader(coneFileContent))
{
return ConeRequestOutcome.NoConeFile;
}
- if (!this.readConfig(out bool ignoreCase))
+ if (!this.readConfig(out ignoreCase))
{
return ConeRequestOutcome.FeatureDisabled;
}
+ return null;
+ }
+
+ private ConeRequestOutcome Widen(string[] args, int waitBudgetMs, int replyCeilingMs)
+ {
+ ParsedGitCommand parsed = GitPathspecParser.ParseHookArgs(args);
+ if (!parsed.NamesPaths)
+ {
+ return ConeRequestOutcome.NoPathsNamed;
+ }
+
+ ConeRequestOutcome? unmanaged = this.GetUnmanagedOutcome(out string coneFileContent, out bool ignoreCase);
+ if (unmanaged != null)
+ {
+ return unmanaged.Value;
+ }
+
// Measured on a large repository: git stash push with a pathspec still expanded the
// whole index after a widen, and the widen made the command slower.
if (IsStash(parsed))
@@ -264,14 +291,10 @@ private ConeRequestOutcome Narrow(string[] args, int waitBudgetMs)
return ConeRequestOutcome.NoPathsNamed;
}
- if (!ConeCoverage.HasConeHeader(this.readConeFile()))
+ ConeRequestOutcome? unmanaged = this.GetUnmanagedOutcome(out _, out _);
+ if (unmanaged != null)
{
- return ConeRequestOutcome.NoConeFile;
- }
-
- if (!this.readConfig(out _))
- {
- return ConeRequestOutcome.FeatureDisabled;
+ return unmanaged.Value;
}
if (IsStash(parsed))
diff --git a/GVFS/GVFS.Hooks/PreCommandConeRequests.cs b/GVFS/GVFS.Hooks/PreCommandConeRequests.cs
new file mode 100644
index 0000000000..be52aa7a9d
--- /dev/null
+++ b/GVFS/GVFS.Hooks/PreCommandConeRequests.cs
@@ -0,0 +1,101 @@
+using System;
+
+namespace GVFS.Hooks
+{
+ ///
+ /// Sends the requests of the pre-command hook that prepare the index before Git reads it:
+ /// the cone widen, the unstage preparation, and the apply of a pending cone change.
+ ///
+ ///
+ ///
+ /// The order matters for an unstage command (for example git restore --staged or
+ /// git reset). The mount finds the staged files with git diff --cached. Git
+ /// does not match a pathspec with a path inside a sparse-directory entry, so before the
+ /// widen that query finds no staged file for a named path outside the cone. Thus the widen
+ /// comes first.
+ ///
+ ///
+ /// The unstage preparation adds the staged files to the modified paths. When the cone does
+ /// not include one of them (for example for git restore --staged ., which names no
+ /// path that the widen can use), the mount makes a cone change pending. The apply then
+ /// expands its directory before Git runs. Otherwise Git keeps the file inside a
+ /// sparse-directory entry, the file keeps skip-worktree, and Git does not report the
+ /// unstaged change.
+ ///
+ ///
+ /// For other commands, a failed request only makes Git slower, so Git always runs. For an
+ /// unstage command, a widen that timed out or an apply that failed can hide the unstaged
+ /// change, so the hook must stop the command (see ).
+ ///
+ ///
+ /// All dependencies are delegates, so that unit tests can check the order without a mount.
+ ///
+ ///
+ internal static class PreCommandConeRequests
+ {
+ /// True when the command unstages files.
+ /// Returns true when the mount's pending file exists.
+ /// Asks the mount to widen the cone for the named paths.
+ /// Asks the mount to add the staged files to the modified paths.
+ /// Asks the mount to apply the pending cone change.
+ ///
+ /// The request that makes an unstage command unsafe, or null when Git can run. Always
+ /// null for other commands.
+ ///
+ public static string Send(
+ bool isUnstage,
+ Func isConeChangePending,
+ Func sendWiden,
+ Action sendPrepareForUnstage,
+ Func applyPendingConeChange)
+ {
+ ArgumentNullException.ThrowIfNull(isConeChangePending);
+ ArgumentNullException.ThrowIfNull(sendWiden);
+ ArgumentNullException.ThrowIfNull(sendPrepareForUnstage);
+ ArgumentNullException.ThrowIfNull(applyPendingConeChange);
+
+ // Check before the widen: a widen that the mount applied also applied the pending change.
+ bool pending = isConeChangePending();
+ ConeRequestOutcome widenOutcome = sendWiden();
+
+ if (!isUnstage)
+ {
+ if (pending && widenOutcome != ConeRequestOutcome.Applied)
+ {
+ applyPendingConeChange();
+ }
+
+ return null;
+ }
+
+ // After a timeout, the mount can still change the cone and the index. The staged-file
+ // query and Git can then see an index that does not have the named paths yet.
+ if (widenOutcome == ConeRequestOutcome.TimedOut)
+ {
+ return "widen: " + widenOutcome;
+ }
+
+ sendPrepareForUnstage();
+
+ // The preparation can make a cone change pending. The mount deletes the pending file
+ // when it applies a change, so after an applied widen the file exists only for a
+ // change that the preparation made.
+ if (!isConeChangePending())
+ {
+ return null;
+ }
+
+ ConeRequestOutcome applyOutcome = applyPendingConeChange();
+ switch (applyOutcome)
+ {
+ case ConeRequestOutcome.Applied:
+ case ConeRequestOutcome.NothingPending:
+ case ConeRequestOutcome.FeatureDisabled:
+ return null;
+
+ default:
+ return "apply: " + applyOutcome;
+ }
+ }
+ }
+}
diff --git a/GVFS/GVFS.Hooks/Program.ConeManagement.cs b/GVFS/GVFS.Hooks/Program.ConeManagement.cs
index dd1cc6d4e2..334570bf9d 100644
--- a/GVFS/GVFS.Hooks/Program.ConeManagement.cs
+++ b/GVFS/GVFS.Hooks/Program.ConeManagement.cs
@@ -39,18 +39,13 @@ private static ConeRequestOutcome TrySendConeWiden(string[] args)
///
/// Before Git reads the index, make sure that the cone includes every working-tree change
- /// that the mount saw. A widen that the mount applied already includes them.
+ /// that the mount saw. See for when the hook calls this.
///
- private static void TryApplyPendingConeChange(string[] args, bool wasPending, ConeRequestOutcome widenOutcome)
+ private static ConeRequestOutcome TryApplyPendingConeChange(string[] args)
{
- if (!wasPending || widenOutcome == ConeRequestOutcome.Applied)
- {
- return;
- }
-
try
{
- new PendingConeChangeHook(IsConeChangePending, DeleteConeChangePendingFile, () => new NamedPipeClient(enlistmentPipename), TraceConeDiagnostic)
+ return new PendingConeChangeHook(IsConeChangePending, DeleteConeChangePendingFile, () => new NamedPipeClient(enlistmentPipename), TraceConeDiagnostic)
.TryApply(
args,
commandHoldsGVFSLock,
@@ -64,6 +59,7 @@ private static void TryApplyPendingConeChange(string[] args, bool wasPending, Co
catch (Exception e)
{
TraceConeDiagnostic($"apply failed: {e.Message}");
+ return ConeRequestOutcome.Failed;
}
}
@@ -117,6 +113,23 @@ private static void TrySendConeNarrow(string[] args)
}
}
+ ///
+ /// Return true when GVFS manages a sparse-index cone for this worktree. See
+ /// .
+ ///
+ private static bool IsSparseIndexConeManaged()
+ {
+ try
+ {
+ return CreateConeManagementHook().IsSparseIndexConeManaged();
+ }
+ catch (Exception e)
+ {
+ TraceConeDiagnostic($"cannot check for a sparse-index cone: {e.Message}");
+ return false;
+ }
+ }
+
private static ConeManagementHook CreateConeManagementHook()
{
return new ConeManagementHook(
diff --git a/GVFS/GVFS.Hooks/Program.Unstage.cs b/GVFS/GVFS.Hooks/Program.Unstage.cs
index bebe9b9a97..60818cd53e 100644
--- a/GVFS/GVFS.Hooks/Program.Unstage.cs
+++ b/GVFS/GVFS.Hooks/Program.Unstage.cs
@@ -5,7 +5,7 @@ namespace GVFS.Hooks
{
///
/// Partial class for unstage-related pre-command handling.
- /// Detects "restore --staged" and "checkout HEAD --" operations and sends
+ /// Detects "restore --staged", "checkout HEAD --", and mixed "reset" operations, and sends
/// a PrepareForUnstage message to the GVFS mount process so it can add
/// staged files to ModifiedPaths before git clears skip-worktree.
///
@@ -98,7 +98,7 @@ private static void SendPrepareForUnstageMessage(string command, string[] args)
"",
"To resolve:",
" 1. Run 'gvfs unmount' and 'gvfs mount' to reset the GVFS state",
- " 2. Retry the restore --staged command",
+ " 2. Retry the unstage command",
"If the problem persists, run 'gvfs repair' or re-clone the enlistment.");
}
}
diff --git a/GVFS/GVFS.Hooks/Program.cs b/GVFS/GVFS.Hooks/Program.cs
index 104a3f1296..773a1c56f5 100644
--- a/GVFS/GVFS.Hooks/Program.cs
+++ b/GVFS/GVFS.Hooks/Program.cs
@@ -111,6 +111,7 @@ public static void Main(string[] args)
private static void RunPreCommands(string[] args)
{
string command = GetGitCommand(args);
+ bool isUnstage = false;
switch (command)
{
case "fetch":
@@ -127,20 +128,29 @@ private static void RunPreCommands(string[] args)
break;
case "restore":
case "checkout":
- if (UnstageCommandParser.IsUnstageOperation(command, args))
- {
- SendPrepareForUnstageMessage(command, args);
- }
+ case "reset":
+ isUnstage = UnstageCommandParser.ShouldPrepareForUnstage(command, args, IsSparseIndexConeManaged);
break;
case "worktree":
RunWorktreePreCommand(args);
break;
}
- // Check before the widen: a widen that the mount applies also applies the pending change.
- bool coneChangePending = IsConeChangePending();
- ConeRequestOutcome widenOutcome = TrySendConeWiden(args);
- TryApplyPendingConeChange(args, coneChangePending, widenOutcome);
+ string unsafeRequest = PreCommandConeRequests.Send(
+ isUnstage,
+ IsConeChangePending,
+ () => TrySendConeWiden(args),
+ () => SendPrepareForUnstageMessage(command, args),
+ () => TryApplyPendingConeChange(args));
+
+ if (unsafeRequest != null)
+ {
+ ExitWithError(
+ "VFS for Git could not add the staged files to the sparse-index cone (" + unsafeRequest + ").",
+ "Without them in the cone, Git would not show the changes that this command unstages.",
+ "",
+ "Run the command again. If it fails again, run 'gvfs unmount' and 'gvfs mount', and then run it again.");
+ }
}
private static bool ArgsBlockHydrationStatus(string[] args)
diff --git a/GVFS/GVFS.Hooks/UnstageCommandParser.cs b/GVFS/GVFS.Hooks/UnstageCommandParser.cs
index d03761821c..7460825823 100644
--- a/GVFS/GVFS.Hooks/UnstageCommandParser.cs
+++ b/GVFS/GVFS.Hooks/UnstageCommandParser.cs
@@ -30,13 +30,52 @@ public class PathspecResult
public bool Failed { get; set; }
}
+ ///
+ /// Return true when the pre-command hook must send PrepareForUnstage for this command.
+ ///
+ ///
+ /// With a full index, Git prepares the files of a mixed reset itself (it clears
+ /// skip-worktree and writes missing files under a virtual file system). With a sparse
+ /// index, Git can do that only for a path that has its own index entry, so the cone must
+ /// include the staged files first. Thus a reset needs the preparation only when GVFS
+ /// manages a sparse-index cone. A reset whose pathspecs the hook cannot read (for example
+ /// --pathspec-from-file=-) runs without the preparation, as before.
+ ///
+ /// Returns true when GVFS manages a sparse-index cone.
+ public static bool ShouldPrepareForUnstage(string command, string[] args, Func isSparseIndexConeManaged)
+ {
+ if (!IsUnstageOperation(command, args))
+ {
+ return false;
+ }
+
+ if (command != "reset")
+ {
+ return true;
+ }
+
+ return !GetRestorePathspec(command, args).Failed && isSparseIndexConeManaged();
+ }
+
///
/// Detects whether the git command is an unstage operation that may need
/// special handling for VFS projections.
- /// Matches: "restore --staged", "restore -S", "checkout HEAD --"
+ /// Matches: "restore --staged", "restore -S", "checkout HEAD --", and a mixed
+ /// "reset" (not --soft, --hard, --merge, --keep, or the interactive --patch)
///
public static bool IsUnstageOperation(string command, string[] args)
{
+ if (command == "reset")
+ {
+ return !args.Any(arg =>
+ arg == "--soft" ||
+ arg == "--hard" ||
+ arg == "--merge" ||
+ arg == "--keep" ||
+ arg == "--patch" ||
+ arg == "-p");
+ }
+
if (command == "restore")
{
return args.Any(arg =>
@@ -63,13 +102,17 @@ public static bool IsUnstageOperation(string command, string[] args)
}
///
- /// Extracts pathspec arguments from a restore/checkout unstage command.
+ /// Extracts pathspec arguments from a restore/checkout/reset unstage command.
/// Returns a containing either inline pathspecs,
/// a --pathspec-from-file reference, or a failure indicator.
///
/// When --pathspec-from-file is specified, the file path is returned so the
/// caller can forward it through IPC to the mount process, which passes it
/// to git diff --cached --pathspec-from-file.
+ ///
+ /// For reset, the argument before "--" is the tree-ish. Without "--", only
+ /// "HEAD" is taken as the tree-ish, and any other argument is a pathspec. An
+ /// extra pathspec only adds staged files to ModifiedPaths.
///
public static PathspecResult GetRestorePathspec(string command, string[] args)
{
@@ -78,6 +121,8 @@ public static PathspecResult GetRestorePathspec(string command, string[] args)
bool pastDashDash = false;
bool skipNext = false;
bool isCheckout = command == "checkout";
+ bool isReset = command == "reset";
+ bool resetHasDashDash = isReset && args.Skip(2).Contains("--");
// For checkout, the first non-option arg before -- is the tree-ish (e.g. HEAD),
// not a pathspec. Track whether we've consumed it.
@@ -136,7 +181,7 @@ public static PathspecResult GetRestorePathspec(string command, string[] args)
if (!pastDashDash && arg.StartsWith("-"))
{
// For restore: --source and -s take a following argument
- if (!isCheckout &&
+ if (command == "restore" &&
(arg == "--source" || arg == "-s"))
{
skipNext = true;
@@ -152,6 +197,13 @@ public static PathspecResult GetRestorePathspec(string command, string[] args)
continue;
}
+ if (isReset && !pastDashDash && !treeishConsumed &&
+ (resetHasDashDash || arg == "HEAD"))
+ {
+ treeishConsumed = true;
+ continue;
+ }
+
paths.Add(arg);
}
diff --git a/GVFS/GVFS.Mount/InProcessMount.cs b/GVFS/GVFS.Mount/InProcessMount.cs
index 288225f570..376c299645 100644
--- a/GVFS/GVFS.Mount/InProcessMount.cs
+++ b/GVFS/GVFS.Mount/InProcessMount.cs
@@ -91,6 +91,10 @@ public class InProcessMount
// a folder dehydrate request
private volatile bool resetForDehydrateInProgress;
+ // Above zero from the start to the end of a folder dehydrate request. The cone manager
+ // then does not return clean files to placeholders.
+ private int folderDehydrateCount;
+
public InProcessMount(ITracer tracer, GVFSEnlistment enlistment, string mountId, string primaryEnlistmentId, CacheServerInfo cacheServer, RetryConfig retryConfig, GitStatusCacheConfig gitStatusCacheConfig, bool showDebugWindow)
{
this.tracer = tracer;
@@ -934,7 +938,15 @@ private void HandleRequest(ITracer tracer, string request, NamedPipeServer.Conne
break;
case NamedPipeMessages.DehydrateFolders.Dehydrate:
- this.HandleDehydrateFolders(message, connection);
+ Interlocked.Increment(ref this.folderDehydrateCount);
+ try
+ {
+ this.HandleDehydrateFolders(message, connection);
+ }
+ finally
+ {
+ Interlocked.Decrement(ref this.folderDehydrateCount);
+ }
break;
case NamedPipeMessages.PrefetchCommits.Request:
@@ -1063,6 +1075,10 @@ private void HandleDehydrateFolders(NamedPipeMessages.Message message, NamedPipe
resetIndexMetadata.Add(nameof(refreshIndexResult.Errors), refreshIndexResult.Errors);
resetIndexMetadata.Add(TracingConstants.MessageKey.InfoMessage, $"{nameof(this.HandleDehydrateFolders)}: Reset git index");
this.tracer.RelatedEvent(EventLevel.Informational, $"{nameof(this.HandleDehydrateFolders)}_ResetIndex", resetIndexMetadata);
+
+ // The reset widened the sparse-index cone for the folders. The next Git command
+ // collapses them again.
+ this.coneManager?.RequestApply();
}
else
{
@@ -1231,9 +1247,10 @@ private void HandlePostIndexChangedRequest(NamedPipeMessages.Message message, Na
///
/// Handles a request to prepare for an unstage operation (e.g., restore --staged).
- /// Finds index entries that are staged (not in HEAD) with skip-worktree set and adds
- /// them to ModifiedPaths so that git will clear skip-worktree and process them.
- /// Also forces a projection update to fix stale placeholders for modified/deleted files.
+ /// Runs git diff --cached for the request's pathspecs and adds the staged files to
+ /// ModifiedPaths so that git will clear skip-worktree and process them. With a
+ /// sparse index, a staged file that the cone does not include makes a cone change
+ /// pending, which the hook applies before git runs.
///
private void HandlePrepareForUnstageRequest(NamedPipeMessages.Message message, NamedPipeServer.Connection connection)
{
@@ -1867,7 +1884,7 @@ private AutoSparseIndexConeManager CreateConeManagerIfEnabled()
this.context.FileSystem,
sparseCheckoutPath,
ignoreCase,
- new MountConeManagerEnvironment(this.context, this.fileSystemCallbacks, sparseCheckoutPath));
+ new MountConeManagerEnvironment(this.context, this.fileSystemCallbacks, sparseCheckoutPath, () => Volatile.Read(ref this.folderDehydrateCount) > 0));
}
private void ValidateGitVersion()
diff --git a/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs b/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs
index d6f200fcb7..e6182a9f5b 100644
--- a/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs
+++ b/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs
@@ -17,21 +17,36 @@ internal class MountConeManagerEnvironment : IConeManagerEnvironment
// The background check stops Git after this long. The cone then keeps the files.
private const int ListPathsTimeoutMs = 2 * 60 * 1000;
+ // The files and folders that Git keeps in its git directory while a merge, rebase,
+ // cherry-pick, or revert is in progress, also while it waits for the user.
+ private static readonly string[] InProgressOperationMarkers =
+ {
+ "MERGE_HEAD",
+ "CHERRY_PICK_HEAD",
+ "REVERT_HEAD",
+ "rebase-merge",
+ "rebase-apply",
+ "sequencer",
+ };
+
private readonly GVFSContext context;
private readonly FileSystemCallbacks fileSystemCallbacks;
private readonly string coneFileLockPath;
private readonly string pendingFilePath;
+ private readonly Func isFolderDehydrateInProgress;
- public MountConeManagerEnvironment(GVFSContext context, FileSystemCallbacks fileSystemCallbacks, string sparseCheckoutPath)
+ public MountConeManagerEnvironment(GVFSContext context, FileSystemCallbacks fileSystemCallbacks, string sparseCheckoutPath, Func isFolderDehydrateInProgress)
{
ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(fileSystemCallbacks);
ArgumentNullException.ThrowIfNull(sparseCheckoutPath);
+ ArgumentNullException.ThrowIfNull(isFolderDehydrateInProgress);
this.context = context;
this.fileSystemCallbacks = fileSystemCallbacks;
this.coneFileLockPath = sparseCheckoutPath + GVFSConstants.DotGit.LockExtension;
this.pendingFilePath = GetPendingFilePath(context.Enlistment);
+ this.isFolderDehydrateInProgress = isFolderDehydrateInProgress;
}
///
@@ -182,10 +197,11 @@ public long GetRepositoryStamp()
try
{
// "git reset --soft" moves HEAD without a write to the index, but Git logs the
- // move in the HEAD reflog.
+ // move in the HEAD reflog. "git symbolic-ref" changes the HEAD file.
long index = File.GetLastWriteTimeUtc(this.context.Enlistment.GitIndexPath).Ticks;
long headLog = File.GetLastWriteTimeUtc(this.context.Enlistment.GitHeadLogPath).Ticks;
- return unchecked((index * 31) + headLog);
+ long head = File.GetLastWriteTimeUtc(Path.Combine(this.context.Enlistment.DotGitRoot, GVFSConstants.DotGit.HeadName)).Ticks;
+ return unchecked((((index * 31) + headLog) * 31) + head);
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
{
@@ -193,5 +209,71 @@ public long GetRepositoryStamp()
return DateTime.UtcNow.Ticks;
}
}
+
+ public string GetDehydrateBlocker()
+ {
+ if (this.isFolderDehydrateInProgress())
+ {
+ return "FolderDehydrate";
+ }
+
+ // Git keeps these in the git directory of the worktree while the operation waits
+ // for the user. The index can then have conflicts or a state that the user resolves.
+ string gitDirectory = Path.GetDirectoryName(this.context.Enlistment.GitIndexPath);
+ foreach (string name in InProgressOperationMarkers)
+ {
+ if (this.context.FileSystem.FileExists(Path.Combine(gitDirectory, name)) ||
+ this.context.FileSystem.DirectoryExists(Path.Combine(gitDirectory, name)))
+ {
+ return name;
+ }
+ }
+
+ return null;
+ }
+
+ public bool TryGetBlobsThatMatchHead(IReadOnlyList gitPaths, int timeoutMs, out IReadOnlyDictionary blobs, out IReadOnlyCollection notInIndex, out string error)
+ {
+ StringComparer pathComparer = GVFSPlatform.Instance.Constants.PathComparer;
+ Dictionary matching = new Dictionary(pathComparer);
+ List missing = new List();
+ GitProcess.Result result = new GitProcess(this.context.Enlistment).GetBlobsThatMatchHead(gitPaths, pathComparer, matching, missing, timeoutMs);
+ if (result.ExitCodeIsFailure)
+ {
+ blobs = null;
+ notInIndex = null;
+ error = result.Errors;
+ return false;
+ }
+
+ blobs = matching;
+ notInIndex = missing;
+ error = null;
+ return true;
+ }
+
+ public CleanFileDehydrateResult TryDehydrateCleanFile(string gitPath, HeadBlob blob)
+ {
+ return this.fileSystemCallbacks.TryDehydrateCleanFile(gitPath, blob);
+ }
+
+ public bool TryRestoreModifiedPath(string gitPath)
+ {
+ return this.fileSystemCallbacks.TryRestoreModifiedPath(gitPath);
+ }
+
+ public bool IsProjectedFile(string gitPath, string sha)
+ {
+ string virtualPath = gitPath.Replace(GVFSConstants.GitPathSeparator, Path.DirectorySeparatorChar);
+ return this.fileSystemCallbacks.GitIndexProjection.IsFileProjectedWithSha(virtualPath, sha);
+ }
+
+ public void InvalidateProjection()
+ {
+ // The projection does not include an entry without the skip-worktree bit. Git set
+ // the bit of each dehydrated file, so the projection must include them again. The
+ // file system callbacks wait for the new projection.
+ this.fileSystemCallbacks.GitIndexProjection.InvalidateProjection();
+ }
}
}
diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs
index 5c8d98970f..f60a30e343 100644
--- a/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs
+++ b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs
@@ -788,7 +788,8 @@ public void ReconcileRemovesAModifiedFileThatMatchesHeadWithoutRunningGitToApply
this.ConeFile.ShouldEqual(Header);
this.environment.DiffCount.ShouldEqual(1);
this.environment.ConeFilesAtApply.Count.ShouldEqual(1, "Only Git can apply a cone");
- this.environment.IsPending.ShouldBeFalse();
+ this.environment.IsPending.ShouldBeTrue("The next apply returns the clean files to placeholders");
+ this.environment.DehydrateCalls.ShouldBeEmpty();
// The root file .gitattributes is clean too.
this.LastEvent("ConeReconcile").Metadata["NewlyCleanCount"].ShouldEqual(2);
}
@@ -863,11 +864,15 @@ public void CleanFileThatDiffersAfterAHeadChangeIsPending()
this.manager.TryReconcile().ShouldBeTrue();
this.ConeFile.ShouldEqual(Header);
- // For example "git reset --soft HEAD~1" after a commit of the file.
+ // For example "git reset --soft HEAD~1" after a commit of the file. The check made a
+ // dehydrate pending, so the check does not run until an apply.
this.environment.DifferingPaths.Add("C/c.txt");
this.environment.RepositoryStamp++;
this.manager.TryReconcile().ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldBeEmpty("The blobs are from before the HEAD change");
+ this.manager.TryReconcile().ShouldBeTrue();
this.environment.IsPending.ShouldBeTrue();
this.Apply(FirstGit).ShouldBeTrue();
this.ConeFile.ShouldEqual(ConeWithC);
@@ -915,7 +920,7 @@ public void ChangeInsideTheAppliedConeStartsACheckWhenTheChangesStop()
SpinWait.SpinUntil(() => this.tracer.SnapshotRelatedEvents().Any(recorded => recorded.Name == "ConeReconcile"), TimeSpan.FromSeconds(10))
.ShouldBeTrue("The check did not run");
this.ConeFile.ShouldEqual(Header);
- this.environment.IsPending.ShouldBeFalse();
+ this.environment.IsPending.ShouldBeTrue("The next apply returns the clean file to a placeholder");
}
[TestCase]
@@ -1034,11 +1039,545 @@ public void HandleRequestAppliesAnApplyRequest()
this.environment.IsPending.ShouldBeFalse();
}
+ [TestCase]
+ public void ApplyAfterACheckDehydratesTheCleanFilesAndRunsGitWhenTheConeDoesNotChange()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.ConeFile.ShouldEqual(Header);
+
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes", "C/c.txt");
+ this.environment.ModifiedPaths.ShouldBeEmpty();
+ this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithC, Header);
+ this.environment.ProjectionInvalidations.ShouldEqual(1);
+ this.environment.RestoredPaths.ShouldBeEmpty();
+ this.environment.IsPending.ShouldBeFalse();
+ this.LastEvent("ConeApply").Metadata["DehydratedCount"].ShouldEqual(2);
+ }
+
+ [TestCase]
+ public void ApplyDoesNotRebuildTheProjectionWhenItStillHasTheDehydratedFiles()
+ {
+ // No command rebuilt the projection while the files were modified paths.
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.environment.ProjectedFiles.UnionWith(new[] { ".gitattributes", "C/c.txt" });
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.ModifiedPaths.ShouldBeEmpty();
+ this.environment.ProjectionInvalidations.ShouldEqual(0);
+ this.LastEvent("ConeApply").Metadata["ProjectionInvalidated"].ShouldEqual(false);
+ }
+
+ [TestCase]
+ public void ApplyRebuildsTheProjectionOnceWhenItDoesNotHaveADehydratedFile()
+ {
+ this.environment.ModifiedPaths.AddRange(new[] { "C/c.txt", "D/d.txt" });
+ this.environment.ProjectedFiles.UnionWith(new[] { ".gitattributes", "C/c.txt" });
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.ProjectionInvalidations.ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void ApplyDoesNotDehydrateAFileThatNoCheckFoundClean()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.BlobRequests.ShouldBeEmpty();
+ this.environment.DehydrateCalls.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenDoesNotDehydrateAndKeepsTheDehydratePending()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Widen(SecondGit, "A/B/b.txt").ShouldBeTrue();
+
+ this.environment.DehydrateCalls.ShouldBeEmpty();
+ this.environment.IsPending.ShouldBeTrue("Only an apply dehydrates");
+
+ this.Apply(SecondGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes", "C/c.txt");
+ }
+
+ [TestCase]
+ public void FileThatChangedAfterTheCheckIsNotDehydrated()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false);
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes");
+ this.environment.ModifiedPaths.ShouldContain(path => path == "C/c.txt");
+ this.ConeFile.ShouldEqual(ConeWithC);
+ }
+
+ [TestCase]
+ public void FileThatIsNotInTheIndexIsNeverDehydrated()
+ {
+ // For example, a created file that Git ignores: Git does not report it.
+ this.environment.ModifiedPaths.Add("D/ignored.txt");
+ this.environment.NotInIndex.Add("D/ignored.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes");
+ this.environment.BlobRequests.Count.ShouldEqual(1, "A file that is not in the index is not tried again until it changes");
+ this.environment.ModifiedPaths.ShouldContain(path => path == "D/ignored.txt");
+ this.ConeFile.ShouldEqual(Header);
+ }
+
+ [TestCase]
+ public void FileInAnUntrackedFolderIsNotDehydrated()
+ {
+ this.environment.ModifiedPaths.AddRange(new[] { "D/", "D/d.txt" });
+ this.environment.DifferingPaths.Add("D/");
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.ConeFile.ShouldEqual(Header + "/D/\n");
+ this.LastEvent("ConeReconcile").Metadata["NewlyCleanCount"].ShouldEqual(1, "Only .gitattributes is clean");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes");
+ }
+
+ [TestCase]
+ public void FolderIsNeverDehydrated()
+ {
+ this.environment.ModifiedPaths.Add("D/");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.BlobRequests.Single().ShouldMatchInOrder(".gitattributes");
+ this.environment.ModifiedPaths.ShouldContain(path => path == "D/");
+ }
+
+ [TestCase]
+ public void DehydrateWaitsUntilAMergeEnds()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateBlocker = "MERGE_HEAD";
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.IsPending.ShouldBeFalse("A blocked dehydrate does not make the next command apply");
+
+ // Another change makes an apply run during the merge.
+ this.environment.ModifiedPaths.Add("D/d.txt");
+ this.manager.OnWorkingDirectoryPathChanged(@"D\d.txt", isFolder: false);
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.BlobRequests.ShouldBeEmpty();
+ this.environment.DehydrateCalls.ShouldBeEmpty();
+ this.LastEvent("ConeApply").Metadata["DehydrateBlocker"].ShouldEqual("MERGE_HEAD");
+ this.environment.IsPending.ShouldBeFalse();
+
+ // The merge commit writes the index, so the next check runs.
+ this.environment.DehydrateBlocker = null;
+ this.environment.RepositoryStamp++;
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.IsPending.ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes", "C/c.txt", "D/d.txt");
+ }
+
+ [TestCase(CleanFileDehydrateResult.InUse)]
+ [TestCase(CleanFileDehydrateResult.Replaced)]
+ [TestCase(CleanFileDehydrateResult.PlaceholderUpdateFailed)]
+ public void FileThatFailsForAPassingReasonWaitsAndDoesNotBlockOtherFiles(CleanFileDehydrateResult failure)
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.environment.DehydrateResults["C/c.txt"] = failure;
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.ModifiedPaths.ShouldContain(path => path == "C/c.txt");
+ this.LastEvent("ConeApply").Metadata["DehydrateSkipped"].ShouldEqual(failure + "=1");
+ this.environment.IsPending.ShouldBeFalse("The retry is not due yet");
+
+ // Another clean file is dehydrated, and the waiting file is not looked up again.
+ this.environment.ModifiedPaths.Add("D/d.txt");
+ this.manager.OnWorkingDirectoryPathChanged(@"D\d.txt", isFolder: false);
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes", "C/c.txt", "D/d.txt");
+ this.environment.BlobRequests.Last().ShouldMatchInOrder("D/d.txt");
+ this.environment.ModifiedPaths.ShouldMatchInOrder("C/c.txt");
+ }
+
+ [TestCase]
+ public void FileInUseIsTriedAgainWhenItsWaitEnds()
+ {
+ this.manager.Stop();
+ this.manager = this.CreateManager(ignoreCase: false, changeCheckDelayMs: Timeout.Infinite, dehydrateRetryDelayMs: 1);
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.environment.DehydrateResults["C/c.txt"] = CleanFileDehydrateResult.InUse;
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ // The timer makes the next Git command apply.
+ SpinWait.SpinUntil(() => this.environment.IsPending, TimeSpan.FromSeconds(10)).ShouldBeTrue();
+
+ this.environment.DehydrateResults.Remove("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes", "C/c.txt", "C/c.txt");
+ this.environment.ModifiedPaths.ShouldBeEmpty();
+ }
+
+ [TestCase(CleanFileDehydrateResult.InUse)]
+ [TestCase(CleanFileDehydrateResult.ContentDiffers)]
+ public void FileThatAnAttemptKeptIsTriedAgainAfterAChangeThatTheCheckSaw(CleanFileDehydrateResult failure)
+ {
+ // D/d.txt differs from HEAD, so the cone includes D/ and a change to D/c.txt is
+ // inside the applied cone. Only the check sees such a change.
+ this.environment.ModifiedPaths.AddRange(new[] { "D/c.txt", "D/d.txt" });
+ this.environment.DifferingPaths.Add("D/d.txt");
+ this.environment.DehydrateResults["D/c.txt"] = failure;
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.IsPending.ShouldBeFalse();
+
+ this.environment.DehydrateResults.Remove("D/c.txt");
+ this.manager.OnWorkingDirectoryPathChanged(@"D\c.txt", isFolder: false);
+ this.environment.IsPending.ShouldBeFalse("The applied cone includes the change");
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.IsPending.ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.Count(path => path == "D/c.txt").ShouldEqual(2);
+ this.environment.ModifiedPaths.ShouldNotContain(path => path == "D/c.txt");
+ }
+
+ [TestCase]
+ public void FileWithOtherBytesIsNotTriedAgainUntilItChanges()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.environment.DehydrateResults["C/c.txt"] = CleanFileDehydrateResult.ContentDiffers;
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.DehydrateCalls.Count(path => path == "C/c.txt").ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void LargeFileIsNotDehydrated()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.environment.BlobSizes["C/c.txt"] = AutoSparseIndexConeManager.MaxDehydrateFileSize + 1;
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.LastEvent("ConeReconcile").Metadata["DehydrateSkipped"].ShouldEqual("TooLarge=1");
+
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes");
+ }
+
+ [TestCase]
+ public void ApplyFailureMakesTheDehydratedFilesModifiedPathsAgain()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.environment.ApplyExitCode = 1;
+ this.Apply(FirstGit).ShouldBeFalse();
+
+ this.environment.RestoredPaths.ShouldMatchInOrder(".gitattributes", "C/c.txt");
+ this.environment.ModifiedPaths.ShouldContain(path => path == "C/c.txt");
+ this.environment.ProjectionInvalidations.ShouldEqual(0);
+ this.environment.IsPending.ShouldBeTrue();
+
+ // They are still clean, so the next apply dehydrates them.
+ this.environment.ApplyExitCode = 0;
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.Count(path => path == "C/c.txt").ShouldEqual(2);
+ this.environment.ModifiedPaths.ShouldNotContain(path => path == "C/c.txt");
+ }
+
+ [TestCase]
+ public void ApplyExceptionMakesTheDehydratedFilesModifiedPathsAgain()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.environment.ApplyException = new InvalidOperationException("Injected");
+ this.Apply(FirstGit).ShouldBeFalse();
+
+ this.environment.RestoredPaths.ShouldMatchInOrder(".gitattributes", "C/c.txt");
+ }
+
+ [TestCase]
+ public void CheckReadsTheBlobsAndTheApplyDoesNotRunTheLookup()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.BlobRequests.Single().ShouldMatchInOrder(".gitattributes", "C/c.txt");
+ this.environment.BlobTimeouts.Single().ShouldEqual(AutoSparseIndexConeManager.DehydrateLookupTimeoutMs);
+ this.LastEvent("ConeReconcile").Metadata["RecordedBlobCount"].ShouldEqual(2);
+ this.environment.IsPending.ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.BlobRequests.Count.ShouldEqual(1);
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes", "C/c.txt");
+ }
+
+ [TestCase]
+ public void ApplyAfterTheStampChangedDoesNotDehydrateAndTheNextCheckReadsTheBlobsAgain()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ // For example, a Git command wrote the index after the check.
+ this.environment.RepositoryStamp++;
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.DehydrateCalls.ShouldBeEmpty();
+ this.LastEvent("ConeApply").Metadata["DehydrateStaleCount"].ShouldEqual(2);
+ this.environment.IsPending.ShouldBeFalse("Only a check can read the blobs");
+
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.BlobRequests.Count.ShouldEqual(2);
+ this.environment.IsPending.ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes", "C/c.txt");
+ }
+
+ [TestCase]
+ public void FileWhoseIndexBlobChangedAfterTheCheckIsNotDehydratedAndReturnsToTheCone()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.ConeFile.ShouldEqual(Header);
+
+ // For example, "git add" of other content, then the old content on disk again.
+ this.environment.DifferingPaths.Add("C/c.txt");
+ this.environment.RepositoryStamp++;
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldBeEmpty();
+
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.IsPending.ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.ConeFile.ShouldEqual(ConeWithC);
+
+ // The other clean file is dehydrated after the next check.
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes");
+ this.environment.ModifiedPaths.ShouldContain(path => path == "C/c.txt");
+ }
+
+ [TestCase]
+ public void ApplyStopsConvertingWhenTheRequestApproachesTheWaitOfTheHook()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.OnDehydrate = () => Thread.Sleep(AutoSparseIndexConeManager.DehydrateRequestBudgetMs + 50);
+
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes");
+ this.environment.IsPending.ShouldBeTrue("The blob of the other file is still valid");
+ }
+
+ [TestCase]
+ public void BlobReadFailureRecordsNothingAndTheFilesWaitBeforeTheNextLookup()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.BlobsFail = true;
+
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.LastEvent("ConeReconcile").Metadata.ContainsKey("DehydrateBlobError").ShouldBeTrue();
+ this.environment.IsPending.ShouldBeFalse();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldBeEmpty();
+
+ // The files wait before the next lookup, so each check does not repeat it.
+ this.environment.RepositoryStamp++;
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.BlobRequests.Count.ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void FileIsDehydratedForTheBlobOfTheNewHeadAfterHeadMoved()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ // HEAD moved to a commit that has another blob for the file, and the index and the
+ // file match it.
+ this.environment.RepositoryStamp++;
+ this.environment.BlobShas["C/c.txt"] = new string('c', 40);
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldBeEmpty();
+
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydratedBlobs["C/c.txt"].Sha.ShouldEqual(new string('c', 40));
+ }
+
+ [TestCase]
+ public void CheckDoesNotRecordBlobsWhenTheStampChangedDuringTheLookup()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DuringBlobs = () => this.environment.RepositoryStamp++;
+
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.LastEvent("ConeReconcile").Metadata["DehydrateBlobStale"].ShouldEqual(true);
+ this.environment.IsPending.ShouldBeFalse();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldBeEmpty();
+
+ this.environment.DuringBlobs = null;
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes", "C/c.txt");
+ }
+
+ [TestCase]
+ public void ApplyThatDehydratesIsTelemetry()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.LastEvent("ConeApply").Keyword.HasFlag(Keywords.Telemetry).ShouldBeFalse();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ MockTracer.RecordedEvent applied = this.LastEvent("ConeApply");
+ applied.Level.ShouldEqual(EventLevel.Informational);
+ applied.Keyword.HasFlag(Keywords.Telemetry).ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void RestoreFailureAfterAnApplyFailureIsAnError()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.ApplyExitCode = 1;
+ this.environment.RestoreFails = true;
+
+ this.Apply(FirstGit).ShouldBeFalse();
+
+ this.LastEvent("ConeApply").Metadata["DehydrateRestoreFailureCount"].ShouldEqual(2);
+ this.tracer.RelatedErrorEvents.ShouldContain(error => error.Contains("DehydrateRestoreFailureCount"));
+ }
+
+ [TestCase]
+ public void ApplyRebuildsTheProjectionWhenItHasADehydratedFileForAnotherBlob()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.environment.ProjectedFiles.UnionWith(new[] { ".gitattributes", "C/c.txt" });
+ this.environment.OtherProjectedShas["C/c.txt"] = new string('b', 40);
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.ProjectionInvalidations.ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void RequestApplyMakesTheNextGitCommandApplyTheCone()
+ {
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.Widen(SecondGit, "A/B/b.txt").ShouldBeTrue();
+ this.Narrow(SecondGit).ShouldBeTrue();
+ int applies = this.environment.ConeFilesAtApply.Count;
+
+ this.manager.RequestApply();
+
+ this.environment.IsPending.ShouldBeTrue();
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.ConeFilesAtApply.Count.ShouldEqual(applies + 1, "The index still expands A/B after the narrow");
+ }
+
+ [TestCase]
+ public void ApplyStopsAfterTheTimeBudgetButDehydratesAtLeastOneFile()
+ {
+ this.environment.ModifiedPaths.Add("C/c.txt");
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+ this.environment.OnDehydrate = () => Thread.Sleep(AutoSparseIndexConeManager.DehydrateTimeBudgetMs + 50);
+
+ this.Apply(FirstGit).ShouldBeTrue();
+
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes");
+ this.environment.IsPending.ShouldBeTrue("The next Git command continues");
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.ShouldMatchInOrder(".gitattributes", "C/c.txt");
+ }
+
+ [TestCase]
+ public void ApplyDehydratesAtMostTheBatchLimitAndKeepsTheRestPending()
+ {
+ for (int i = 0; i < AutoSparseIndexConeManager.MaxDehydrateFiles; i++)
+ {
+ this.environment.ModifiedPaths.Add("C/" + i.ToString("D5") + ".txt");
+ }
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.manager.TryReconcile().ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.DehydrateCalls.Count.ShouldEqual(AutoSparseIndexConeManager.MaxDehydrateFiles);
+ this.environment.ModifiedPaths.Count.ShouldEqual(1);
+ this.environment.IsPending.ShouldBeTrue();
+
+ this.Apply(FirstGit).ShouldBeTrue();
+ this.environment.ModifiedPaths.ShouldBeEmpty();
+ this.environment.IsPending.ShouldBeFalse();
+ }
+
private string ConeFile => this.fileSystem.ReadAllText(SparseCheckoutPath);
- private AutoSparseIndexConeManager CreateManager(bool ignoreCase, int changeCheckDelayMs)
+ private AutoSparseIndexConeManager CreateManager(bool ignoreCase, int changeCheckDelayMs, int dehydrateRetryDelayMs = AutoSparseIndexConeManager.DefaultDehydrateRetryDelayMs)
{
- return new AutoSparseIndexConeManager(this.tracer, this.fileSystem, SparseCheckoutPath, ignoreCase, this.environment, changeCheckDelayMs);
+ return new AutoSparseIndexConeManager(this.tracer, this.fileSystem, SparseCheckoutPath, ignoreCase, this.environment, changeCheckDelayMs, dehydrateRetryDelayMs);
}
private bool Apply(int processId)
@@ -1090,6 +1629,8 @@ private static MockDirectory CreateRoot()
private sealed class MockEnvironment : IConeManagerEnvironment
{
+ public static readonly string HeadSha = new string('a', 40);
+
private readonly MockFileSystem fileSystem;
private int lockHeld;
@@ -1152,6 +1693,110 @@ public MockEnvironment(MockFileSystem fileSystem)
public long RepositoryStamp { get; set; }
+ public string DehydrateBlocker { get; set; }
+
+ public HashSet NotInIndex { get; } = new HashSet();
+
+ public bool BlobsFail { get; set; }
+
+ public List> BlobRequests { get; } = new List>();
+
+ public List BlobTimeouts { get; } = new List();
+
+ public Action DuringBlobs { get; set; }
+
+ // The blobs of HEAD and the index, when they are not HeadSha.
+ public Dictionary BlobShas { get; } = new Dictionary();
+
+ public Dictionary DehydratedBlobs { get; } = new Dictionary();
+
+ public bool RestoreFails { get; set; }
+
+ public Dictionary DehydrateResults { get; } = new Dictionary();
+
+ public Dictionary BlobSizes { get; } = new Dictionary();
+
+ public List DehydrateCalls { get; } = new List();
+
+ public List RestoredPaths { get; } = new List();
+
+ public int ProjectionInvalidations { get; private set; }
+
+ public Action OnDehydrate { get; set; }
+
+ public string GetDehydrateBlocker()
+ {
+ return this.DehydrateBlocker;
+ }
+
+ public bool TryGetBlobsThatMatchHead(IReadOnlyList gitPaths, int timeoutMs, out IReadOnlyDictionary blobs, out IReadOnlyCollection notInIndex, out string error)
+ {
+ this.BlobRequests.Add(gitPaths.ToList());
+ this.BlobTimeouts.Add(timeoutMs);
+ this.DuringBlobs?.Invoke();
+ if (this.BlobsFail)
+ {
+ blobs = null;
+ notInIndex = null;
+ error = "fatal: injected failure";
+ return false;
+ }
+
+ // A path that differs from HEAD in the index has another blob there.
+ notInIndex = gitPaths.Where(path => this.NotInIndex.Contains(path)).ToList();
+ blobs = gitPaths
+ .Where(path => !this.NotInIndex.Contains(path) && !this.DifferingPaths.Contains(path))
+ .ToDictionary(path => path, path => new HeadBlob(this.BlobShas.TryGetValue(path, out string sha) ? sha : HeadSha, this.BlobSizes.TryGetValue(path, out long size) ? size : 1));
+ error = null;
+ return true;
+ }
+
+ public CleanFileDehydrateResult TryDehydrateCleanFile(string gitPath, HeadBlob blob)
+ {
+ this.DehydrateCalls.Add(gitPath);
+ this.OnDehydrate?.Invoke();
+ if (!this.DehydrateResults.TryGetValue(gitPath, out CleanFileDehydrateResult result))
+ {
+ result = CleanFileDehydrateResult.Dehydrated;
+ }
+
+ if (result == CleanFileDehydrateResult.Dehydrated)
+ {
+ this.ModifiedPaths.Remove(gitPath);
+ this.DehydratedBlobs[gitPath] = blob;
+ }
+
+ return result;
+ }
+
+ public bool TryRestoreModifiedPath(string gitPath)
+ {
+ this.RestoredPaths.Add(gitPath);
+ if (this.RestoreFails)
+ {
+ return false;
+ }
+
+ this.ModifiedPaths.Add(gitPath);
+ return true;
+ }
+
+ // The projected files, with the blob of HEAD unless OtherProjectedShas has the path.
+ public HashSet ProjectedFiles { get; } = new HashSet();
+
+ public Dictionary OtherProjectedShas { get; } = new Dictionary();
+
+ public bool IsProjectedFile(string gitPath, string sha)
+ {
+ string projectedSha = this.OtherProjectedShas.TryGetValue(gitPath, out string other) ? other : HeadSha;
+ return this.ProjectedFiles.Contains(gitPath) && projectedSha == sha;
+ }
+
+ public void InvalidateProjection()
+ {
+ this.ProjectionInvalidations++;
+ }
+
public bool TrySetConeChangePending(bool pending, out Exception error)
{
if (this.PendingFileFails || (!pending && this.PendingFileDeleteFails))
diff --git a/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj
index 45cdb7d8eb..cc9c71a9a0 100644
--- a/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj
+++ b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj
@@ -37,6 +37,9 @@
Hooks\PendingConeChangeHook.cs
+
+ Hooks\PreCommandConeRequests.cs
+
Hooks\GitCommandLock.cs
diff --git a/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs b/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs
index cff508e14f..00cc64f59f 100644
--- a/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs
+++ b/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs
@@ -43,6 +43,45 @@ public void GetPorcelainV2PathReturnsThePathOfAChangedEntry(string record, strin
GitProcess.GetPorcelainV2Path(record).ShouldEqual(expectedPath);
}
+ [TestCase("100644 ce013625030ba8dba906f756967f9e9ca394464a 0\td/a file.txt", true)]
+ [TestCase("100755 CE013625030BA8DBA906F756967F9E9CA394464A 0\td/a file.txt", true)]
+ [TestCase("120000 ce013625030ba8dba906f756967f9e9ca394464a 0\td/a file.txt", false)]
+ [TestCase("040000 ce013625030ba8dba906f756967f9e9ca394464a 0\td/", false)]
+ [TestCase("100644 ce013625030ba8dba906f756967f9e9ca394464a 2\td/a file.txt", false)]
+ [TestCase("100644 ce013625 0\td/a file.txt", false)]
+ [TestCase("100644 ce013625030ba8dba906f756967f9e9ca394464a 0", false)]
+ public void TryParseLsFilesStageRecordAcceptsOnlyARegularFileAtStageZero(string record, bool expected)
+ {
+ GitProcess.TryParseLsFilesStageRecord(record, out string path, out string sha).ShouldEqual(expected);
+ if (expected)
+ {
+ path.ShouldEqual("d/a file.txt");
+ sha.ShouldEqual("ce013625030ba8dba906f756967f9e9ca394464a");
+ }
+ }
+
+ [TestCase("100644 blob ce013625030ba8dba906f756967f9e9ca394464a 6\td/a file.txt", true)]
+ [TestCase("100755 blob ce013625030ba8dba906f756967f9e9ca394464a 6\td/a file.txt", true)]
+ [TestCase("120000 blob ce013625030ba8dba906f756967f9e9ca394464a 6\td/a file.txt", false)]
+ [TestCase("040000 tree ce013625030ba8dba906f756967f9e9ca394464a -\td", false)]
+ [TestCase("160000 commit ce013625030ba8dba906f756967f9e9ca394464a -\td/sub", false)]
+ public void TryParseLsTreeLongRecordAcceptsOnlyARegularFile(string record, bool expected)
+ {
+ GitProcess.TryParseLsTreeLongRecord(record, out string path, out HeadBlob blob).ShouldEqual(expected);
+ if (expected)
+ {
+ path.ShouldEqual("d/a file.txt");
+ blob.ShouldEqual(new HeadBlob("ce013625030ba8dba906f756967f9e9ca394464a", 6));
+ }
+ }
+
+ [TestCase]
+ public void GetPathspecArgumentsQuotesThePathsAndSplitsALongList()
+ {
+ GitProcess.GetPathspecArguments(new[] { "a b.txt", "c.txt", "dd.txt" }, maxLength: 18)
+ .ShouldMatchInOrder("\"a b.txt\" \"c.txt\"", "\"dd.txt\"");
+ }
+
[TestCase]
public void ReadStdOutTokens_EmptyInputYieldsNoTokens()
{
diff --git a/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs b/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs
index 0ab4c827d6..16ab7bc265 100644
--- a/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs
+++ b/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs
@@ -65,6 +65,21 @@ public void WithoutConeModeFileNeitherHookReadsConfigOrSends(string content)
this.createdClients.ShouldBeEmpty();
}
+ [TestCase(null, true, false, 0)]
+ [TestCase("/A/\n", true, false, 0)]
+ [TestCase(ConeWithRecursiveA, false, false, 1)]
+ [TestCase(ConeWithRecursiveA, true, true, 1)]
+ public void IsSparseIndexConeManagedUsesTheGateOfAWiden(string content, bool enabled, bool expected, int expectedConfigReads)
+ {
+ this.coneFileContent = content;
+ this.featureEnabled = enabled;
+
+ this.CreateHook().IsSparseIndexConeManaged().ShouldEqual(expected);
+
+ this.configReadCount.ShouldEqual(expectedConfigReads);
+ this.createdClients.ShouldBeEmpty();
+ }
+
[TestCase("status")]
[TestCase("commit", "-m", "message")]
[TestCase("checkout", "topic")]
diff --git a/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs b/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs
new file mode 100644
index 0000000000..b0e7e9718a
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Hooks/PreCommandConeRequestsTests.cs
@@ -0,0 +1,161 @@
+using GVFS.Hooks;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System;
+using System.Collections.Generic;
+
+namespace GVFS.UnitTests.Hooks
+{
+ [TestFixture]
+ public class PreCommandConeRequestsTests
+ {
+ private List calls;
+ private bool pending;
+
+ [SetUp]
+ public void SetUp()
+ {
+ this.calls = new List();
+ this.pending = false;
+ }
+
+ [TestCase]
+ public void UnstageWidensBeforeItPrepares()
+ {
+ // Git does not match a pathspec with a path inside a sparse-directory entry, so the
+ // staged-file query of the preparation must run after the widen.
+ this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.Applied).ShouldBeNull();
+
+ this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?");
+ }
+
+ [TestCase("Applied")]
+ [TestCase("NoPathsNamed")]
+ [TestCase("NoResolvablePaths")]
+ public void UnstageAppliesAChangeThatThePreparationMadePending(string widenOutcome)
+ {
+ this.Send(isUnstage: true, widenOutcome: Parse(widenOutcome), preparationMakesPending: true).ShouldBeNull();
+
+ this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?", "apply");
+ }
+
+ [TestCase]
+ public void UnstageAppliesOnceAChangeThatWasPendingBeforeAWidenThatDidNotApply()
+ {
+ this.pending = true;
+ this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.NoPathsNamed).ShouldBeNull();
+
+ this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?", "apply");
+ }
+
+ [TestCase]
+ public void UnstageDoesNotApplyWhenNothingIsPendingAfterThePreparation()
+ {
+ this.pending = true;
+ this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.Applied, widenClearsPending: true).ShouldBeNull();
+
+ this.calls.ShouldMatchInOrder("pending?", "widen", "prepare", "pending?");
+ }
+
+ [TestCase("NothingPending")]
+ [TestCase("FeatureDisabled")]
+ public void UnstageRunsWhenTheApplyHasNothingToDo(string applyOutcome)
+ {
+ this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.NoPathsNamed, preparationMakesPending: true, applyOutcome: Parse(applyOutcome))
+ .ShouldBeNull();
+ }
+
+ [TestCase("TimedOut")]
+ [TestCase("Rejected")]
+ [TestCase("Failed")]
+ [TestCase("MountUnavailable")]
+ [TestCase("NotAnIndexReader")]
+ public void UnstageStopsWhenTheApplyFails(string applyOutcome)
+ {
+ // Without the apply, the unstaged file stays inside a sparse-directory entry with
+ // skip-worktree set, and Git does not report the change.
+ this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.NoPathsNamed, preparationMakesPending: true, applyOutcome: Parse(applyOutcome))
+ .ShouldEqual("apply: " + applyOutcome);
+ }
+
+ [TestCase]
+ public void UnstageStopsWithoutPreparingWhenTheWidenTimedOut()
+ {
+ // The mount can still change the cone and the index after the hook stops waiting.
+ this.Send(isUnstage: true, widenOutcome: ConeRequestOutcome.TimedOut).ShouldEqual("widen: TimedOut");
+
+ this.calls.ShouldMatchInOrder("pending?", "widen");
+ }
+
+ [TestCase]
+ public void OtherCommandSkipsTheApplyAfterAnAppliedWiden()
+ {
+ this.pending = true;
+ this.Send(isUnstage: false, widenOutcome: ConeRequestOutcome.Applied).ShouldBeNull();
+
+ this.calls.ShouldMatchInOrder("pending?", "widen");
+ }
+
+ [TestCase]
+ public void OtherCommandAppliesAPendingChangeWhenTheWidenDidNotApply()
+ {
+ this.pending = true;
+ this.Send(isUnstage: false, widenOutcome: ConeRequestOutcome.TimedOut, applyOutcome: ConeRequestOutcome.Failed).ShouldBeNull();
+
+ this.calls.ShouldMatchInOrder("pending?", "widen", "apply");
+ }
+
+ [TestCase]
+ public void OtherCommandDoesNotApplyWhenNothingIsPending()
+ {
+ this.Send(isUnstage: false, widenOutcome: ConeRequestOutcome.NoPathsNamed).ShouldBeNull();
+
+ this.calls.ShouldMatchInOrder("pending?", "widen");
+ }
+
+ // ConeRequestOutcome is internal, and NUnit test methods are public, so test cases name it.
+ private static ConeRequestOutcome Parse(string outcome)
+ {
+ return Enum.Parse(outcome);
+ }
+
+ private string Send(
+ bool isUnstage,
+ ConeRequestOutcome widenOutcome,
+ bool preparationMakesPending = false,
+ bool widenClearsPending = false,
+ ConeRequestOutcome applyOutcome = ConeRequestOutcome.Applied)
+ {
+ return PreCommandConeRequests.Send(
+ isUnstage,
+ () =>
+ {
+ this.calls.Add("pending?");
+ return this.pending;
+ },
+ () =>
+ {
+ this.calls.Add("widen");
+ if (widenClearsPending)
+ {
+ this.pending = false;
+ }
+
+ return widenOutcome;
+ },
+ () =>
+ {
+ this.calls.Add("prepare");
+ if (preparationMakesPending)
+ {
+ this.pending = true;
+ }
+ },
+ () =>
+ {
+ this.calls.Add("apply");
+ return applyOutcome;
+ });
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/Hooks/UnstageTests.cs b/GVFS/GVFS.UnitTests/Hooks/UnstageTests.cs
index 2341c15be0..15ff0355a8 100644
--- a/GVFS/GVFS.UnitTests/Hooks/UnstageTests.cs
+++ b/GVFS/GVFS.UnitTests/Hooks/UnstageTests.cs
@@ -92,6 +92,72 @@ public void IsUnstageOperation_OtherCommand()
.ShouldBeFalse();
}
+ [TestCase("reset")]
+ [TestCase("reset", "--mixed")]
+ [TestCase("reset", "--", "file.txt")]
+ [TestCase("reset", "HEAD", "file.txt")]
+ public void IsUnstageOperation_MixedReset(params string[] gitArgs)
+ {
+ UnstageCommandParser.IsUnstageOperation("reset", PreCommandArgs(gitArgs)).ShouldBeTrue();
+ }
+
+ [TestCase("reset", "--soft", "HEAD~1")]
+ [TestCase("reset", "--hard")]
+ [TestCase("reset", "--merge")]
+ [TestCase("reset", "--keep", "HEAD~1")]
+ [TestCase("reset", "-p")]
+ [TestCase("reset", "--patch", "--", "file.txt")]
+ public void IsUnstageOperation_ResetThatDoesNotUnstage(params string[] gitArgs)
+ {
+ UnstageCommandParser.IsUnstageOperation("reset", PreCommandArgs(gitArgs)).ShouldBeFalse();
+ }
+
+ [TestCase(false, false)]
+ [TestCase(true, true)]
+ public void ShouldPrepareForUnstage_ResetOnlyWhenTheConeIsManaged(bool managed, bool expected)
+ {
+ int checks = 0;
+ UnstageCommandParser.ShouldPrepareForUnstage("reset", PreCommandArgs(new[] { "reset" }), () => { checks++; return managed; })
+ .ShouldEqual(expected);
+ checks.ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void ShouldPrepareForUnstage_RestoreDoesNotCheckTheCone()
+ {
+ UnstageCommandParser.ShouldPrepareForUnstage("restore", PreCommandArgs(new[] { "restore", "--staged", "." }), () => throw new AssertionException("checked the cone"))
+ .ShouldBeTrue();
+ }
+
+ [TestCase("reset", "--pathspec-from-file=-")]
+ [TestCase("reset", "--soft", "HEAD~1")]
+ public void ShouldPrepareForUnstage_SkipsResetThatItCannotPrepare(params string[] gitArgs)
+ {
+ UnstageCommandParser.ShouldPrepareForUnstage("reset", PreCommandArgs(gitArgs), () => true).ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void ShouldPrepareForUnstage_OtherCommand()
+ {
+ UnstageCommandParser.ShouldPrepareForUnstage("status", PreCommandArgs(new[] { "status" }), () => true).ShouldBeFalse();
+ }
+
+ [TestCase(new[] { "reset" }, "")]
+ [TestCase(new[] { "reset", "-q" }, "")]
+ [TestCase(new[] { "reset", "HEAD" }, "")]
+ [TestCase(new[] { "reset", "-q", "HEAD", "--", "a.txt" }, "a.txt")]
+ [TestCase(new[] { "reset", "--", "a.txt", "b.txt" }, "a.txt\0b.txt")]
+ [TestCase(new[] { "reset", "HEAD", "a.txt" }, "a.txt")]
+ [TestCase(new[] { "reset", "HEAD", "--", "a.txt" }, "a.txt")]
+ [TestCase(new[] { "reset", "main", "--", "a.txt" }, "a.txt")]
+ [TestCase(new[] { "reset", "a.txt" }, "a.txt")]
+ public void GetRestorePathspec_ResetStripsTreeish(string[] gitArgs, string expectedPathspecs)
+ {
+ UnstageCommandParser.PathspecResult result = UnstageCommandParser.GetRestorePathspec("reset", PreCommandArgs(gitArgs));
+ result.Failed.ShouldBeFalse();
+ result.InlinePathspecs.ShouldEqual(expectedPathspecs);
+ }
+
// ── GetRestorePathspec: inline pathspecs ────────────────────────
[TestCase]
@@ -282,5 +348,14 @@ public void GetRestorePathspec_PathspecFromFileWithInlinePaths()
result.PathspecFromFile.ShouldEqual("list.txt");
result.InlinePathspecs.ShouldEqual("extra.txt");
}
+
+ private static string[] PreCommandArgs(string[] gitArgs)
+ {
+ string[] args = new string[gitArgs.Length + 2];
+ args[0] = "pre-command";
+ gitArgs.CopyTo(args, 1);
+ args[args.Length - 1] = "--git-pid=1234";
+ return args;
+ }
}
}
diff --git a/GVFS/GVFS.UnitTests/Mock/FileSystem/MockFileSystem.cs b/GVFS/GVFS.UnitTests/Mock/FileSystem/MockFileSystem.cs
index d162624ad6..6a7a4d3dd5 100644
--- a/GVFS/GVFS.UnitTests/Mock/FileSystem/MockFileSystem.cs
+++ b/GVFS/GVFS.UnitTests/Mock/FileSystem/MockFileSystem.cs
@@ -40,6 +40,14 @@ public MockFileSystem(MockDirectory rootDirectory)
///
public bool DeleteNonExistentFileThrowsException { get; set; }
+ /// The result of .
+ public bool OpenFileIsAtPath { get; set; } = true;
+
+ public override bool IsOpenFileAtPath(Stream stream, string path)
+ {
+ return this.OpenFileIsAtPath;
+ }
+
public override void DeleteDirectory(string path, bool recursive = true, bool ignoreDirectoryDeleteExceptions = false)
{
if (!recursive)
diff --git a/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs b/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs
index 66b7a3821b..b4ef0ad30b 100644
--- a/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs
+++ b/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs
@@ -1,6 +1,7 @@
using GVFS.Common;
using GVFS.Common.Database;
using GVFS.Common.FileSystem;
+using GVFS.Common.Git;
using GVFS.Common.NamedPipes;
using GVFS.Common.Sparse;
using GVFS.Common.Tracing;
@@ -16,11 +17,13 @@
using GVFS.UnitTests.Virtual;
using GVFS.Virtualization;
using GVFS.Virtualization.Background;
+using GVFS.Virtualization.FileSystem;
using Moq;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
+using System.Linq;
using System.Threading;
namespace GVFS.UnitTests.Virtualization
@@ -475,6 +478,198 @@ public void WorkingDirectoryChangesReachTheObserver()
}
}
+ [TestCase]
+ public void StagedFilesReachModifiedPathsAndTheObserver()
+ {
+ // "git reset --soft" stages files without a file system write, so no callback reports
+ // them. The unstage preparation must report them, so that the cone includes them.
+ Mock mockPlaceholderDb = new Mock(MockBehavior.Strict);
+ mockPlaceholderDb.Setup(x => x.GetCount()).Returns(1);
+ Mock mockSparseDb = new Mock(MockBehavior.Strict);
+ mockSparseDb.Setup(x => x.GetAll()).Returns(new HashSet());
+ using (MockBackgroundFileSystemTaskRunner backgroundTaskRunner = new MockBackgroundFileSystemTaskRunner())
+ using (FileSystemCallbacks fileSystemCallbacks = new FileSystemCallbacks(
+ this.Repo.Context,
+ this.Repo.GitObjects,
+ RepoMetadata.Instance,
+ new MockBlobSizes(),
+ gitIndexProjection: null,
+ backgroundFileSystemTaskRunner: backgroundTaskRunner,
+ fileSystemVirtualizer: null,
+ placeholderDatabase: mockPlaceholderDb.Object,
+ sparseCollection: mockSparseDb.Object))
+ {
+ RecordingObserver observer = new RecordingObserver();
+ fileSystemCallbacks.SetWorkingDirectoryChangeObserver(observer);
+
+ fileSystemCallbacks.TryAddStagedFileToModifiedPaths("Out/Inc/staged.h", out bool wasModifiedPath).ShouldBeTrue();
+ wasModifiedPath.ShouldBeFalse();
+ fileSystemCallbacks.TryAddStagedFileToModifiedPaths(string.Empty, out _).ShouldBeFalse();
+
+ fileSystemCallbacks.GetAllModifiedPaths().ShouldContain(path => path == "Out/Inc/staged.h");
+ observer.Changes.ShouldMatchInOrder(@"Out\Inc\staged.h");
+
+ // A path that already is a modified path is reported again, so that a staged file
+ // that left the cone comes back into it. The caller must not overwrite it.
+ fileSystemCallbacks.TryAddStagedFileToModifiedPaths("Out/Inc/staged.h", out wasModifiedPath).ShouldBeTrue();
+ wasModifiedPath.ShouldBeTrue();
+ observer.Changes.ShouldMatchInOrder(@"Out\Inc\staged.h", @"Out\Inc\staged.h");
+ }
+ }
+
+ [TestCase]
+ public void DehydrateCleanFileConvertsTheFileThenAddsThePlaceholderThenRemovesTheModifiedPath()
+ {
+ List steps = new List();
+ using (CleanFileFixture fixture = new CleanFileFixture(this.Repo, steps, "hello\n"))
+ {
+ fixture.Virtualizer.OnUpdate = (path, sha, size, flags) =>
+ {
+ path.ShouldEqual(@"Out\clean.txt");
+ sha.ShouldEqual(CleanFileFixture.HelloSha);
+ size.ShouldEqual(6);
+ flags.HasFlag(UpdatePlaceholderType.AllowDirtyData).ShouldBeTrue();
+ fixture.IsModifiedPath().ShouldBeTrue("The file must stay a modified path until it is a placeholder");
+ steps.Add("convert");
+ return FSResult.Ok;
+ };
+ fixture.PlaceholderDb
+ .Setup(x => x.AddFile(@"Out\clean.txt", CleanFileFixture.HelloSha))
+ .Callback(() =>
+ {
+ fixture.IsModifiedPath().ShouldBeTrue("The placeholder must be added before the modified path is removed");
+ steps.Add("placeholder");
+ });
+
+ fixture.Callbacks.TryDehydrateCleanFile("Out/clean.txt", new HeadBlob(CleanFileFixture.HelloSha, 6))
+ .ShouldEqual(CleanFileDehydrateResult.Dehydrated);
+
+ steps.ShouldMatchInOrder("convert", "placeholder");
+ fixture.IsModifiedPath().ShouldBeFalse();
+ }
+ }
+
+ [TestCase]
+ public void DehydrateCleanFileKeepsTheTimesAndTheReadOnlyAttribute()
+ {
+ using (CleanFileFixture fixture = new CleanFileFixture(this.Repo, new List(), "hello\n"))
+ {
+ DateTime written = new DateTime(2020, 1, 2, 3, 4, 5, DateTimeKind.Utc);
+ fixture.CleanFile.FileProperties = new FileProperties(FileAttributes.ReadOnly, written.AddDays(-1), written, written, 6);
+ fixture.Virtualizer.OnUpdate = (path, sha, size, flags) => FSResult.Ok;
+ fixture.PlaceholderDb.Setup(x => x.AddFile(@"Out\clean.txt", CleanFileFixture.HelloSha));
+
+ fixture.Callbacks.TryDehydrateCleanFile("Out/clean.txt", new HeadBlob(CleanFileFixture.HelloSha, 6))
+ .ShouldEqual(CleanFileDehydrateResult.Dehydrated);
+
+ fixture.Virtualizer.LastAttributes.ShouldEqual(FileAttributes.ReadOnly);
+ fixture.Virtualizer.LastCreationTime.ShouldEqual(written.AddDays(-1));
+ fixture.Virtualizer.LastWriteTime.ShouldEqual(written);
+ }
+ }
+
+ [TestCase]
+ public void DehydrateCleanFileDoesNotConvertAFileThatThePathNoLongerNames()
+ {
+ using (CleanFileFixture fixture = new CleanFileFixture(this.Repo, new List(), "hello\n"))
+ {
+ // For example, a process renamed another file over the path after the hash.
+ this.Repo.FileSystem.OpenFileIsAtPath = false;
+
+ fixture.Callbacks.TryDehydrateCleanFile("Out/clean.txt", new HeadBlob(CleanFileFixture.HelloSha, 6))
+ .ShouldEqual(CleanFileDehydrateResult.Replaced);
+
+ fixture.Virtualizer.UpdateCount.ShouldEqual(0);
+ fixture.IsModifiedPath().ShouldBeTrue();
+ fixture.Callbacks.IsDehydratedPlaceholder(@"Out\clean.txt").ShouldBeFalse();
+ }
+ }
+
+ [TestCase]
+ public void DehydratedFileIsReportedOnceAsADehydratedPlaceholder()
+ {
+ using (CleanFileFixture fixture = new CleanFileFixture(this.Repo, new List(), "hello\n"))
+ {
+ fixture.Virtualizer.OnUpdate = (path, sha, size, flags) =>
+ {
+ // A write right after the conversion must find the path.
+ fixture.Callbacks.IsDehydratedPlaceholder(@"Out\clean.txt").ShouldBeTrue();
+ return FSResult.Ok;
+ };
+ fixture.PlaceholderDb.Setup(x => x.AddFile(@"Out\clean.txt", CleanFileFixture.HelloSha));
+ fixture.Callbacks.TryDehydrateCleanFile("Out/clean.txt", new HeadBlob(CleanFileFixture.HelloSha, 6))
+ .ShouldEqual(CleanFileDehydrateResult.Dehydrated);
+ fixture.Callbacks.IsDehydratedPlaceholder(@"Out\clean.txt").ShouldBeFalse("The check above took the path");
+
+ fixture.Virtualizer.OnUpdate = (path, sha, size, flags) => FSResult.Ok;
+ fixture.Callbacks.TryRestoreModifiedPath("Out/clean.txt").ShouldBeTrue();
+ fixture.Callbacks.TryDehydrateCleanFile("Out/clean.txt", new HeadBlob(CleanFileFixture.HelloSha, 6))
+ .ShouldEqual(CleanFileDehydrateResult.Dehydrated);
+ fixture.Callbacks.IsDehydratedPlaceholder(@"Out\clean.txt").ShouldBeTrue();
+ fixture.Callbacks.IsDehydratedPlaceholder(@"Out\clean.txt").ShouldBeFalse();
+ }
+ }
+
+ [TestCase("hellO\n")]
+ [TestCase("hello\n\n")]
+ [TestCase("hell\n")]
+ public void DehydrateCleanFileDoesNotConvertAFileWithOtherBytes(string content)
+ {
+ using (CleanFileFixture fixture = new CleanFileFixture(this.Repo, new List(), content))
+ {
+ fixture.Callbacks.TryDehydrateCleanFile("Out/clean.txt", new HeadBlob(CleanFileFixture.HelloSha, 6))
+ .ShouldEqual(CleanFileDehydrateResult.ContentDiffers);
+
+ fixture.Virtualizer.UpdateCount.ShouldEqual(0);
+ fixture.IsModifiedPath().ShouldBeTrue();
+ }
+ }
+
+ [TestCase]
+ public void DehydrateCleanFileKeepsTheModifiedPathWhenTheFileIsNotConverted()
+ {
+ using (CleanFileFixture fixture = new CleanFileFixture(this.Repo, new List(), "hello\n"))
+ {
+ // For example, the file became dirty, or a process holds it open.
+ fixture.Virtualizer.OnUpdate = (path, sha, size, flags) => FSResult.VirtualizationInvalidOperation;
+
+ fixture.Callbacks.TryDehydrateCleanFile("Out/clean.txt", new HeadBlob(CleanFileFixture.HelloSha, 6))
+ .ShouldEqual(CleanFileDehydrateResult.PlaceholderUpdateFailed);
+
+ fixture.IsModifiedPath().ShouldBeTrue();
+ fixture.Callbacks.IsDehydratedPlaceholder(@"Out\clean.txt").ShouldBeFalse();
+ fixture.PlaceholderDb.Verify(x => x.AddFile(It.IsAny(), It.IsAny()), Times.Never());
+ }
+ }
+
+ [TestCase]
+ public void DehydrateCleanFileDoesNothingForAPathThatIsNotAModifiedPath()
+ {
+ using (CleanFileFixture fixture = new CleanFileFixture(this.Repo, new List(), "hello\n"))
+ {
+ fixture.Callbacks.TryDehydrateCleanFile("Out/other.txt", new HeadBlob(CleanFileFixture.HelloSha, 6))
+ .ShouldEqual(CleanFileDehydrateResult.NotModifiedPath);
+
+ fixture.Virtualizer.UpdateCount.ShouldEqual(0);
+ }
+ }
+
+ [TestCase]
+ public void RestoreModifiedPathAddsTheFileBack()
+ {
+ using (CleanFileFixture fixture = new CleanFileFixture(this.Repo, new List(), "hello\n"))
+ {
+ fixture.Virtualizer.OnUpdate = (path, sha, size, flags) => FSResult.Ok;
+ fixture.PlaceholderDb.Setup(x => x.AddFile(@"Out\clean.txt", CleanFileFixture.HelloSha));
+ fixture.Callbacks.TryDehydrateCleanFile("Out/clean.txt", new HeadBlob(CleanFileFixture.HelloSha, 6))
+ .ShouldEqual(CleanFileDehydrateResult.Dehydrated);
+
+ fixture.Callbacks.TryRestoreModifiedPath("Out/clean.txt").ShouldBeTrue();
+
+ fixture.IsModifiedPath().ShouldBeTrue();
+ }
+ }
+
[TestCase]
public void FileAndFolderCallbacksScheduleBackgroundTasks()
{
@@ -656,5 +851,94 @@ public void OnWorkingDirectoryPathChanged(string relativePath, bool isFolder)
this.Changes.Add(isFolder ? relativePath + Path.DirectorySeparatorChar : relativePath);
}
}
+
+ ///
+ /// File system callbacks with one modified file, "Out\clean.txt", and a virtualizer that
+ /// records placeholder updates.
+ ///
+ private sealed class CleanFileFixture : IDisposable
+ {
+ // The object id of the blob "hello\n".
+ public const string HelloSha = "ce013625030ba8dba906f756967f9e9ca394464a";
+
+ private readonly MockBackgroundFileSystemTaskRunner backgroundTaskRunner;
+ private readonly Mock sparseDb;
+
+ public CleanFileFixture(CommonRepoSetup repo, List steps, string content)
+ {
+ this.PlaceholderDb = new Mock(MockBehavior.Strict);
+ this.PlaceholderDb.Setup(x => x.GetCount()).Returns(0);
+ this.sparseDb = new Mock(MockBehavior.Strict);
+ this.sparseDb.Setup(x => x.GetAll()).Returns(new HashSet());
+ this.backgroundTaskRunner = new MockBackgroundFileSystemTaskRunner();
+ this.Virtualizer = new RecordingVirtualizer(repo.Context, repo.GitObjects);
+
+ string folder = Path.Combine(repo.Context.Enlistment.WorkingDirectoryBackingRoot, "Out");
+ repo.Context.FileSystem.CreateDirectory(folder);
+ repo.Context.FileSystem.WriteAllText(Path.Combine(folder, "clean.txt"), content);
+ this.CleanFile = ((MockFileSystem)repo.Context.FileSystem).RootDirectory.FindFile(Path.Combine(folder, "clean.txt"));
+
+ this.Callbacks = new FileSystemCallbacks(
+ repo.Context,
+ repo.GitObjects,
+ RepoMetadata.Instance,
+ new MockBlobSizes(),
+ gitIndexProjection: null,
+ backgroundFileSystemTaskRunner: this.backgroundTaskRunner,
+ fileSystemVirtualizer: this.Virtualizer,
+ placeholderDatabase: this.PlaceholderDb.Object,
+ sparseCollection: this.sparseDb.Object);
+ this.Callbacks.TryRestoreModifiedPath("Out/clean.txt").ShouldBeTrue();
+ }
+
+ public Mock PlaceholderDb { get; }
+
+ public MockFile CleanFile { get; }
+
+ public RecordingVirtualizer Virtualizer { get; }
+
+ public FileSystemCallbacks Callbacks { get; }
+
+ public bool IsModifiedPath()
+ {
+ return this.Callbacks.GetAllModifiedPaths().Contains("Out/clean.txt");
+ }
+
+ public void Dispose()
+ {
+ this.Callbacks.Dispose();
+ this.Virtualizer.Dispose();
+ this.backgroundTaskRunner.Dispose();
+ }
+ }
+
+ private sealed class RecordingVirtualizer : MockFileSystemVirtualizer
+ {
+ public RecordingVirtualizer(GVFSContext context, GVFSGitObjects gitObjects)
+ : base(context, gitObjects)
+ {
+ }
+
+ public Func OnUpdate { get; set; }
+
+ public int UpdateCount { get; private set; }
+
+ public FileAttributes LastAttributes { get; private set; }
+
+ public DateTime LastCreationTime { get; private set; }
+
+ public DateTime LastWriteTime { get; private set; }
+
+ public override FileSystemResult UpdatePlaceholderIfNeeded(string relativePath, DateTime creationTime, DateTime lastAccessTime, DateTime lastWriteTime, DateTime changeTime, FileAttributes fileAttributes, long endOfFile, string shaContentId, UpdatePlaceholderType updateFlags, out UpdateFailureReason failureReason)
+ {
+ this.UpdateCount++;
+ this.LastAttributes = fileAttributes;
+ this.LastCreationTime = creationTime;
+ this.LastWriteTime = lastWriteTime;
+ failureReason = UpdateFailureReason.NoFailure;
+ FSResult result = this.OnUpdate(relativePath, shaContentId, endOfFile, updateFlags);
+ return new FileSystemResult(result, rawResult: result == FSResult.Ok ? 0 : -1);
+ }
+ }
}
}
diff --git a/GVFS/GVFS.UnitTests/Windows/Virtualization/WindowsFileSystemVirtualizerTests.cs b/GVFS/GVFS.UnitTests/Windows/Virtualization/WindowsFileSystemVirtualizerTests.cs
index cf077d2f78..ebd1e9852b 100644
--- a/GVFS/GVFS.UnitTests/Windows/Virtualization/WindowsFileSystemVirtualizerTests.cs
+++ b/GVFS/GVFS.UnitTests/Windows/Virtualization/WindowsFileSystemVirtualizerTests.cs
@@ -21,6 +21,8 @@
using GVFS.UnitTests.Mock.Virtualization.BlobSize;
using GVFS.Virtualization.Projection;
using System.Reflection;
+using GVFS.Virtualization.Background;
+using GVFS.Common.Sparse;
namespace GVFS.UnitTests.Windows.Virtualization
{
@@ -1615,6 +1617,28 @@ public void EndForNeverHeldIdDoesNotSkewLaterGetToEndedRecently()
}
}
+ [TestCase]
+ public void ConversionToFullOfADehydratedFileThatIsNotProjectedMakesItAModifiedPath()
+ {
+ const string HelloSha = "ce013625030ba8dba906f756967f9e9ca394464a";
+ using (WindowsFileSystemVirtualizerTester tester = new WindowsFileSystemVirtualizerTester(this.Repo))
+ {
+ // Git sets the skip-worktree bit, and the projection gets the file, only after
+ // the dehydrate.
+ this.Repo.Context.FileSystem.WriteAllText(Path.Combine(this.Repo.Context.Enlistment.WorkingDirectoryBackingRoot, "dehydrated.txt"), "hello\n");
+ tester.MockPlaceholderDb.Setup(x => x.AddFile("dehydrated.txt", HelloSha));
+ tester.FileSystemCallbacks.TryRestoreModifiedPath("dehydrated.txt").ShouldBeTrue();
+ tester.FileSystemCallbacks.TryDehydrateCleanFile("dehydrated.txt", new HeadBlob(HelloSha, 6)).ShouldEqual(CleanFileDehydrateResult.Dehydrated);
+
+ tester.MockVirtualization.OnNotifyFilePreConvertToFull("dehydrated.txt", TriggeringProcessId, TriggeringProcessImageFileName);
+ tester.BackgroundTaskShouldBeScheduled("dehydrated.txt", FileSystemTask.OperationType.OnFileConvertedToFull);
+
+ // Another file that the projection does not have is not tracked by Git.
+ tester.MockVirtualization.OnNotifyFilePreConvertToFull("other.txt", TriggeringProcessId, TriggeringProcessImageFileName);
+ tester.BackgroundTaskRunner.Count.ShouldEqual(1);
+ }
+ }
+
[TestCase]
public void GetPlaceholderInformationHandlerPathNotProjected()
{
diff --git a/GVFS/GVFS.Virtualization/FileSystem/FileSystemVirtualizer.cs b/GVFS/GVFS.Virtualization/FileSystem/FileSystemVirtualizer.cs
index 67fb3177e4..c3ad9b9e04 100644
--- a/GVFS/GVFS.Virtualization/FileSystem/FileSystemVirtualizer.cs
+++ b/GVFS/GVFS.Virtualization/FileSystem/FileSystemVirtualizer.cs
@@ -310,7 +310,8 @@ protected void OnFilePreConvertToFull(string relativePath)
bool isFolder;
string fileName;
bool isPathProjected = this.FileSystemCallbacks.GitIndexProjection.IsPathProjected(relativePath, out fileName, out isFolder);
- if (isPathProjected)
+ bool wasDehydrated = this.FileSystemCallbacks.IsDehydratedPlaceholder(relativePath);
+ if (isPathProjected || wasDehydrated)
{
this.FileSystemCallbacks.OnFileConvertedToFull(relativePath);
}
diff --git a/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs b/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs
index 310bd4414c..7604ba045b 100644
--- a/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs
+++ b/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs
@@ -14,6 +14,8 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
+using System.Security.Cryptography;
+using System.Text;
using System.Threading;
namespace GVFS.Virtualization
@@ -24,6 +26,24 @@ public class FileSystemCallbacks : IDisposable, IHeartBeatMetadataProvider
private const int NumberOfRetriesCheckingForDeleted = 10;
private const int MillisecondsToSleepBeforeCheckingForDeleted = 1;
+ // AllowDirtyData discards the bytes on disk, so it is used only for a file whose bytes
+ // are proven to be the blob (see TryDehydrateCleanFile).
+ private const UpdatePlaceholderType CleanFileDehydrateFlags =
+ UpdatePlaceholderType.AllowDirtyMetadata |
+ UpdatePlaceholderType.AllowReadOnly |
+ UpdatePlaceholderType.AllowDirtyData;
+
+ private const int ErrorSharingViolation = 32;
+ private const int ErrorLockViolation = 33;
+
+ // The attributes that a clean file keeps when it becomes a placeholder.
+ private const FileAttributes KeptFileAttributes =
+ FileAttributes.ReadOnly |
+ FileAttributes.Hidden |
+ FileAttributes.System |
+ FileAttributes.Archive |
+ FileAttributes.NotContentIndexed;
+
private static readonly GitCommandLineParser.Verbs LeavesProjectionUnchangedVerbs =
GitCommandLineParser.Verbs.AddOrStage |
GitCommandLineParser.Verbs.Commit |
@@ -37,6 +57,11 @@ public class FileSystemCallbacks : IDisposable, IHeartBeatMetadataProvider
private IPlaceholderCollection placeholderDatabase;
private ModifiedPathsDatabase modifiedPaths;
private ConcurrentHashSet newlyCreatedFileAndFolderPaths;
+
+ // Files that TryDehydrateCleanFile made placeholders. The projection can lack such a file
+ // until Git writes the index and the projection is parsed again, so the first conversion
+ // to a full file must make the file a modified path without the projection.
+ private ConcurrentHashSet dehydratedPlaceholders;
private ConcurrentDictionary filePlaceHolderCreationCount;
private ConcurrentDictionary folderPlaceHolderCreationCount;
private ConcurrentDictionary fileHydrationCount;
@@ -73,6 +98,7 @@ public FileSystemCallbacks(
this.folderPlaceHolderCreationCount = new ConcurrentDictionary(GVFSPlatform.Instance.Constants.PathComparer);
this.fileHydrationCount = new ConcurrentDictionary(GVFSPlatform.Instance.Constants.PathComparer);
this.newlyCreatedFileAndFolderPaths = new ConcurrentHashSet(GVFSPlatform.Instance.Constants.PathComparer);
+ this.dehydratedPlaceholders = new ConcurrentHashSet(GVFSPlatform.Instance.Constants.PathComparer);
string error;
if (!ModifiedPathsDatabase.TryLoadOrCreate(
@@ -392,6 +418,215 @@ public bool TryDehydrateFolder(string relativePath, out string errorMessage)
return string.IsNullOrEmpty(errorMessage);
}
+ ///
+ /// Return a modified file that has the content of to a placeholder
+ /// for that blob, and remove it from ModifiedPaths.
+ ///
+ ///
+ /// A full file that is not a modified path loses later in-place and memory-mapped writes:
+ /// the file system reports no event that makes it a modified path again, so Git does not
+ /// see the write. A placeholder becomes a modified path at its first write (see
+ /// ). The conversion discards the bytes on disk, so
+ /// this method first proves that they are exactly the blob: it opens the file without
+ /// write sharing, compares the size, and hashes the bytes as Git hashes a blob. While that
+ /// handle is open, no process can open the file for writing, and the open fails if a
+ /// process already has it open for writing. The handle shares delete access, because the
+ /// virtualization layer needs it to convert the file. So, just before the conversion,
+ /// this method checks that the path still names the hashed file and that no delete of
+ /// the file is pending. A rename over the path between that check and the conversion is
+ /// not detected.
+ ///
+ /// Order: (1) convert the file, (2) add the placeholder, (3) remove the modified path. The
+ /// file has the content of the blob after each step, so a stop between two steps loses
+ /// nothing. A path that is not a modified path while its index entry has no skip-worktree
+ /// bit becomes a modified path again at the next validation of the modified paths.
+ ///
+ ///
+ /// The caller must hold the GVFS lock for a Git command that waits, and must make Git
+ /// write the index afterwards, so that Git sets the skip-worktree bit of the file.
+ ///
+ ///
+ /// The path relative to the working-tree root, with forward slashes.
+ /// The blob that the index entry and HEAD have for the path.
+ public CleanFileDehydrateResult TryDehydrateCleanFile(string gitPath, HeadBlob blob)
+ {
+ ArgumentException.ThrowIfNullOrEmpty(gitPath);
+ string platformPath = gitPath.Replace(GVFSConstants.GitPathSeparator, Path.DirectorySeparatorChar);
+ if (!this.modifiedPaths.Contains(platformPath, isFolder: false))
+ {
+ return CleanFileDehydrateResult.NotModifiedPath;
+ }
+
+ string fullPath = Path.Combine(this.context.Enlistment.WorkingDirectoryBackingRoot, platformPath);
+ bool converted = false;
+ try
+ {
+ using (Stream stream = this.context.FileSystem.OpenFileStream(
+ fullPath,
+ FileMode.Open,
+ FileAccess.Read,
+ FileShare.Read | FileShare.Delete,
+ FileOptions.SequentialScan,
+ callFlushFileBuffers: false))
+ {
+ if (stream.Length != blob.Size || !HasBlobContent(stream, blob))
+ {
+ return CleanFileDehydrateResult.ContentDiffers;
+ }
+
+ FileProperties properties = this.context.FileSystem.GetFileProperties(fullPath);
+ FileAttributes attributes = properties.FileAttributes & KeptFileAttributes;
+ DateTime now = DateTime.UtcNow;
+
+ // Add the path before the conversion: a write right after the conversion
+ // must find it.
+ this.dehydratedPlaceholders.Add(platformPath);
+ if (!this.context.FileSystem.IsOpenFileAtPath(stream, fullPath))
+ {
+ this.dehydratedPlaceholders.TryRemove(platformPath);
+ return CleanFileDehydrateResult.Replaced;
+ }
+
+ FileSystemResult result = this.fileSystemVirtualizer.UpdatePlaceholderIfNeeded(
+ platformPath,
+ creationTime: FileTimeOrNow(properties.CreationTimeUTC, now),
+ lastAccessTime: FileTimeOrNow(properties.LastAccessTimeUTC, now),
+ lastWriteTime: FileTimeOrNow(properties.LastWriteTimeUTC, now),
+ changeTime: FileTimeOrNow(properties.LastWriteTimeUTC, now),
+ fileAttributes: attributes == 0 ? FileAttributes.Archive : attributes,
+ endOfFile: blob.Size,
+ shaContentId: blob.Sha,
+ updateFlags: CleanFileDehydrateFlags,
+ failureReason: out UpdateFailureReason failureReason);
+ if (result.Result != FSResult.Ok)
+ {
+ EventMetadata metadata = this.CreateEventMetadata(platformPath);
+ metadata.Add("Result", result.Result.ToString());
+ metadata.Add("RawResult", result.RawResult);
+ metadata.Add("FailureReason", failureReason.ToString());
+ this.context.Tracer.RelatedEvent(EventLevel.Informational, nameof(this.TryDehydrateCleanFile) + "_UpdateFailed", metadata);
+ return CleanFileDehydrateResult.PlaceholderUpdateFailed;
+ }
+
+ converted = true;
+
+ // The handle stays open until the modified path is gone, so that no process
+ // can open the placeholder for writing before then. A write after that
+ // converts the placeholder again and makes it a modified path.
+ return this.FinishCleanFileDehydrate(platformPath, blob);
+ }
+ }
+ catch (Exception e) when (e is FileNotFoundException || e is DirectoryNotFoundException)
+ {
+ return CleanFileDehydrateResult.NotFound;
+ }
+ catch (IOException e) when (IsSharingViolation(e))
+ {
+ return CleanFileDehydrateResult.InUse;
+ }
+ catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
+ {
+ EventMetadata metadata = this.CreateEventMetadata(platformPath, e);
+ this.context.Tracer.RelatedWarning(metadata, nameof(this.TryDehydrateCleanFile) + ": the file could not be checked");
+ return CleanFileDehydrateResult.Failed;
+ }
+ finally
+ {
+ if (!converted)
+ {
+ this.dehydratedPlaceholders.TryRemove(platformPath);
+ }
+ }
+ }
+
+ ///
+ /// Return true when made
+ /// a placeholder, and the file did not become full since then. Forget the path, so the
+ /// caller must make the file a modified path when it converts to full.
+ ///
+ public bool IsDehydratedPlaceholder(string relativePath)
+ {
+ return this.dehydratedPlaceholders.TryRemove(relativePath);
+ }
+
+ // Steps (2) and (3) of TryDehydrateCleanFile, after the conversion.
+ private CleanFileDehydrateResult FinishCleanFileDehydrate(string platformPath, HeadBlob blob)
+ {
+ try
+ {
+ this.placeholderDatabase.AddFile(platformPath, blob.Sha);
+ }
+ catch (GVFSDatabaseException e)
+ {
+ // The file is a placeholder with the content of the blob, and it stays a modified
+ // path, so Git still sees it.
+ EventMetadata metadata = this.CreateEventMetadata(platformPath, e);
+ this.context.Tracer.RelatedWarning(metadata, nameof(this.TryDehydrateCleanFile) + ": the placeholder could not be added");
+ return CleanFileDehydrateResult.Failed;
+ }
+
+ // TryRemove can fail after it removed the entry from memory, and before it wrote the
+ // removal to disk. Git then does not see the file, as after a removal.
+ if (!this.modifiedPaths.TryRemove(platformPath, isFolder: false, isRetryable: out _) &&
+ this.modifiedPaths.Contains(platformPath, isFolder: false))
+ {
+ return CleanFileDehydrateResult.ModifiedPathNotRemoved;
+ }
+
+ return CleanFileDehydrateResult.Dehydrated;
+ }
+
+ ///
+ /// Add a file that removed back to ModifiedPaths.
+ ///
+ /// The path relative to the working-tree root, with forward slashes.
+ public bool TryRestoreModifiedPath(string gitPath)
+ {
+ ArgumentException.ThrowIfNullOrEmpty(gitPath);
+ string platformPath = gitPath.Replace(GVFSConstants.GitPathSeparator, Path.DirectorySeparatorChar);
+ return this.modifiedPaths.TryAdd(platformPath, isFolder: false, isRetryable: out _);
+ }
+
+ ///
+ /// Return true when has the bytes of :
+ /// the SHA-1 of "blob <size>\0" and the bytes is the object id.
+ ///
+ internal static bool HasBlobContent(Stream stream, HeadBlob blob)
+ {
+ using (IncrementalHash hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA1))
+ {
+ hash.AppendData(Encoding.ASCII.GetBytes("blob " + blob.Size.ToString(System.Globalization.CultureInfo.InvariantCulture) + "\0"));
+ byte[] buffer = new byte[81920];
+ long total = 0;
+ int read;
+ while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ total += read;
+ if (total > blob.Size)
+ {
+ return false;
+ }
+
+ hash.AppendData(buffer, 0, read);
+ }
+
+ return total == blob.Size &&
+ string.Equals(SHA1Util.HexStringFromBytes(hash.GetHashAndReset()), blob.Sha, StringComparison.OrdinalIgnoreCase);
+ }
+ }
+
+ private static bool IsSharingViolation(IOException e)
+ {
+ int win32Error = e.HResult & 0xFFFF;
+ return win32Error == ErrorSharingViolation || win32Error == ErrorLockViolation;
+ }
+
+ // A file time cannot be earlier than 1601.
+ private static DateTime FileTimeOrNow(DateTime time, DateTime now)
+ {
+ return time.Year >= 1601 ? time : now;
+ }
+
public void ForceIndexProjectionUpdate(bool invalidateProjection, bool invalidateModifiedPaths)
{
this.InvalidateState(invalidateProjection, invalidateModifiedPaths);
@@ -425,9 +660,12 @@ public bool IsPathOrParentInModifiedPaths(string path, bool isFolder)
/// Finds index entries that are staged (differ from HEAD) matching the given
/// pathspec, and adds them to ModifiedPaths. This prepares for an unstage operation
/// (e.g., restore --staged) by ensuring git will clear skip-worktree for these
- /// entries so it can detect their working tree state correctly.
- /// Files that were added (not in HEAD) are also written to disk from the git object
- /// store as full files, so they persist after projection changes.
+ /// entries so it can detect their working tree state correctly. Each path is also
+ /// reported to the working-tree change observer (see
+ /// ).
+ /// Files that were added (not in HEAD) and were not modified paths yet are also
+ /// written to disk from the git object store as full files, so they persist after
+ /// projection changes.
///
///
/// IPC message body. Formats:
@@ -493,16 +731,17 @@ public bool AddStagedFilesToModifiedPaths(string messageBody, out int addedCount
return;
}
- string platformPath = gitPath.Replace(GVFSConstants.GitPathSeparator, Path.DirectorySeparatorChar);
- if (this.modifiedPaths.TryAdd(platformPath, isFolder: false, isRetryable: out _))
+ if (this.TryAddStagedFileToModifiedPaths(gitPath, out bool wasModifiedPath))
{
added++;
}
// Added files (in index but not in HEAD) are ProjFS placeholders that
// would vanish when the projection reverts to HEAD. Collect them for
- // hydration below.
- if (status.StartsWith("A"))
+ // hydration below. A path that already was a modified path is a file that
+ // the user or Git owns in the working tree, and it can have unstaged
+ // changes, so it is not overwritten with the staged content.
+ if (!wasModifiedPath && status.StartsWith("A"))
{
addedFilePaths.Add(gitPath);
}
@@ -630,6 +869,41 @@ public bool AddStagedFilesToModifiedPaths(string messageBody, out int addedCount
return success;
}
+ ///
+ /// Add one staged file to ModifiedPaths, and report it to the working-tree change
+ /// observer.
+ ///
+ ///
+ /// git reset --soft changes which files are staged without a file system write, so
+ /// no callback reports these paths. With a sparse index, Git clears skip-worktree only for
+ /// a path that has its own index entry, so the cone must include the path before Git
+ /// unstages it. The observer makes a cone change pending when the cone does not include
+ /// the path.
+ ///
+ /// The path relative to the working-tree root, with forward slashes.
+ ///
+ /// True when ModifiedPaths already had the path or one of its parent folders before this call.
+ ///
+ /// True when ModifiedPaths has the path or one of its parent folders.
+ internal bool TryAddStagedFileToModifiedPaths(string gitPath, out bool wasModifiedPath)
+ {
+ wasModifiedPath = false;
+ if (string.IsNullOrEmpty(gitPath))
+ {
+ return false;
+ }
+
+ string platformPath = gitPath.Replace(GVFSConstants.GitPathSeparator, Path.DirectorySeparatorChar);
+ wasModifiedPath = this.IsPathOrParentInModifiedPaths(platformPath, isFolder: false);
+ if (!this.modifiedPaths.TryAdd(platformPath, isFolder: false, isRetryable: out _))
+ {
+ return false;
+ }
+
+ this.NotifyWorkingDirectoryChange(platformPath, isFolder: false);
+ return true;
+ }
+
///
/// Writes the staged (index) versions of files to the working directory as
/// full files, bypassing ProjFS. Uses "git checkout-index --force" with
diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs
index 74a0fc2879..11f5588dcf 100644
--- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs
+++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs
@@ -681,6 +681,23 @@ public virtual bool IsPathProjected(string virtualPath, out string fileName, out
return false;
}
+ ///
+ /// Return true when the projection has a file at for the
+ /// blob . The projection has a file only when its index entry had
+ /// the skip-worktree bit when the projection was last parsed.
+ ///
+ public virtual bool IsFileProjectedWithSha(string virtualPath, string sha)
+ {
+ this.GetChildNameAndParentKey(virtualPath, out string fileName, out string parentKey);
+ FolderEntryData data = this.GetProjectedFolderEntryData(
+ blobSizesConnection: null,
+ childName: fileName,
+ parentKey: parentKey);
+
+ return data is FileData fileData &&
+ string.Equals(fileData.ConvertShaToString(), sha, StringComparison.OrdinalIgnoreCase);
+ }
+
public virtual ProjectedFileInfo GetProjectedFileInfo(
CancellationToken cancellationToken,
BlobSizes.BlobSizesConnection blobSizesConnection,