From ff9957f8c242f892c78812d9581ab2a874828a00 Mon Sep 17 00:00:00 2001 From: Tyrie Vella Date: Tue, 17 Nov 2026 00:38:39 -0800 Subject: [PATCH] Widen the sparse-index cone for working-tree changes When a user edits, creates, or deletes a file outside the sparse-index cone without a Git command, GVFS records the path in the modified paths, but the cone does not change. The directory of the file stays a sparse-directory entry, so the index has no entry for the file, and the virtual file system hook cannot clear its skip-worktree bit. Git then does not see the change: "git status" does not list it, "git add ." stops with "outside of your sparse-checkout definition", and "git commit -a" leaves it out. The file system callbacks now report each created, written, renamed, or deleted path to the cone manager. When the applied cone does not include the path, the callback creates the file .gvfs\ConeChangePending and returns. It does not wait for a Git command. The pre-command hook checks that file. If it exists, the hook sends a new ConeApply request before Git reads the index. The mount applies the cone of all modified paths, as for a widen, while the command holds the GVFS lock. As for a widen, the hook sends the request within the send budget, and after the send it waits for the reply up to the reply ceiling, so that Git does not run while the mount's Git holds the index lock. A command that reads the index without the lock (for example "git diff", or "git status" with optional locks off) takes the lock for the apply and releases it before Git runs. The apply shares the widen path in the mount, so the mount starts Git only while the requester holds the GVFS lock and the request is not too late. A failed apply keeps the change pending for the next Git command. The background task that adds a changed path to the modified paths waits while a Git command holds the GVFS lock. A change that arrives before its modified path therefore stays in the cone until the modified paths have it, or until a check finds it clean. The cone includes a modified file only while the file can differ from HEAD. After a Git command releases the GVFS lock, and when changes inside the cone stop for two seconds, the mount runs "git status --porcelain=v2 --untracked-files=normal" on its own thread. It writes a cone file without the modified files that Git does not list, alone or in an untracked folder. Under a virtual file system, Git looks for untracked files only in the paths that the mount reports. If another process has the cone file open, the mount writes it again after the delay, without Git. Git does not collapse the directories of clean files while they are modified paths, because the virtual file system hook clears their skip-worktree bits. The next change to such a file makes the apply include it again. When Git advertises "feature: vfs-sparse-index", it changes only the index when the cone changes, so the mount does not refuse a widen that expands the directory of a deleted file. The mount also skips the sparse-directory probe for a deleted file or modified folder that the applied cone already includes. Assisted-by: Claude Opus 5.5 Signed-off-by: Tyrie Vella --- GVFS/GVFS.Common/GVFSConstants.cs | 6 + GVFS/GVFS.Common/Git/GitProcess.cs | 68 ++ .../ConeManagementNamedPipeMessages.cs | 50 + .../Sparse/AutoSparseIndexConeManager.cs | 904 ++++++++++++++++-- .../Sparse/IConeManagerEnvironment.cs | 28 + .../Sparse/IWorkingDirectoryChangeObserver.cs | 16 + .../AutoSparseIndexConeTests.cs | 128 +-- .../AutoSparseIndexTestsBase.cs | 179 ++++ .../AutoSparseIndexWorkingTreeTests.cs | 374 ++++++++ GVFS/GVFS.Hooks/ConeRequestOutcome.cs | 13 +- GVFS/GVFS.Hooks/PendingConeChangeHook.cs | 363 +++++++ GVFS/GVFS.Hooks/Program.ConeManagement.cs | 77 +- GVFS/GVFS.Hooks/Program.cs | 7 +- GVFS/GVFS.Mount/InProcessMount.cs | 34 +- .../GVFS.Mount/MountConeManagerEnvironment.cs | 77 ++ .../WindowsFileSystemVirtualizer.cs | 2 +- .../Sparse/AutoSparseIndexConeManagerTests.cs | 540 ++++++++++- GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj | 3 + GVFS/GVFS.UnitTests/Git/GitProcessTests.cs | 13 + .../Hooks/PendingConeChangeHookTests.cs | 299 ++++++ .../FileSystemCallbacksTests.cs | 59 ++ .../FileSystemCallbacks.cs | 45 + 22 files changed, 3099 insertions(+), 186 deletions(-) create mode 100644 GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs create mode 100644 GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs create mode 100644 GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexWorkingTreeTests.cs create mode 100644 GVFS/GVFS.Hooks/PendingConeChangeHook.cs create mode 100644 GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs diff --git a/GVFS/GVFS.Common/GVFSConstants.cs b/GVFS/GVFS.Common/GVFSConstants.cs index 0f6ce06de..425e9b3d4 100644 --- a/GVFS/GVFS.Common/GVFSConstants.cs +++ b/GVFS/GVFS.Common/GVFSConstants.cs @@ -177,6 +177,12 @@ public static class DotGVFS public const string LogName = "logs"; public const string MountLock = "mount.lock"; + /// + /// The mount creates this file when a working-tree change needs a sparse-index cone + /// change that the index does not have yet. The pre-command hook checks it. + /// + public const string ConeChangePending = "ConeChangePending"; + public static class Databases { public const string Name = "databases"; diff --git a/GVFS/GVFS.Common/Git/GitProcess.cs b/GVFS/GVFS.Common/Git/GitProcess.cs index 2fe762d46..edcbd728b 100644 --- a/GVFS/GVFS.Common/Git/GitProcess.cs +++ b/GVFS/GVFS.Common/Git/GitProcess.cs @@ -896,6 +896,43 @@ public Result ListSparseDirectories(Action onSparseDirectory) }); } + /// + /// List the paths that differ between HEAD and the index or the working tree, with + /// git status --porcelain=v2: changed and unmerged tracked paths, and untracked + /// files. An untracked folder ends with '/'. Git does not list ignored files. + /// + /// + /// git status reads a sparse index without expanding it, and it compares the + /// content of a file whose stat data changed, so a file that has the content of HEAD + /// again is not listed. --no-optional-locks stops Git from writing the refreshed + /// index, so this does not need the GVFS lock. --no-deserialize stops Git from + /// reading the GVFS status cache. The virtual file system stays on, so Git checks only + /// the paths that the mount reports, and it looks for untracked files only there. + /// COMMAND_HOOK_LOCK makes Git skip the pre-command and post-command hooks. + /// + public Result ListPathsThatDifferFromHead(Action onPath, int timeoutMs) + { + ArgumentNullException.ThrowIfNull(onPath); + + return this.InvokeGitImpl( + "--no-optional-locks status --porcelain=v2 -z --untracked-files=normal --no-renames --ignore-submodules=all --no-deserialize", + workingDirectory: this.workingDirectoryRoot, + dotGitDirectory: null, + useReadObjectHook: true, + writeStdIn: null, + parseStdOutLine: null, + timeoutMs: timeoutMs, + usePreCommandHook: false, + parseStdOutToken: record => + { + string path = GetPorcelainV2Path(record); + if (path != null) + { + onPath(path); + } + }); + } + /// Run git version --build-options. public Result VersionBuildOptions() { @@ -924,6 +961,37 @@ internal static bool HasBuildOption(string buildOptionsOutput, string option) return false; } + /// + /// Return the path of a git status --porcelain=v2 -z record for a changed, + /// unmerged, or untracked entry, or null for any other record. The path of an untracked + /// folder ends with '/'. + /// + internal static string GetPorcelainV2Path(string record) + { + // "1 XY sub mH mI mW hH hI path", "u XY sub m1 m2 m3 mW h1 h2 h3 path", and + // "? path". The path is the rest of the record, so it can contain spaces. + int pathField; + if (record.StartsWith("1 ", StringComparison.Ordinal)) + { + pathField = 8; + } + else if (record.StartsWith("u ", StringComparison.Ordinal)) + { + pathField = 10; + } + else if (record.StartsWith("? ", StringComparison.Ordinal)) + { + pathField = 1; + } + else + { + return null; + } + + string[] fields = record.Split(' ', pathField + 1); + return fields.Length == pathField + 1 && fields[pathField].Length > 0 ? fields[pathField] : null; + } + public Result Status(bool allowObjectDownloads, bool useStatusCache, bool showUntracked = false) { string command = "status"; diff --git a/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs index be774e38b..cdb33f93e 100644 --- a/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs +++ b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs @@ -37,6 +37,13 @@ public static partial class NamedPipeMessages /// no longer runs. /// /// + /// When a working-tree change needs a cone change that the index does not have yet, + /// the mount creates the file. The + /// pre-command hook then sends an before Git reads the index, + /// also for a command that names no paths. The requesting Git process must hold the + /// GVFS lock, as for a widen. + /// + /// /// A body is a list of fields separated by NUL. The header and the body split on the /// first '|' only, so a field can contain '|'. /// @@ -45,6 +52,7 @@ public static class ConeManagement { public const string WidenRequest = "ConeWiden"; public const string NarrowRequest = "ConeNarrow"; + public const string ApplyRequest = "ConeApply"; /// The mount applied the request. public const string SuccessResult = "S"; @@ -73,6 +81,13 @@ public static class ConeManagement /// public const int WidenReplyCeilingMs = 10000; + /// + /// The time in which the mount applies a pending working-tree change. A slower apply + /// is a warning. The hook waits for the apply reply up to + /// , for the same reason as for a widen. + /// + public const int ApplyWaitBudgetMs = 5000; + /// /// The maximum time that the post-command hook waits for a narrow reply. Git has /// already run, so this wait only delays the return to the user. @@ -225,6 +240,41 @@ public static bool TryParse(string body, out NarrowParameters parameters) return true; } } + + /// + /// Parameters for an apply request: the command id of the Git command that holds the + /// GVFS lock and waits for the mount to apply the pending cone change. + /// + public class ApplyParameters + { + public ApplyParameters(string commandId) + { + this.CommandId = commandId ?? string.Empty; + } + + /// The Git process id, as decimal digits, or empty. + public string CommandId { get; } + + public string ToBody() + { + return this.CommandId; + } + + /// + /// Parse an apply body. Return false when the command id is not valid. + /// + public static bool TryParse(string body, out ApplyParameters parameters) + { + parameters = null; + if (!IsValidCommandId(body)) + { + return false; + } + + parameters = new ApplyParameters(body); + return true; + } + } } } } diff --git a/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs index a38e67e7c..f25e433ba 100644 --- a/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs +++ b/GVFS/GVFS.Common/Sparse/AutoSparseIndexConeManager.cs @@ -3,10 +3,13 @@ using GVFS.Common.NamedPipes; using GVFS.Common.Tracing; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; +using System.Linq; using System.Threading; +using System.Threading.Tasks; namespace GVFS.Common.Sparse { @@ -15,7 +18,8 @@ namespace GVFS.Common.Sparse /// gvfs.auto-sparse-index is true. /// /// - /// The cone is computed from the modified paths plus the transient paths of every Git + /// The cone is computed from the modified paths that can differ from HEAD, plus the changed + /// paths that the modified paths do not have yet, plus the transient paths of every Git /// command that widened and did not narrow yet (see ). /// When the last command narrows, the cone is again the cone of the modified paths. /// @@ -23,15 +27,17 @@ namespace GVFS.Common.Sparse /// so that the index has entries for the new directories before Git runs. If Git fails, /// restore the previous cone file. Only the Git command that holds the GVFS lock can /// widen: it waits in its pre-command hook, so no other Git command writes the index. - /// The cone does not include the directory of a deleted file that a sparse-directory entry - /// hides (see ). + /// Unless Git changes only the index when the cone changes + /// (), the cone does not + /// include the directory of a deleted file that a sparse-directory entry hides (see + /// ). /// /// - /// Narrow: write the new cone file only. The narrow arrives after the post-command hook - /// released the GVFS lock, so the mount cannot replace the index (see - /// ). The index keeps the expanded - /// entries, all skip-worktree, until the next widen collapses every directory outside the - /// cone. + /// Narrow: write the new cone file only, after the post-command hook of a command that + /// widened, or after a background check (see below). The mount cannot replace the index then + /// (see ). The index keeps the expanded + /// entries until the next widen collapses each directory outside the cone whose entries + /// are all skip-worktree. /// /// /// Locks: a process-internal lock serializes all requests. Then the manager takes the lock @@ -45,8 +51,30 @@ namespace GVFS.Common.Sparse /// Every failure lets Git run, because the hook treats any reply other than success as /// "not applied". Git then expands the index in memory, which is slower but correct. /// + /// + /// Working-tree changes: Git sees a change to a file only when the index has an entry for + /// it, and git add takes a path only when the cone includes it. The file system + /// callbacks report every created, written, renamed, or deleted path (see + /// ). When the applied cone does not include the + /// path, the manager creates the pending file (see + /// ). The callback does not + /// wait for a Git command. The pre-command hook of the next Git command that reads the + /// index sees the file and sends an apply request while that command holds the GVFS lock. + /// The apply widens the cone like a widen without request paths. If the apply fails, the + /// change stays pending for the next Git command. + /// + /// + /// Clean paths: the cone includes a modified path only while the path can differ from HEAD. + /// After a Git command releases the GVFS lock, and when changes inside the applied cone stop + /// for , a background check (see + /// ) asks Git which paths differ from HEAD. A modified + /// file that matches HEAD, the index, and the working tree is clean, and the manager writes + /// a cone file without it. Git cannot collapse its directory while the file is a modified + /// path, because the virtual file system hook clears its skip-worktree bit, so the index + /// keeps its entry. The next change to the file makes it a candidate again. + /// /// - public class AutoSparseIndexConeManager + public class AutoSparseIndexConeManager : IWorkingDirectoryChangeObserver { /// A widen with more paths is refused, and Git expands the index in memory. public const int MaxWidenPaths = 1000; @@ -58,8 +86,16 @@ public class AutoSparseIndexConeManager /// public const string SparseIndexFeature = "feature: vfs-sparse-index"; + /// + /// After a change inside the applied cone, the manager waits until no change came for + /// this long, and then checks which modified files match HEAD again. + /// + public const int DefaultChangeCheckDelayMs = 2000; + private const string WidenEventName = "ConeWiden"; private const string NarrowEventName = "ConeNarrow"; + private const string ApplyEventName = "ConeApply"; + private const string ReconcileEventName = "ConeReconcile"; private const int MaxTracedPaths = 10; // The mount does not start Git for a widen later than this after it got the request: @@ -71,6 +107,12 @@ public class AutoSparseIndexConeManager // refuses only when reapply could not finish inside the ceiling. internal const int DefaultMaxElapsedBeforeApplyMs = NamedPipeMessages.ConeManagement.WidenReplyCeilingMs / 2; + // A check that cannot write the cone file tries again after the change-check delay, at + // most this many times in a row. The next Git command that ends tries again too. + private const int MaxReconcileWriteRetries = 5; + + private static readonly IReadOnlyList NoPaths = new List(); + private readonly ITracer tracer; private readonly PhysicalFileSystem fileSystem; private readonly ConeFileWriter coneFileWriter; @@ -80,6 +122,14 @@ public class AutoSparseIndexConeManager private readonly int maxElapsedBeforeApplyMs; private readonly TransientConeState transientState = new TransientConeState(); private readonly Lock coneLock = new Lock(); + private readonly Lock pendingLock = new Lock(); + private readonly Lock reconcileScheduleLock = new Lock(); + private readonly StringComparer pathComparer; + private readonly int changeCheckDelayMs; + private readonly Timer changeCheckTimer; + + // The working-tree paths that changed since an apply or a check last used them. + private readonly ConcurrentDictionary changedPaths; // True when the index can have sparse-directory entries that do not match the cone // file: before the first widen of this mount, after a narrow, and after a failure. @@ -95,13 +145,40 @@ public class AutoSparseIndexConeManager // in the cone file either. private HashSet hiddenModifiedPaths = new HashSet(StringComparer.Ordinal); + // The modified files that the last check found equal to HEAD, the index, and the working + // tree. The cone leaves them out. Guarded by coneLock. + private HashSet cleanPaths; + + // Changed paths that an apply used before the modified paths had them (see + // ConsumeChanges). The cone includes them. Guarded by coneLock. + private HashSet unconfirmedPaths; + + // The directories that the cone file includes and the index expands, or null when that + // is not known. + private AppliedConeSnapshot appliedCone; + + private long changeSequence; + private bool isPending; + + // Changes when an apply or a widen uses the changed paths, so that a check that started + // before it does not use its result. Guarded by coneLock. + private long consumeEpoch; + + // The state that the last check saw. A check with the same state does not run Git again. + private (long ChangeSequence, long ConsumeEpoch, long RepositoryStamp)? lastReconcileState; + + private bool reconcileRunning; + private bool reconcileRequested; + private int reconcileWriteRetries; + private volatile bool isStopped; + public AutoSparseIndexConeManager( ITracer tracer, PhysicalFileSystem fileSystem, string sparseCheckoutPath, bool ignoreCase, IConeManagerEnvironment environment) - : this(tracer, fileSystem, sparseCheckoutPath, ignoreCase, environment, DefaultMaxElapsedBeforeApplyMs) + : this(tracer, fileSystem, sparseCheckoutPath, ignoreCase, environment, DefaultMaxElapsedBeforeApplyMs, DefaultChangeCheckDelayMs) { } @@ -111,7 +188,8 @@ internal AutoSparseIndexConeManager( string sparseCheckoutPath, bool ignoreCase, IConeManagerEnvironment environment, - int maxElapsedBeforeApplyMs) + int maxElapsedBeforeApplyMs, + int changeCheckDelayMs) { ArgumentNullException.ThrowIfNull(tracer); ArgumentNullException.ThrowIfNull(fileSystem); @@ -125,6 +203,12 @@ internal AutoSparseIndexConeManager( this.ignoreCase = ignoreCase; this.environment = environment; this.maxElapsedBeforeApplyMs = maxElapsedBeforeApplyMs; + this.pathComparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; + this.changedPaths = new ConcurrentDictionary(this.pathComparer); + this.cleanPaths = new HashSet(this.pathComparer); + this.unconfirmedPaths = new HashSet(this.pathComparer); + this.changeCheckDelayMs = changeCheckDelayMs; + this.changeCheckTimer = new Timer(_ => this.ScheduleReconcile(), state: null, Timeout.Infinite, Timeout.Infinite); } private enum ConeChange @@ -148,6 +232,12 @@ private enum ConeChange WriteFailed, ApplyFailed, UnexpectedException, + ConeChangePending, + NothingChanged, + StateChanged, + CleanPathChanged, + DiffFailed, + Stopped, } /// @@ -162,8 +252,9 @@ public static bool GitSupportsSparseIndex(GitProcess.Result buildOptions) } /// - /// Handle a or - /// and return the reply. + /// Handle a , + /// , or + /// and return the reply. /// /// The cone manager, or null when the feature is off. /// Traces a request that is not valid. @@ -201,6 +292,16 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t succeeded = manager.TryNarrow(narrow); break; + case NamedPipeMessages.ConeManagement.ApplyRequest: + if (!NamedPipeMessages.ConeManagement.ApplyParameters.TryParse(message.Body, out NamedPipeMessages.ConeManagement.ApplyParameters apply)) + { + TraceInvalidRequest(tracer, message.Header); + return NamedPipeMessages.ConeManagement.FailureResult; + } + + succeeded = manager.TryApply(apply); + break; + default: throw new ArgumentException($"'{message.Header}' is not a cone request.", nameof(message)); } @@ -210,7 +311,7 @@ public static string HandleRequest(AutoSparseIndexConeManager manager, ITracer t /// /// Add the paths of a Git command to the cone and update the index. The hook waits for - /// the result before Git runs. + /// the result before Git runs. The cone also gets every pending working-tree change. /// /// True when the cone and the index include the paths. public bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters) @@ -221,7 +322,9 @@ public bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters EventMetadata metadata = this.CreateMetadata(parameters.CommandId); metadata.Add("PathCount", parameters.Paths.Count); - ConeChange change = this.RunAndCatch(() => this.Widen(parameters, stopwatch, metadata), metadata); + ApplyAttempt attempt = new ApplyAttempt(); + ConeChange change = this.RunAndCatch(() => this.Widen(parameters, attempt, stopwatch, metadata), metadata); + this.RearmPendingAfterAttempt(attempt, change, requestHasPaths: true, metadata); bool succeeded = change == ConeChange.Applied || change == ConeChange.ConeUnchanged; // A widen slower than WidenWaitBudgetMs is a warning. The hook waits for the reply up @@ -230,6 +333,155 @@ public bool TryWiden(NamedPipeMessages.ConeManagement.WidenParameters parameters return succeeded; } + /// + /// Apply the pending working-tree changes to the cone and the index before a Git command + /// reads the index. The hook waits for the result before Git runs. + /// + /// True when the cone and the index include every pending change. + public bool TryApply(NamedPipeMessages.ConeManagement.ApplyParameters parameters) + { + ArgumentNullException.ThrowIfNull(parameters); + + Stopwatch stopwatch = Stopwatch.StartNew(); + EventMetadata metadata = this.CreateMetadata(parameters.CommandId); + + ApplyAttempt attempt = new ApplyAttempt(); + ConeChange change = this.RunAndCatch( + () => TryGetProcessId(parameters.CommandId, out int processId) + ? this.ApplyCone(processId, NoPaths, attempt, stopwatch, metadata) + : ConeChange.NoCommandId, + metadata); + this.RearmPendingAfterAttempt(attempt, change, requestHasPaths: false, metadata); + bool succeeded = change == ConeChange.Applied || change == ConeChange.ConeUnchanged; + + this.TraceResult(ApplyEventName, change, stopwatch.ElapsedMilliseconds, NamedPipeMessages.ConeManagement.ApplyWaitBudgetMs, metadata); + return succeeded; + } + + /// + /// Start to track working-tree changes. Changes made while no mount ran do not reach the + /// manager, so the first Git command applies the cone of every modified path. + /// + public void Start() + { + this.SetPending(); + } + + /// Stop the background checks. Requests and callbacks after this do nothing. + public void Stop() + { + this.isStopped = true; + this.changeCheckTimer.Dispose(); + } + + /// + public void OnWorkingDirectoryPathChanged(string relativePath, bool isFolder) + { + if (this.isStopped || string.IsNullOrEmpty(relativePath)) + { + return; + } + + try + { + string path = NormalizeModifiedPath(relativePath, isFolder); + if (path.Length == 0 || path == GVFSConstants.GitPathSeparatorString) + { + return; + } + + // Record the change before reading the cone. A cone change then either sees this + // record, or this method sees the new cone (see PublishCone). + long sequence = Interlocked.Increment(ref this.changeSequence); + PathChange uncovered = new PathChange(sequence, WasCovered: false); + this.changedPaths[path] = uncovered; + + AppliedConeSnapshot cone = Volatile.Read(ref this.appliedCone); + if (cone != null && cone.IsCovered(path)) + { + this.changedPaths.TryUpdate(path, new PathChange(sequence, WasCovered: true), uncovered); + + // The file can have the content of HEAD again. Check when the changes stop. + this.changeCheckTimer.Change(this.changeCheckDelayMs, Timeout.Infinite); + } + else + { + this.SetPending(); + } + } + catch (ObjectDisposedException) when (this.isStopped) + { + } + catch (Exception e) when (e is not OutOfMemoryException) + { + // The cone can miss this change. The next Git command that names the path, or the + // next mount, adds it. + EventMetadata metadata = this.CreateMetadata(commandId: null); + metadata.Add("Exception", e.ToString()); + this.tracer.RelatedWarning(metadata, nameof(this.OnWorkingDirectoryPathChanged) + " failed", Keywords.Telemetry); + } + } + + /// + /// A Git command released the GVFS lock. Start a background check for modified files + /// that match HEAD again (see ). Returns at once. + /// + public void OnGitCommandCompleted() + { + this.ScheduleReconcile(); + } + + /// + /// Ask Git which paths differ from HEAD, and write a cone file without the modified files + /// that match HEAD. A clean file that differs again goes back into the cone. Git does not + /// write the index, and the manager does not wait for the GVFS lock. + /// + /// True when the check ran or was not needed. + public bool TryReconcile() + { + Stopwatch stopwatch = Stopwatch.StartNew(); + EventMetadata metadata = this.CreateMetadata(commandId: null); + ConeChange change = this.RunAndCatch(() => this.Reconcile(metadata), metadata); + + bool succeeded; + switch (change) + { + case ConeChange.NothingChanged: + case ConeChange.ConeChangePending: + case ConeChange.StateChanged: + case ConeChange.Stopped: + // Nothing to report: the check did not change anything. + return true; + + case ConeChange.Narrowed: + case ConeChange.ConeUnchanged: + case ConeChange.CleanPathChanged: + Interlocked.Exchange(ref this.reconcileWriteRetries, 0); + succeeded = true; + break; + + case ConeChange.WriteFailed: + case ConeChange.ConeFileLocked: + // Another process can have the cone file open, or a Git sparse-checkout + // command can hold its lock. No Git command has to end before the next try. + if (Interlocked.Increment(ref this.reconcileWriteRetries) <= MaxReconcileWriteRetries) + { + metadata.Add("RetryAfterMs", this.changeCheckDelayMs); + this.changeCheckTimer.Change(this.changeCheckDelayMs, Timeout.Infinite); + } + + succeeded = false; + break; + + default: + succeeded = false; + break; + } + + this.TraceResult(ReconcileEventName, change, stopwatch.ElapsedMilliseconds, waitBudgetMs: int.MaxValue, metadata); + return succeeded; + } + /// /// Remove the paths of a Git command from the cone. Git has already run. /// @@ -281,6 +533,7 @@ private static bool IsFailure(ConeChange change) case ConeChange.WriteFailed: case ConeChange.ApplyFailed: case ConeChange.UnexpectedException: + case ConeChange.DiffFailed: return true; default: @@ -288,7 +541,20 @@ private static bool IsFailure(ConeChange change) } } - private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parameters, Stopwatch stopwatch, EventMetadata metadata) + private static string NormalizeModifiedPath(string path, bool isFolder) + { + // The same form as the modified-paths database: forward slashes, no leading or + // trailing slash, and a trailing slash for a folder. + string normalized = path.Replace('\\', GVFSConstants.GitPathSeparator).Trim(GVFSConstants.GitPathSeparator); + return isFolder ? normalized + GVFSConstants.GitPathSeparatorString : normalized; + } + + private static bool IsFolderPath(string modifiedPath) + { + return modifiedPath.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal); + } + + private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parameters, ApplyAttempt attempt, Stopwatch stopwatch, EventMetadata metadata) { if (!parameters.IsValid()) { @@ -306,6 +572,21 @@ private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parame return ConeChange.NoCommandId; } + if (parameters.Paths.Count <= MaxTracedPaths) + { + metadata.Add("Paths", string.Join(";", parameters.Paths)); + } + + return this.ApplyCone(processId, parameters.Paths, attempt, stopwatch, metadata); + } + + /// + /// Write the cone of the modified paths, the transient paths, and + /// , and apply it to the index for the Git process that + /// holds the GVFS lock. + /// + private ConeChange ApplyCone(int processId, IReadOnlyList requestPaths, ApplyAttempt attempt, Stopwatch stopwatch, EventMetadata metadata) + { // Refuse a command that does not hold the GVFS lock before it waits for other // requests. The check runs again under the lock, because the holder can change. if (!this.environment.CanWriteIndex(processId)) @@ -320,11 +601,6 @@ private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parame return ConeChange.NotLockHolder; } - if (parameters.Paths.Count <= MaxTracedPaths) - { - metadata.Add("Paths", string.Join(";", parameters.Paths)); - } - this.RemoveEndedCommands(metadata); if (!this.TryGetStartTime(processId, out long startTime)) @@ -332,7 +608,7 @@ private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parame return ConeChange.CommandEnded; } - if (this.transientState.IsNarrowed(processId, startTime)) + if (requestPaths.Count > 0 && this.transientState.IsNarrowed(processId, startTime)) { return ConeChange.CommandAlreadyNarrowed; } @@ -342,13 +618,34 @@ private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parame return ConeChange.QueueWaitTooLong; } + // From here, this request applies every change that is pending now. A change + // after this point makes the pending file again (see OnWorkingDirectoryPathChanged). + attempt.ClearedPending = this.ClearPending(); + long consumedSequence = Interlocked.Read(ref this.changeSequence); + List modifiedPaths = new List(this.environment.GetModifiedPaths()); + this.ConsumeChanges(consumedSequence, modifiedPaths, metadata); // A modified file that exists keeps its content when Git expands its directory. - // A deleted file, or a modified folder, does not. Only those need the list of - // sparse-directory entries. - List unsafePaths = modifiedPaths.FindAll( - path => path.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal) || !this.environment.IsFileInWorkingDirectory(path)); + // A deleted file, or a modified folder, does not, unless Git changes only the + // index. Only those need the list of sparse-directory entries, and only when the + // applied cone does not already expand them. A clean path has no index entry that + // differs from the working tree. + AppliedConeSnapshot applied = Volatile.Read(ref this.appliedCone); + List unsafePaths = new List(); + if (!this.environment.SparsityChangeIsIndexOnly) + { + foreach (string path in modifiedPaths.Concat(this.unconfirmedPaths)) + { + if ((IsFolderPath(path) || !this.environment.IsFileInWorkingDirectory(path)) && + !this.cleanPaths.Contains(path) && + (applied == null || !applied.IsCovered(path))) + { + unsafePaths.Add(path); + } + } + } + List hidden = new List(); if (unsafePaths.Count > 0) { @@ -370,7 +667,7 @@ private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parame } List conePaths = this.GetConePaths(modifiedPaths, hiddenSet); - conePaths.AddRange(parameters.Paths); + conePaths.AddRange(requestPaths); if (!this.TryBuildCone(conePaths, metadata, out ConePatternSet cone)) { return ConeChange.InvalidPath; @@ -420,7 +717,8 @@ private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parame this.coneFileMayBeStale = false; if (writeResult == ConeFileWriteResult.Unchanged && !this.indexMayDifferFromCone) { - this.transientState.Add(processId, startTime, parameters.Paths); + this.AddTransientPaths(processId, startTime, requestPaths); + this.PublishCone(cone); return ConeChange.ConeUnchanged; } @@ -430,11 +728,18 @@ private ConeChange Widen(NamedPipeMessages.ConeManagement.WidenParameters parame { keepBackup = !this.TryRollBack(writeResult, coneFileExisted, backupPath, metadata); this.coneFileMayBeStale = keepBackup; + if (keepBackup) + { + // The cone file now has directories that the index did not expand. + this.PublishCone(null); + } + return ConeChange.ApplyFailed; } this.indexMayDifferFromCone = false; - this.transientState.Add(processId, startTime, parameters.Paths); + this.AddTransientPaths(processId, startTime, requestPaths); + this.PublishCone(cone); return ConeChange.Applied; } finally @@ -469,44 +774,75 @@ private ConeChange Narrow(NamedPipeMessages.ConeManagement.NarrowParameters para return ConeChange.NothingToNarrow; } - // Until the cone file is written, a later request must write it again. - this.coneFileMayBeStale = true; - - List modifiedPaths = new List(this.environment.GetModifiedPaths()); - if (!this.TryBuildCone(this.GetConePaths(modifiedPaths, this.hiddenModifiedPaths), metadata, out ConePatternSet cone)) + ConeChange change = this.WriteNarrowerCone(metadata); + if (change == ConeChange.Narrowed) { - return ConeChange.InvalidPath; + // The index keeps the directories of the transient paths until the next widen. + this.indexMayDifferFromCone = true; } - if (!this.environment.TryLockConeFile(out IDisposable coneFileLock, out Exception lockError)) - { - metadata.Add("LockError", lockError?.ToString()); - return ConeChange.ConeFileLocked; - } + return change; + } + } - using (coneFileLock) - { - ConeFileWriteResult writeResult = this.coneFileWriter.Write(this.sparseCheckoutPath, cone, out string backupPath, out Exception writeError); - metadata.Add("WriteResult", writeResult.ToString()); + /// + /// Write the cone of the modified paths and the transient paths without running Git. + /// The caller holds , and the new cone does not include a directory + /// that the index does not expand. + /// + private ConeChange WriteNarrowerCone(EventMetadata metadata) + { + // Until the cone file is written, a later request must write it again. + this.coneFileMayBeStale = true; - // The narrow does not run Git, so it never restores the previous file. - this.DeleteBackup(backupPath, metadata); + List modifiedPaths = new List(this.environment.GetModifiedPaths()); + List conePaths = this.GetConePaths(modifiedPaths, this.hiddenModifiedPaths); + if (!this.TryBuildCone(conePaths, metadata, out ConePatternSet cone)) + { + return ConeChange.InvalidPath; + } - switch (writeResult) - { - case ConeFileWriteResult.Failed: - metadata.Add("WriteError", writeError?.ToString()); - return ConeChange.WriteFailed; + // A modified path that is newer than the last apply can be in a directory that the + // index does not expand. The cone file then has it, so the next apply must run Git + // even when the cone file does not change. + AppliedConeSnapshot applied = Volatile.Read(ref this.appliedCone); + bool hasUnappliedPaths = applied == null || conePaths.Exists(path => !applied.IsCovered(path)); - case ConeFileWriteResult.Unchanged: - this.coneFileMayBeStale = false; - return ConeChange.ConeUnchanged; + if (!this.environment.TryLockConeFile(out IDisposable coneFileLock, out Exception lockError)) + { + metadata.Add("LockError", lockError?.ToString()); + return ConeChange.ConeFileLocked; + } + + using (coneFileLock) + { + ConeFileWriteResult writeResult = this.coneFileWriter.Write(this.sparseCheckoutPath, cone, out string backupPath, out Exception writeError); + metadata.Add("WriteResult", writeResult.ToString()); - default: - this.coneFileMayBeStale = false; + // A narrow does not run Git, so it never restores the previous file. + this.DeleteBackup(backupPath, metadata); + + switch (writeResult) + { + case ConeFileWriteResult.Failed: + metadata.Add("WriteError", writeError?.ToString()); + return ConeChange.WriteFailed; + + case ConeFileWriteResult.Unchanged: + this.coneFileMayBeStale = false; + this.PublishConeIfKnown(cone); + return ConeChange.ConeUnchanged; + + default: + this.coneFileMayBeStale = false; + if (hasUnappliedPaths) + { + metadata.Add("HasUnappliedPaths", true); this.indexMayDifferFromCone = true; - return ConeChange.Narrowed; - } + } + + this.PublishConeIfKnown(cone); + return ConeChange.Narrowed; } } } @@ -592,16 +928,410 @@ private List GetConePaths(List modifiedPaths, HashSet ex List paths = new List(modifiedPaths.Count); foreach (string modifiedPath in modifiedPaths) { - if (!excludedModifiedPaths.Contains(modifiedPath)) + if (!excludedModifiedPaths.Contains(modifiedPath) && !this.cleanPaths.Contains(modifiedPath)) { paths.Add(modifiedPath); } } + foreach (string unconfirmedPath in this.unconfirmedPaths) + { + if (!excludedModifiedPaths.Contains(unconfirmedPath)) + { + paths.Add(unconfirmedPath); + } + } + paths.AddRange(this.transientState.GetAllPaths()); return paths; } + private void AddTransientPaths(int processId, long startTime, IReadOnlyList requestPaths) + { + if (requestPaths.Count > 0) + { + this.transientState.Add(processId, startTime, requestPaths); + } + } + + /// + /// Use the working-tree changes up to : a clean file that + /// changed can differ from HEAD again. The caller holds . + /// + /// + /// The mount adds a changed path to the modified paths in a background task, and that + /// task waits while a Git command holds the GVFS lock. So a change can arrive before + /// its modified path. Such a path stays in the cone as an unconfirmed path until the + /// modified paths have it, or until a check finds it clean. + /// + private void ConsumeChanges(long sequence, List modifiedPaths, EventMetadata metadata) + { + HashSet modified = new HashSet(modifiedPaths, this.pathComparer); + int consumed = 0; + foreach (KeyValuePair change in this.changedPaths) + { + if (change.Value.Sequence <= sequence && + ((ICollection>)this.changedPaths).Remove(change)) + { + this.cleanPaths.Remove(change.Key); + if (!IsModifiedPathOrUnderModifiedFolder(change.Key, modified)) + { + this.unconfirmedPaths.Add(change.Key); + } + + consumed++; + } + } + + this.RemoveConfirmedAndStalePaths(modified); + this.consumeEpoch++; + metadata.Add("ConsumedChangeCount", consumed); + metadata.Add("CleanPathCount", this.cleanPaths.Count); + if (this.unconfirmedPaths.Count > 0) + { + metadata.Add("UnconfirmedPathCount", this.unconfirmedPaths.Count); + } + } + + private static bool IsModifiedPathOrUnderModifiedFolder(string path, HashSet modified) + { + if (modified.Contains(path)) + { + return true; + } + + // The modified paths do not list a file or folder inside a modified folder. + string trimmed = path.TrimEnd(GVFSConstants.GitPathSeparator); + for (int separator = trimmed.LastIndexOf(GVFSConstants.GitPathSeparator); separator > 0; separator = trimmed.LastIndexOf(GVFSConstants.GitPathSeparator, separator - 1)) + { + if (modified.Contains(trimmed.Substring(0, separator + 1))) + { + return true; + } + } + + return false; + } + + private void RemoveConfirmedAndStalePaths(HashSet modified) + { + // A dehydrated file leaves the modified paths. It is not clean or dirty any more. + this.cleanPaths.RemoveWhere(path => !modified.Contains(path)); + this.unconfirmedPaths.RemoveWhere(path => IsModifiedPathOrUnderModifiedFolder(path, modified)); + } + + /// + /// Record that the index has entries for every directory of , and + /// that the cone file is . Null means that this is not known. + /// + private void PublishCone(ConePatternSet cone) + { + this.PublishSnapshot(cone == null ? null : new AppliedConeSnapshot(new ConeCoverage(cone))); + } + + /// + /// Record a cone file that the manager wrote without running Git. The index can lack + /// entries for a directory that the new cone adds, so only the directories that both + /// cones include count as applied. + /// + private void PublishConeIfKnown(ConePatternSet cone) + { + AppliedConeSnapshot current = Volatile.Read(ref this.appliedCone); + this.PublishSnapshot(current?.Intersect(new ConeCoverage(cone))); + } + + private void PublishSnapshot(AppliedConeSnapshot snapshot) + { + Volatile.Write(ref this.appliedCone, snapshot); + Interlocked.MemoryBarrier(); + + // A change that read the previous cone may need the new one. See + // OnWorkingDirectoryPathChanged for the order of the two steps. + foreach (KeyValuePair change in this.changedPaths) + { + if (snapshot == null || !snapshot.IsCovered(change.Key)) + { + this.SetPending(); + return; + } + } + } + + private void SetPending() + { + if (Volatile.Read(ref this.isPending)) + { + return; + } + + lock (this.pendingLock) + { + if (this.isPending) + { + return; + } + + if (this.environment.TrySetConeChangePending(true, out Exception error)) + { + this.isPending = true; + return; + } + + // Without the file, the hook does not ask for the change. The next change, or + // the next Git command that names the path, tries again. + EventMetadata metadata = this.CreateMetadata(commandId: null); + metadata.Add("Exception", error?.ToString()); + this.tracer.RelatedWarning(metadata, "Could not create the cone change pending file", Keywords.Telemetry); + } + } + + /// Delete the pending file. Return true when a change was pending. + private bool ClearPending() + { + lock (this.pendingLock) + { + if (!this.isPending) + { + return false; + } + + if (!this.environment.TrySetConeChangePending(false, out Exception error)) + { + // The file stays, and so does the pending state: the next request deletes + // the file again. Until then, each Git command sends a request. + EventMetadata metadata = this.CreateMetadata(commandId: null); + metadata.Add("Exception", error?.ToString()); + this.tracer.RelatedWarning(metadata, "Could not delete the cone change pending file", Keywords.Telemetry); + return true; + } + + Volatile.Write(ref this.isPending, false); + return true; + } + } + + private void RearmPendingAfterAttempt(ApplyAttempt attempt, ConeChange change, bool requestHasPaths, EventMetadata metadata) + { + if (!attempt.ClearedPending) + { + return; + } + + bool rearm; + switch (change) + { + case ConeChange.Applied: + case ConeChange.ConeUnchanged: + return; + + case ConeChange.ExpandsModifiedPath: + case ConeChange.InvalidPath: + // The pending changes alone cannot make the same cone valid, so a retry + // fails again until the working tree changes. The request paths can be the + // cause, and an apply without them can succeed. + rearm = requestHasPaths; + break; + + default: + // Without the apply, Git does not see the change, and Git has no fallback + // for that. Every later Git command tries again. + rearm = true; + break; + } + + metadata.Add("PendingKept", rearm); + if (rearm) + { + this.SetPending(); + } + } + + /// Run in the background, at most one at a time. + private void ScheduleReconcile() + { + if (this.isStopped) + { + return; + } + + lock (this.reconcileScheduleLock) + { + if (this.reconcileRunning) + { + this.reconcileRequested = true; + return; + } + + this.reconcileRunning = true; + } + + // The check runs Git and can take seconds, so it gets its own thread. + Task.Factory.StartNew( + () => + { + while (true) + { + this.TryReconcile(); + lock (this.reconcileScheduleLock) + { + if (!this.reconcileRequested || this.isStopped) + { + this.reconcileRunning = false; + return; + } + + this.reconcileRequested = false; + } + } + }, + CancellationToken.None, + TaskCreationOptions.LongRunning, + TaskScheduler.Default); + } + + private ConeChange Reconcile(EventMetadata metadata) + { + if (this.isStopped) + { + return ConeChange.Stopped; + } + + long startSequence; + long epoch; + AppliedConeSnapshot cone; + List candidates; + (long, long, long) state; + lock (this.coneLock) + { + // A pending change can be in a directory that the index does not expand, so Git + // does not report it. Check after the next apply. + cone = Volatile.Read(ref this.appliedCone); + if (Volatile.Read(ref this.isPending) || cone == null) + { + return ConeChange.ConeChangePending; + } + + startSequence = Interlocked.Read(ref this.changeSequence); + epoch = this.consumeEpoch; + state = (startSequence, epoch, this.environment.GetRepositoryStamp()); + if (this.lastReconcileState == state) + { + // A failed write leaves the cone file stale. The clean paths are known, so + // write the file again without Git. + return this.coneFileMayBeStale ? this.WriteNarrowerCone(metadata) : ConeChange.NothingChanged; + } + + // Only a file that the index has an entry for can be clean: one in an applied + // directory, or one that an earlier check found clean while its directory was + // applied. Folders stay in the cone. + candidates = new List(); + HashSet seen = new HashSet(this.pathComparer); + foreach (string path in this.environment.GetModifiedPaths().Concat(this.unconfirmedPaths)) + { + if (!IsFolderPath(path) && + !this.hiddenModifiedPaths.Contains(path) && + (this.cleanPaths.Contains(path) || cone.IsCovered(path)) && + seen.Add(path)) + { + candidates.Add(path); + } + } + + if (candidates.Count == 0) + { + this.lastReconcileState = state; + return ConeChange.NothingChanged; + } + } + + metadata.Add("CandidateCount", candidates.Count); + Stopwatch diffStopwatch = Stopwatch.StartNew(); + if (!this.environment.TryGetPathsThatDifferFromHead(out ICollection differingPaths, out string diffError)) + { + metadata.Add("DiffError", diffError); + return ConeChange.DiffFailed; + } + + metadata.Add("DiffMs", diffStopwatch.ElapsedMilliseconds); + if (this.isStopped) + { + return ConeChange.Stopped; + } + + HashSet differing = new HashSet(differingPaths, this.pathComparer); + List untrackedFolders = differingPaths.Where(IsFolderPath).ToList(); + + // A file is clean when Git lists neither the file nor an untracked folder that + // contains it. Git lists an untracked file, and a deleted tracked file. It does not + // list an ignored file, or a created file that was deleted again. + Dictionary isClean = new Dictionary(candidates.Count, this.pathComparer); + foreach (string path in candidates) + { + isClean[path] = !differing.Contains(path) && + !untrackedFolders.Any(folder => path.StartsWith(folder, this.ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)); + } + + lock (this.coneLock) + { + if (this.consumeEpoch != epoch || this.isStopped) + { + // An apply changed the clean paths or the index while Git ran. + return ConeChange.StateChanged; + } + + int newlyClean = 0; + int newlyDirty = 0; + foreach (KeyValuePair result in isClean) + { + bool changedDuringCheck = this.changedPaths.TryGetValue(result.Key, out PathChange change) && + (change.Sequence > startSequence || !change.WasCovered); + if (result.Value && !changedDuringCheck) + { + // A clean unconfirmed path is not a modified path (for example, a file + // that Git wrote), so it leaves the cone without becoming a clean path. + if (this.unconfirmedPaths.Remove(result.Key) || this.cleanPaths.Add(result.Key)) + { + newlyClean++; + } + } + else if (this.cleanPaths.Remove(result.Key)) + { + newlyDirty++; + } + } + + // Git saw each change that came before the check in a directory that the index + // expands, so the result above already includes it. + foreach (KeyValuePair change in this.changedPaths) + { + if (change.Value.Sequence <= startSequence && change.Value.WasCovered) + { + ((ICollection>)this.changedPaths).Remove(change); + } + } + + this.lastReconcileState = state; + metadata.Add("NewlyCleanCount", newlyClean); + metadata.Add("NewlyDirtyCount", newlyDirty); + metadata.Add("CleanPathCount", this.cleanPaths.Count); + + if (newlyDirty > 0) + { + // The cone must include the file again. Its directory still has index + // entries, but only an apply writes a wider cone file. + this.SetPending(); + return ConeChange.CleanPathChanged; + } + + if (newlyClean == 0) + { + return ConeChange.ConeUnchanged; + } + + return this.WriteNarrowerCone(metadata); + } + } + private bool TryBuildCone(List paths, EventMetadata metadata, out ConePatternSet cone) { try @@ -685,7 +1415,8 @@ private void TraceResult(string eventName, ConeChange change, long durationMs, i metadata.Add("WaitBudgetMs", waitBudgetMs); } - if (IsFailure(change) || exceededWaitBudget || metadata.ContainsKey("DeleteBackupError")) + // A hidden modified path stays invisible to Git, so it is a warning too. + if (IsFailure(change) || exceededWaitBudget || metadata.ContainsKey("DeleteBackupError") || metadata.ContainsKey("HiddenModifiedPathCount")) { this.tracer.RelatedEvent(EventLevel.Warning, eventName, metadata, Keywords.Telemetry); } @@ -702,5 +1433,58 @@ private int GetTransientCommandCount() return this.transientState.CommandCount; } } + + /// A working-tree change: its order, and if the applied cone included the path then. + private readonly record struct PathChange(long Sequence, bool WasCovered); + + /// Records whether a request cleared the pending file. + private sealed class ApplyAttempt + { + public bool ClearedPending { get; set; } + } + + /// + /// The directories that the cone file includes and the index expands: those that every + /// cone in the list includes. + /// + private sealed class AppliedConeSnapshot + { + // More cones make every callback slower. Then the manager treats the state as + // unknown, and the next Git command applies the cone again. + private const int MaxCones = 4; + + private readonly ConeCoverage[] cones; + + public AppliedConeSnapshot(params ConeCoverage[] cones) + { + this.cones = cones; + } + + public bool IsCovered(string path) + { + foreach (ConeCoverage cone in this.cones) + { + if (!cone.IsCovered(path)) + { + return false; + } + } + + return true; + } + + public AppliedConeSnapshot Intersect(ConeCoverage cone) + { + if (this.cones.Length >= MaxCones) + { + return null; + } + + ConeCoverage[] combined = new ConeCoverage[this.cones.Length + 1]; + this.cones.CopyTo(combined, 0); + combined[this.cones.Length] = cone; + return new AppliedConeSnapshot(combined); + } + } } } diff --git a/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs b/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs index 3676af85f..867ed212e 100644 --- a/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs +++ b/GVFS/GVFS.Common/Sparse/IConeManagerEnvironment.cs @@ -46,5 +46,33 @@ public interface IConeManagerEnvironment /// Read the start time of a process, to tell it apart from a later process with the same id. ProcessStartTimeResult TryGetProcessStartTime(int processId, out long startTime); + + /// + /// True when Git changes only the index when the cone changes, and never writes or deletes + /// a working-tree file. Then a widen can expand the directory of a deleted file, and the + /// manager does not need . + /// + bool SparsityChangeIsIndexOnly { get; } + + /// + /// Create ( true) or delete the file that tells the pre-command + /// hook that a cone change is pending (see ). + /// This runs in file system callbacks, so it must be fast and must not throw. + /// + bool TrySetConeChangePending(bool pending, out Exception error); + + /// + /// Get the paths that differ between HEAD and the index or the working tree, as Git + /// reports them: changed and unmerged tracked paths, and untracked files and folders (a + /// folder ends with '/'). Git compares the content of a file whose stat data changed, and + /// it does not write the index. + /// + bool TryGetPathsThatDifferFromHead(out ICollection paths, out string error); + + /// + /// Return a value that changes when Git writes the index or moves HEAD, so that the + /// manager can skip a check when nothing changed. + /// + long GetRepositoryStamp(); } } diff --git a/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs b/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs new file mode 100644 index 000000000..6d3dcb9ab --- /dev/null +++ b/GVFS/GVFS.Common/Sparse/IWorkingDirectoryChangeObserver.cs @@ -0,0 +1,16 @@ +namespace GVFS.Common.Sparse +{ + /// + /// Receives the working-tree changes that the file system callbacks of the mount see. + /// + 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. + /// + /// The path relative to the working-tree root, with either separator. + /// True for a folder. + void OnWorkingDirectoryPathChanged(string relativePath, bool isFolder); + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs index b8a8a1152..6ed078384 100644 --- a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexConeTests.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; using System.Threading.Tasks; namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture @@ -16,69 +15,35 @@ namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture /// gvfs.auto-sparse-index is true and the index is sparse. /// [TestFixture] - public class AutoSparseIndexConeTests : TestsWithEnlistmentPerFixture + public class AutoSparseIndexConeTests : AutoSparseIndexTestsBase { - private const string BypassGVFS = "-c core.virtualfilesystem= -c core.hookspath="; - private const string RootOnlyCone = "/*\n!/*/\n"; private const string ConeManagementPrefix = "gvfs cone-management: "; private const string HookFailurePrefix = ConeManagementPrefix + "widen not applied"; - private static readonly UTF8Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); - // Files three or more levels deep, one for each different "first/second" directory private List deepFiles; // Two files in one directory that no other test uses private string deletedFile; private string siblingOfDeletedFile; - private int traceCount; [OneTimeSetUp] - public void EnableSparseIndex() + public void SelectFiles() { - string buildOptions = GitProcess.Invoke(this.Enlistment.RepoRoot, "version --build-options"); - if (!buildOptions.Contains("feature: vfs-sparse-index")) - { - Assert.Ignore("This git does not support a sparse index with VFS (git version --build-options has no 'feature: vfs-sparse-index')"); - } - - List headFiles = this.GitShouldSucceed("-c core.quotepath=false ls-tree -r --name-only HEAD") - .Split('\n', StringSplitOptions.RemoveEmptyEntries) - .Select(path => path.Trim()) - .Where(path => path.Count(character => character == '/') >= 2 && !path.Contains(' ')) - .ToList(); - List> directories = headFiles - .GroupBy(path => TwoLevelDirectory(path), StringComparer.OrdinalIgnoreCase) - .ToList(); + List> directories = this.GroupByTwoLevelDirectory(); directories.Count.ShouldBeAtLeast(9, "HEAD has too few directories that are two levels deep"); this.deepFiles = directories.Take(8).Select(group => group.First()).ToList(); List pair = directories .Skip(8) - .SelectMany(group => group.GroupBy(path => path.Substring(0, path.LastIndexOf('/')), StringComparer.OrdinalIgnoreCase)) + .SelectMany(group => group.GroupBy(path => ParentDirectory(path), StringComparer.OrdinalIgnoreCase)) .First(group => group.Count() >= 2) .Take(2) .ToList(); this.deletedFile = pair[0]; this.siblingOfDeletedFile = pair[1]; - - // Mount with the feature on, a root-only cone, and a collapsed index. The persisted - // projection gets the same index, as it does when git collapses the index while the - // repository is mounted. - this.Enlistment.UnmountGVFS(); - this.GitShouldSucceed("-c core.hookspath= config gvfs.auto-sparse-index true"); - this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckout true"); - this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckoutCone true"); - this.GitShouldSucceed("-c core.hookspath= config index.sparse true"); - File.WriteAllText(this.SparseCheckoutPath, RootOnlyCone, Utf8NoBom); - this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true update-index --force-write-index"); - this.SparseDirectoryEntries().ShouldBeNonEmpty(); - File.Copy(this.Enlistment.GetDotGitPath("index"), Path.Combine(this.Enlistment.DotGVFSRoot, "GVFS_projection"), overwrite: true); - this.Enlistment.MountGVFS(); } - private string SparseCheckoutPath => this.Enlistment.GetDotGitPath("info", "sparse-checkout"); - [TestCase] public void GitAddWidensTheConeWithoutExpandingTheIndexAndTheConeNarrowsAfterwards() { @@ -103,7 +68,7 @@ public void GitAddWidensTheConeWithoutExpandingTheIndexAndTheConeNarrowsAfterwar string[] coneLines = this.WaitForConeFile(lines => !lines.Any(line => IsConeLineFor(line, unmodifiedDirectory))); coneLines.ShouldContain(line => IsConeLineFor(line, TwoLevelDirectory(modifiedFile))); coneLines.ShouldNotContain(line => IsConeLineFor(line, unmodifiedDirectory)); - string cone = File.ReadAllText(this.SparseCheckoutPath); + string cone = this.ReadConeFile(); this.SparseDirectoryEntries().ShouldBeNonEmpty(); this.SparseIndexEntries().ShouldContain(entry => entry.Equals(unmodifiedFile, StringComparison.OrdinalIgnoreCase)); @@ -159,14 +124,14 @@ public void ConcurrentGitCommandsThatNameOutOfConePathsSucceed() public void UnlockedCommandDoesNotChangeTheCone() { string file = this.deepFiles[6]; - string coneBefore = File.ReadAllText(this.SparseCheckoutPath); + string coneBefore = this.ReadConeFile(); // git diff does not take the GVFS lock, so the mount must not replace the index for it. ProcessResult diff = this.GitWithTrace($"diff --stat -- {file}", out _); diff.ExitCode.ShouldEqual(0, diff.Errors); diff.Errors.ShouldContain(HookFailurePrefix + ": Rejected"); - File.ReadAllText(this.SparseCheckoutPath).ShouldEqual(coneBefore); + this.ReadConeFile().ShouldEqual(coneBefore); } [TestCase] @@ -201,14 +166,15 @@ public void WidenOfAFullIndexCollapsesTheIndex() [TestCase] public void WidenDoesNotRestoreADeletedFile() { - // Expanding the directory of a deleted file makes Git check the file out again, so - // the mount must not widen the cone to that directory. File.Delete(this.Enlistment.GetVirtualPathTo(this.deletedFile)); ProcessResult add = this.GitWithTrace($"add -- {this.siblingOfDeletedFile}", out _); add.ExitCode.ShouldEqual(0, add.Errors); - add.Errors.ShouldContain(HookFailurePrefix + ": Rejected"); + + // Git expands the directory of the deleted file without a checkout. + add.Errors.ShouldNotContain(ignoreCase: false, HookFailurePrefix); + this.GitShouldSucceed("status --porcelain").ShouldContain(" D " + this.deletedFile); File.Exists(this.Enlistment.GetVirtualPathTo(this.deletedFile)).ShouldBeFalse("The widen restored the deleted file"); } @@ -224,81 +190,9 @@ private static void ConeRequestsShouldSucceed(ProcessResult result) .ShouldBeEmpty("A cone request failed: " + result.Errors); } - private static string[] ConeLines(string cone) - { - return cone.Split('\n'); - } - - private string[] WaitForConeFile(Func isExpected) - { - string[] lines = ConeLines(File.ReadAllText(this.SparseCheckoutPath)); - for (int attempt = 0; attempt < 50 && !isExpected(lines); attempt++) - { - System.Threading.Thread.Sleep(100); - lines = ConeLines(File.ReadAllText(this.SparseCheckoutPath)); - } - - return lines; - } - - private static bool IsConeLineFor(string line, string directory) - { - return line.Equals("/" + directory + "/", StringComparison.OrdinalIgnoreCase); - } - - private static string TwoLevelDirectory(string path) - { - string[] segments = path.Split('/'); - return segments[0] + "/" + segments[1]; - } - - private static int CountFullIndexExpansions(string trace2EventFile) - { - File.Exists(trace2EventFile).ShouldBeTrue("git did not write the trace2 file " + trace2EventFile); - return File.ReadLines(trace2EventFile) - .Count(line => line.Contains("\"event\":\"region_enter\"") && line.Contains("\"label\":\"ensure_full_index\"")); - } - - private ProcessResult GitWithTrace(string command, out string trace2EventFile) - { - string traceFile = Path.Combine(this.Enlistment.EnlistmentRoot, $"cone-trace2-{System.Threading.Interlocked.Increment(ref this.traceCount)}.json"); - trace2EventFile = traceFile; - return GitProcess.InvokeProcess( - this.Enlistment.RepoRoot, - command, - new Dictionary - { - { "GIT_TRACE", "1" }, - { "GIT_TRACE2_EVENT", traceFile }, - }); - } - - private string GitShouldSucceed(string command) - { - ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command); - result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); - return result.Output; - } - private int IndexHeaderEntryCount() { return GVFSHelpers.IndexHeaderEntryCount(this.Enlistment); } - - private List SparseDirectoryEntries() - { - return this.SparseIndexEntries().Where(line => line.EndsWith("/")).ToList(); - } - - private List SparseIndexEntries() - { - // Without the virtual file system, git sees the projected folders outside the cone. By - // default it then clears their skip-worktree bits and expands the index in memory. - return this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true -c core.quotepath=false ls-files --sparse") - .Split('\n') - .Select(line => line.Trim()) - .Where(line => line.Length > 0) - .ToList(); - } } } diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs new file mode 100644 index 000000000..5eb4a16be --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexTestsBase.cs @@ -0,0 +1,179 @@ +using GVFS.FunctionalTests.Tools; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; + +namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture +{ + /// + /// Mounts the fixture's enlistment with gvfs.auto-sparse-index on, a root-only cone, + /// and a collapsed sparse index, and has helpers for the tests of the sparse-index cone. + /// + public abstract class AutoSparseIndexTestsBase : TestsWithEnlistmentPerFixture + { + protected const string BypassGVFS = "-c core.virtualfilesystem= -c core.hookspath="; + protected const string RootOnlyCone = "/*\n!/*/\n"; + + private static readonly UTF8Encoding Utf8NoBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + + private int traceCount; + + /// The files of HEAD that are three or more levels deep and have no space in the path. + protected List DeepHeadFiles { get; private set; } + + protected string SparseCheckoutPath => this.Enlistment.GetDotGitPath("info", "sparse-checkout"); + + [OneTimeSetUp] + public void MountWithASparseIndex() + { + // A Git with this feature also changes only the index when the cone changes. + string buildOptions = GitProcess.Invoke(this.Enlistment.RepoRoot, "version --build-options"); + if (!buildOptions.Contains("feature: vfs-sparse-index")) + { + Assert.Ignore("This git does not support a sparse index with VFS (git version --build-options has no 'feature: vfs-sparse-index')"); + } + + this.DeepHeadFiles = this.GitShouldSucceed("-c core.quotepath=false ls-tree -r --name-only HEAD") + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Select(path => path.Trim()) + .Where(path => path.Count(character => character == '/') >= 2 && !path.Contains(' ')) + .ToList(); + + // Mount with the feature on, a root-only cone, and a collapsed index. The persisted + // projection gets the same index, as it does when git collapses the index while the + // repository is mounted. + this.Enlistment.UnmountGVFS(); + this.GitShouldSucceed("-c core.hookspath= config gvfs.auto-sparse-index true"); + this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckout true"); + this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckoutCone true"); + this.GitShouldSucceed("-c core.hookspath= config index.sparse true"); + File.WriteAllText(this.SparseCheckoutPath, RootOnlyCone, Utf8NoBom); + this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true update-index --force-write-index"); + this.SparseDirectoryEntries().ShouldBeNonEmpty(); + File.Copy(this.Enlistment.GetDotGitPath("index"), Path.Combine(this.Enlistment.DotGVFSRoot, "GVFS_projection"), overwrite: true); + this.Enlistment.MountGVFS(); + } + + protected static string[] ConeLines(string cone) + { + return cone.Split('\n'); + } + + protected static bool IsConeLineFor(string line, string directory) + { + return line.Equals("/" + directory + "/", StringComparison.OrdinalIgnoreCase); + } + + protected static string TwoLevelDirectory(string path) + { + string[] segments = path.Split('/'); + return segments[0] + "/" + segments[1]; + } + + protected static string ParentDirectory(string path) + { + return path.Substring(0, path.LastIndexOf('/')); + } + + protected static int CountFullIndexExpansions(string trace2EventFile) + { + File.Exists(trace2EventFile).ShouldBeTrue("git did not write the trace2 file " + trace2EventFile); + return File.ReadLines(trace2EventFile) + .Count(line => line.Contains("\"event\":\"region_enter\"") && line.Contains("\"label\":\"ensure_full_index\"")); + } + + /// + /// Return the files of HEAD that are three or more levels deep, grouped by their + /// two-level directory. Files of different groups are in different directories outside a + /// root-only cone. + /// + protected List> GroupByTwoLevelDirectory() + { + return this.DeepHeadFiles + .GroupBy(path => TwoLevelDirectory(path), StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + protected string[] WaitForConeFile(Func isExpected) + { + string[] lines = ConeLines(this.ReadConeFile()); + for (int attempt = 0; attempt < 100 && !isExpected(lines); attempt++) + { + System.Threading.Thread.Sleep(100); + lines = ConeLines(this.ReadConeFile()); + } + + return lines; + } + + /// + /// Read the cone file. The read lets the mount replace the file, as a read by Git does. + /// + protected string ReadConeFile() + { + for (int attempt = 0; ; attempt++) + { + try + { + using (FileStream stream = new FileStream(this.SparseCheckoutPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + using (StreamReader reader = new StreamReader(stream)) + { + return reader.ReadToEnd(); + } + } + catch (IOException) when (attempt < 10) + { + // The mount replaced the file between the lookup and the open. + System.Threading.Thread.Sleep(50); + } + } + } + + protected ProcessResult GitWithTrace(string command, out string trace2EventFile, bool takeOptionalLocks = false) + { + string traceFile = Path.Combine(this.Enlistment.EnlistmentRoot, $"cone-trace2-{System.Threading.Interlocked.Increment(ref this.traceCount)}.json"); + trace2EventFile = traceFile; + Dictionary environment = new Dictionary + { + { "GIT_TRACE", "1" }, + { "GIT_TRACE2_EVENT", traceFile }, + }; + + // The test runner turns optional locks off, so "git status" does not take the GVFS + // lock unless the test turns them on again. + if (takeOptionalLocks) + { + environment.Add("GIT_OPTIONAL_LOCKS", "1"); + } + + return GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command, environment); + } + + protected string GitShouldSucceed(string command) + { + ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command); + result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); + return result.Output; + } + + protected List SparseDirectoryEntries() + { + return this.SparseIndexEntries().Where(line => line.EndsWith("/")).ToList(); + } + + protected List SparseIndexEntries() + { + // Without the virtual file system, git sees the projected folders outside the cone. By + // default it then clears their skip-worktree bits and expands the index in memory. + return this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true -c core.quotepath=false ls-files --sparse") + .Split('\n') + .Select(line => line.Trim()) + .Where(line => line.Length > 0) + .ToList(); + } + } +} diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexWorkingTreeTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexWorkingTreeTests.cs new file mode 100644 index 000000000..934d61a16 --- /dev/null +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/AutoSparseIndexWorkingTreeTests.cs @@ -0,0 +1,374 @@ +using GVFS.FunctionalTests.Tools; +using GVFS.Tests.Should; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; + +namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture +{ + /// + /// Functional tests for working-tree changes outside the sparse-index cone that no Git + /// command names: Git must see them before it reads the index. + /// + [TestFixture] + public class AutoSparseIndexWorkingTreeTests : AutoSparseIndexTestsBase + { + private const string ConeManagementPrefix = "gvfs cone-management:"; + + private static readonly Func SamePath = (first, second) => first.Equals(second, StringComparison.OrdinalIgnoreCase); + + // Files of HEAD, each in a different two-level directory outside the root-only cone + private Queue unusedFiles; + + [OneTimeSetUp] + public void SelectFiles() + { + this.unusedFiles = new Queue(this.GroupByTwoLevelDirectory().Select(group => group.First())); + this.unusedFiles.Count.ShouldBeAtLeast(18, "HEAD has too few directories that are two levels deep"); + } + + [TestCase] + public void StatusAndAddSeeFilesThatWereEditedOutsideTheCone() + { + List files = this.TakeFiles(3); + foreach (string file in files) + { + this.AppendTo(file); + } + + // This status takes the GVFS lock. The other tests run "git status" without it, as + // an editor does. + ProcessResult status = this.GitWithTrace("status --porcelain", out string statusTrace, takeOptionalLocks: true); + status.ExitCode.ShouldEqual(0, status.Errors); + ModifiedFilesIn(status.Output).ShouldContain(files, SamePath); + this.ShouldNotExpandTheIndex(status, statusTrace); + + ProcessResult add = this.GitWithTrace("add .", out string addTrace); + add.ExitCode.ShouldEqual(0, add.Errors); + this.ShouldNotExpandTheIndex(add, addTrace); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(files.ToArray()); + + this.SparseDirectoryEntries().ShouldBeNonEmpty(); + this.CommitAndCheckThatTheConeNarrows(files, "commit -m \"Edited outside the cone\""); + } + + [TestCase] + public void CommitAllIncludesFilesThatWereEditedOutsideTheCone() + { + List files = this.TakeFiles(3); + foreach (string file in files) + { + this.AppendTo(file); + } + + this.CommitAndCheckThatTheConeNarrows(files, "commit -a -m \"Edited outside the cone\""); + } + + [TestCase] + public void ConeNarrowsAfterResetHardDiscardsAnEdit() + { + string file = this.TakeFiles(1).Single(); + string directory = ParentDirectory(file); + this.AppendTo(file); + ModifiedFilesIn(this.Status()).ShouldContain(new[] { file }, SamePath); + this.ConeShouldInclude(directory); + + // The reset rebuilds the projection. The file has the content of HEAD again. + this.GitShouldSucceed("reset --hard --quiet"); + + this.WaitForConeFile(lines => !lines.Any(line => IsConeLineFor(line, directory))) + .ShouldNotContain(line => IsConeLineFor(line, directory)); + } + + [TestCase] + public void ConeNarrowsWhenACreatedFileIsIgnored() + { + string directory = ParentDirectory(this.TakeFiles(1).Single()); + string ignoredFile = directory + "/created.vfs-cone-ignored"; + File.AppendAllText(this.Enlistment.GetDotGitPath("info", "exclude"), "\n*.vfs-cone-ignored\n"); + File.WriteAllText(this.Enlistment.GetVirtualPathTo(ignoredFile), "ignored"); + + // The status applies the change. Git does not list an ignored file, so the + // check finds it clean, and the cone leaves its directory out. + this.Status().ShouldNotContain(ignoreCase: true, ignoredFile); + this.WaitForConeFile(lines => !lines.Any(line => IsConeLineFor(line, directory))) + .ShouldNotContain(line => IsConeLineFor(line, directory)); + } + + [TestCase] + public void ConeNarrowsWhenAFileHasTheContentOfHeadAgainAndWidensAtTheNextEdit() + { + string file = this.TakeFiles(1).Single(); + string directory = ParentDirectory(file); + string path = this.Enlistment.GetVirtualPathTo(file); + byte[] headContent = File.ReadAllBytes(path); + + this.AppendTo(file); + ModifiedFilesIn(this.Status()).ShouldContain(new[] { file }, SamePath); + this.ConeShouldInclude(directory); + + // The change is inside the applied cone, so no request is pending. When changes stop + // for a short time, the mount checks which modified files match HEAD. + File.WriteAllBytes(path, headContent); + ModifiedFilesIn(this.Status()).ShouldNotContain(new[] { file }, SamePath); + this.WaitForConeFile(lines => !lines.Any(line => IsConeLineFor(line, directory))) + .ShouldNotContain(line => IsConeLineFor(line, directory)); + + this.AppendTo(file); + ProcessResult status = this.GitWithTrace("status --porcelain", out string trace); + ModifiedFilesIn(status.Output).ShouldContain(new[] { file }, SamePath); + this.ShouldNotExpandTheIndex(status, trace); + this.ConeShouldInclude(directory); + } + + [TestCase] + public void UnlockedDiffSeesAFileThatWasEditedOutsideTheCone() + { + string file = this.TakeFiles(1).Single(); + this.AppendTo(file); + + // git diff does not take the GVFS lock. The hook takes it to apply the pending change. + ProcessResult diff = this.GitWithTrace("diff --name-only", out string trace); + + diff.ExitCode.ShouldEqual(0, diff.Errors); + diff.Output.Split('\n').Select(line => line.Trim()).ShouldContain(line => line.Equals(file, StringComparison.OrdinalIgnoreCase)); + this.ShouldNotExpandTheIndex(diff, trace); + this.ConeShouldInclude(ParentDirectory(file)); + } + + [TestCase] + public void AddSeesANewFileOutsideTheCone() + { + string directory = ParentDirectory(this.TakeFiles(1).Single()); + string newFile = directory + "/new-file-outside-the-cone.txt"; + File.WriteAllText(this.Enlistment.GetVirtualPathTo(newFile), "new"); + + ProcessResult add = this.GitWithTrace("add .", out string trace); + + add.ExitCode.ShouldEqual(0, add.Errors); + this.ShouldNotExpandTheIndex(add, trace); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(newFile); + this.GitShouldSucceed("reset --quiet -- " + newFile); + File.Delete(this.Enlistment.GetVirtualPathTo(newFile)); + } + + [TestCase] + public void AddSeesARenameOverSaveAfterAFolderDehydrate() + { + // An earlier change, then a folder dehydrate, which rewrites the index and the cone. + string earlierFile = this.TakeFiles(1).Single(); + this.AppendTo(earlierFile); + this.GitShouldSucceed("add -- " + earlierFile); + this.GitShouldSucceed("restore --staged --worktree -- " + earlierFile); + this.DehydrateFolder(ParentDirectory(earlierFile)); + + // An editor writes a temporary file and renames it over the file. + string file = this.TakeFiles(1).Single(); + string path = this.Enlistment.GetVirtualPathTo(file); + string temporaryPath = path + ".tmp~"; + File.WriteAllText(temporaryPath, File.ReadAllText(path) + "edited outside the cone\n"); + File.Move(temporaryPath, path, overwrite: true); + + ProcessResult add = this.GitWithTrace("add -- " + file, out string trace); + + add.ExitCode.ShouldEqual(0, add.Errors); + this.ShouldNotExpandTheIndex(add, trace); + this.GitShouldSucceed("diff --cached --name-only").ShouldContain(file); + this.GitShouldSucceed("restore --staged --worktree -- " + file); + } + + [TestCase] + public void StatusAndCommitAllSeeAFileThatWasDeletedOutsideTheCone() + { + string file = this.TakeFiles(1).Single(); + File.Delete(this.Enlistment.GetVirtualPathTo(file)); + + ProcessResult status = this.GitWithTrace("status --porcelain", out string trace); + status.ExitCode.ShouldEqual(0, status.Errors); + status.Output.ShouldContain(" D " + file); + this.ShouldNotExpandTheIndex(status, trace); + + this.GitShouldSucceed("commit -a -m \"Deleted outside the cone\""); + this.GitShouldSucceed("show --name-status --format= HEAD").ShouldContain("D\t" + file); + File.Exists(this.Enlistment.GetVirtualPathTo(file)).ShouldBeFalse("Git restored the deleted file"); + } + + [TestCase("checkout --detach")] + [TestCase("reset --merge")] + public void SwitchingCommitsKeepsOrRefusesToOverwriteChangesOutsideTheCone(string switchCommand) + { + List files = this.TakeFiles(2); + string editedFile = files[0]; + string deletedFile = files[1]; + string editedPath = this.Enlistment.GetVirtualPathTo(editedFile); + string deletedPath = this.Enlistment.GetVirtualPathTo(deletedFile); + string addedFile = ParentDirectory(editedFile) + "/added-next-to-an-edit.txt"; + string startCommit = this.GitShouldSucceed("rev-parse HEAD").Trim(); + string branch = this.GitShouldSucceed("symbolic-ref --short HEAD").Trim(); + + // The sibling commit changes the directories of both files, but not the files. The + // other commit changes the edited file. + string siblingCommit = this.CommitWithoutTheWorkingTree( + startCommit, + (addedFile, "added"), + (ParentDirectory(deletedFile) + "/added-next-to-a-delete.txt", "added")); + string overwriteCommit = this.CommitWithoutTheWorkingTree(startCommit, (editedFile, "changed by a commit")); + + this.GitShouldSucceed("checkout --detach"); + try + { + this.AppendTo(editedFile); + string editedContent = File.ReadAllText(editedPath); + File.Delete(deletedPath); + string status = this.Status(); + status.ShouldContain(" M " + editedFile, " D " + deletedFile); + + // Git keeps both changes, as it does with a full index. + ProcessResult keep = this.GitWithTrace($"{switchCommand} {siblingCommit}", out _); + keep.ExitCode.ShouldEqual(0, keep.Errors); + keep.Errors.ShouldNotContain(ignoreCase: false, ConeManagementPrefix); + this.GitShouldSucceed("rev-parse HEAD").Trim().ShouldEqual(siblingCommit); + File.Exists(this.Enlistment.GetVirtualPathTo(addedFile)).ShouldBeTrue("Git did not check out the new file of the commit"); + File.ReadAllText(editedPath).ShouldEqual(editedContent, "Git lost the edit"); + File.Exists(deletedPath).ShouldBeFalse("Git restored the deleted file"); + this.Status().ShouldContain(" M " + editedFile, " D " + deletedFile); + + // Git refuses to overwrite the edit. + ProcessResult refuse = this.GitWithTrace($"{switchCommand} {overwriteCommit}", out _); + refuse.ExitCode.ShouldNotEqual(0, "Git overwrote a file that was edited outside the cone"); + refuse.Errors.ShouldContain(editedFile); + this.GitShouldSucceed("rev-parse HEAD").Trim().ShouldEqual(siblingCommit); + File.ReadAllText(editedPath).ShouldEqual(editedContent, "Git lost the edit"); + File.Exists(deletedPath).ShouldBeFalse("Git restored the deleted file"); + } + finally + { + GitProcess.InvokeProcess(this.Enlistment.RepoRoot, $"{switchCommand} {startCommit}"); + GitProcess.InvokeProcess(this.Enlistment.RepoRoot, $"checkout {startCommit} -- {editedFile} {deletedFile}"); + GitProcess.InvokeProcess(this.Enlistment.RepoRoot, $"checkout {branch}"); + } + + this.GitShouldSucceed("status --porcelain").ShouldNotContain(ignoreCase: true, editedFile, deletedFile); + } + + private static List ModifiedFilesIn(string porcelainStatus) + { + return porcelainStatus + .Split('\n') + .Where(line => line.Length > 3) + .Select(line => line.Substring(3).Trim()) + .ToList(); + } + + private string Status() + { + ProcessResult status = this.GitWithTrace("status --porcelain", out string trace); + status.ExitCode.ShouldEqual(0, status.Errors); + this.ShouldNotExpandTheIndex(status, trace); + return status.Output; + } + + private List TakeFiles(int count) + { + List files = new List(); + for (int i = 0; i < count; i++) + { + files.Add(this.unusedFiles.Dequeue()); + } + + return files; + } + + private void AppendTo(string file) + { + File.AppendAllText(this.Enlistment.GetVirtualPathTo(file), Environment.NewLine + "edited outside the cone" + Environment.NewLine); + } + + private void DehydrateFolder(string directory) + { + ProcessStartInfo processInfo = new ProcessStartInfo(GVFSTestConfig.PathToGVFS); + processInfo.Arguments = $"dehydrate --confirm --no-status --folders {directory} {TestConstants.InternalUseOnlyFlag} {GVFSHelpers.GetInternalParameter()}"; + processInfo.WorkingDirectory = this.Enlistment.EnlistmentRoot; + processInfo.UseShellExecute = false; + processInfo.RedirectStandardOutput = true; + ProcessResult dehydrate = ProcessHelper.Run(processInfo); + dehydrate.ExitCode.ShouldEqual(0, dehydrate.Output + dehydrate.Errors); + } + + /// + /// Commit on top of with a separate + /// index and without the virtual file system, so that the working tree, the index, and the + /// cone do not change. + /// + private string CommitWithoutTheWorkingTree(string parent, params (string Path, string Content)[] files) + { + string indexFile = Path.Combine(this.Enlistment.EnlistmentRoot, "commit-" + Guid.NewGuid().ToString("N") + ".index"); + string plainGit = BypassGVFS + " -c core.sparseCheckout=false -c index.sparse=false"; + Dictionary environment = new Dictionary { { "GIT_INDEX_FILE", indexFile } }; + try + { + this.PlainGitShouldSucceed($"{plainGit} read-tree {parent}", environment); + foreach ((string path, string content) in files) + { + string blob; + using (MemoryStream input = new MemoryStream(Encoding.UTF8.GetBytes(content + "\n"))) + { + // hash-object rejects the empty paths of the other options, and it does + // not read the index. + blob = this.PlainGitShouldSucceed("hash-object -w --no-filters --stdin", environment, input).Trim(); + } + + this.PlainGitShouldSucceed($"{plainGit} update-index --add --cacheinfo 100644,{blob},{path}", environment); + } + + string tree = this.PlainGitShouldSucceed($"{plainGit} write-tree", environment).Trim(); + return this.PlainGitShouldSucceed($"{plainGit} commit-tree {tree} -p {parent} -m \"Commit beside the working tree\"", environment).Trim(); + } + finally + { + File.Delete(indexFile); + } + } + + private string PlainGitShouldSucceed(string command, Dictionary environment, Stream input = null) + { + ProcessResult result = GitProcess.InvokeProcess(this.Enlistment.RepoRoot, command, environment, input); + result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); + return result.Output; + } + + private void ShouldNotExpandTheIndex(ProcessResult result, string trace) + { + result.Errors.ShouldNotContain(ignoreCase: false, ConeManagementPrefix + " widen not applied", ConeManagementPrefix + " apply"); + CountFullIndexExpansions(trace).ShouldEqual(0, "git expanded the whole index: " + result.Errors); + } + + private void ConeShouldInclude(string directory) + { + ConeLines(this.ReadConeFile()).ShouldContain(line => IsConeLineFor(line, directory)); + } + + private void CommitAndCheckThatTheConeNarrows(List files, string commitCommand) + { + ProcessResult commit = this.GitWithTrace(commitCommand, out string trace); + commit.ExitCode.ShouldEqual(0, commit.Errors); + this.ShouldNotExpandTheIndex(commit, trace); + List committed = this.GitShouldSucceed("show --name-only --format= HEAD") + .Split('\n') + .Select(line => line.Trim()) + .ToList(); + committed.ShouldContain(files, SamePath); + + // The committed files match HEAD, so the cone no longer needs their directories. + List directories = files.Select(ParentDirectory).ToList(); + string[] coneLines = this.WaitForConeFile(lines => !lines.Any(line => directories.Any(directory => IsConeLineFor(line, directory)))); + coneLines.ShouldNotContain(line => directories.Any(directory => IsConeLineFor(line, directory))); + this.SparseDirectoryEntries().ShouldBeNonEmpty(); + ModifiedFilesIn(this.Status()).ShouldNotContain(files, SamePath); + } + } +} diff --git a/GVFS/GVFS.Hooks/ConeRequestOutcome.cs b/GVFS/GVFS.Hooks/ConeRequestOutcome.cs index fd927f827..e06ada95d 100644 --- a/GVFS/GVFS.Hooks/ConeRequestOutcome.cs +++ b/GVFS/GVFS.Hooks/ConeRequestOutcome.cs @@ -39,12 +39,21 @@ internal enum ConeRequestOutcome TimedOut, /// - /// The hook sent a widen, but the mount did not reply within the reply ceiling. Git can - /// then find the index lock that the mount's Git process holds. + /// The hook sent a widen or an apply, but the mount did not reply within the reply + /// ceiling. Git can then find the index lock that the mount's Git process holds. /// ReplyTimedOut, /// The request failed with an exception. Failed, + + /// No working-tree change waits for a cone change, so the hook did nothing. + NothingPending, + + /// The command does not read the index and does not take the GVFS lock, so the hook did nothing. + NotAnIndexReader, + + /// The hook could not take the GVFS lock for a command that does not take it, so it did not send the request. + LockUnavailable, } } diff --git a/GVFS/GVFS.Hooks/PendingConeChangeHook.cs b/GVFS/GVFS.Hooks/PendingConeChangeHook.cs new file mode 100644 index 000000000..56eb3a1f8 --- /dev/null +++ b/GVFS/GVFS.Hooks/PendingConeChangeHook.cs @@ -0,0 +1,363 @@ +using GVFS.Common.NamedPipes; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; +using System.Threading.Tasks; + +namespace GVFS.Hooks +{ + /// + /// Asks the mount to apply a pending sparse-index cone change before Git reads the index. + /// + /// + /// When a working-tree change needs a directory that the index does not expand, the mount + /// creates a pending file. The file system callback that sees the change does not wait for a + /// Git command. The hook checks that file with one file-system query, so a command pays + /// nothing more when no change is pending. + /// + /// Only the Git process that holds the GVFS lock can apply a cone change. A command that + /// takes the lock holds it when this hook runs. A command that reads the index without the + /// lock (for example git diff) takes the lock for the apply, and releases it before + /// Git runs. If another Git command holds the lock, the hook does not wait, because that + /// command can be the parent of this one. The reader can then miss a change that is not + /// applied yet, as it can miss any change that a concurrent command makes. + /// + /// + /// As for the other cone requests, every failure lets Git run. When the mount replies that + /// the feature is off, or does not know the request, the hook deletes the pending file, + /// because that mount never applies the change. + /// + /// + internal sealed class PendingConeChangeHook + { + // How long the hook waits before it asks for the GVFS lock again. + private const int LockRetryDelayMs = 25; + + // The release must reach the mount, or the lock stays with the Git process until it ends. + private const int ReleaseConnectTimeoutMs = 5000; + + // After a timeout, the hook of a command without the lock still waits this long for the + // mount to finish, so that it does not release the lock while the mount changes the index. + private const int ApplyCompletionWaitMs = 60000; + + // Built-in commands that read the index or the working tree through the index and do not + // take the GVFS lock. "status" is here for "--no-optional-locks", which only checks the + // lock. A "git-" prefix means an alias or a program, which is not in this list: the Git + // commands that it runs have their own hooks. + private static readonly HashSet UnlockedIndexReaders = new HashSet(StringComparer.Ordinal) + { + "annotate", + "blame", + "cat-file", + "check-attr", + "check-ignore", + "diff", + "diff-files", + "diff-index", + "difftool", + "ls-files", + "rev-parse", + "show", + "status", + }; + + private readonly Func isPending; + private readonly Action deletePendingFile; + private readonly Func createPipeClient; + private readonly Action trace; + + /// Returns true when the mount's pending file exists. + /// Deletes the mount's pending file. + /// Creates an unconnected client for the mount pipe. + /// Writes a diagnostic message. + public PendingConeChangeHook(Func isPending, Action deletePendingFile, Func createPipeClient, Action trace) + { + this.isPending = isPending ?? throw new ArgumentNullException(nameof(isPending)); + this.deletePendingFile = deletePendingFile ?? throw new ArgumentNullException(nameof(deletePendingFile)); + this.createPipeClient = createPipeClient ?? throw new ArgumentNullException(nameof(createPipeClient)); + this.trace = trace ?? (message => { }); + } + + /// + /// If a cone change is pending, ask the mount to apply it, and wait for the reply. Never throws. + /// + /// + /// The hook connects and sends the request within . If it + /// cannot, it does not send the request, and Git runs. After it sent the request, it + /// waits for the reply up to : the mount applies the + /// cone with a Git process that holds the index lock, so Git must not run before that + /// process ends. + /// + /// The hook arguments. + /// True when this hook took the GVFS lock for the Git command. + /// Creates the GVFS lock request for a Git process id. + /// The longest wait for the reply after the request was sent. + /// The longest time to connect and send the request. + /// The longest wait for the GVFS lock. + public ConeRequestOutcome TryApply( + string[] args, + bool holdsLock, + Func createLockRequest, + int replyCeilingMs = NamedPipeMessages.ConeManagement.WidenReplyCeilingMs, + int sendBudgetMs = NamedPipeMessages.ConeManagement.WidenWaitBudgetMs, + int lockWaitBudgetMs = NamedPipeMessages.ConeManagement.WidenWaitBudgetMs) + { + ConeRequestOutcome outcome; + try + { + outcome = this.Apply(args, holdsLock, createLockRequest, sendBudgetMs, replyCeilingMs, lockWaitBudgetMs); + } + catch (Exception e) + { + this.trace($"apply failed: {e.Message}"); + return ConeRequestOutcome.Failed; + } + + switch (outcome) + { + case ConeRequestOutcome.NothingPending: + case ConeRequestOutcome.NotAnIndexReader: + case ConeRequestOutcome.Applied: + break; + + default: + this.trace($"apply not applied: {outcome}"); + break; + } + + return outcome; + } + + internal static bool IsUnlockedIndexReader(string[] args) + { + return args != null && args.Length > 1 && args[1] != null && UnlockedIndexReaders.Contains(args[1]); + } + + private ConeRequestOutcome Apply(string[] args, bool holdsLock, Func createLockRequest, int sendBudgetMs, int replyCeilingMs, int lockWaitBudgetMs) + { + if (!this.isPending()) + { + return ConeRequestOutcome.NothingPending; + } + + string commandId = ConeManagementHook.GetCommandId(args); + if (holdsLock) + { + return this.WaitForApply(this.StartApply(commandId), sendBudgetMs, replyCeilingMs); + } + + if (!IsUnlockedIndexReader(args)) + { + return ConeRequestOutcome.NotAnIndexReader; + } + + // Use the same process id as the apply request. The mount accepts the apply only + // from the process that holds the lock. + if (!int.TryParse(commandId, out int processId) || processId <= 0) + { + return ConeRequestOutcome.Failed; + } + + NamedPipeMessages.LockRequest lockRequest = createLockRequest(processId); + if (!this.TryAcquireLock(lockRequest, lockWaitBudgetMs)) + { + return ConeRequestOutcome.LockUnavailable; + } + + ApplyRequest apply = null; + try + { + apply = this.StartApply(commandId); + return this.WaitForApply(apply, sendBudgetMs, replyCeilingMs); + } + finally + { + // The mount can still run Git for a request that the hook sent. Another command + // must not get the lock until it is done, so wait for it, but not forever. + if (apply != null && apply.WasSent && !apply.Reply.IsCompleted && !apply.Reply.Wait(ApplyCompletionWaitMs)) + { + this.trace("apply still running; releasing the GVFS lock"); + } + + this.ReleaseLock(lockRequest); + } + } + + private bool TryAcquireLock(NamedPipeMessages.LockRequest lockRequest, int lockWaitBudgetMs) + { + NamedPipeMessages.Message request = lockRequest.CreateMessage(NamedPipeMessages.AcquireLock.AcquireRequest); + Stopwatch stopwatch = Stopwatch.StartNew(); + using (NamedPipeClient pipeClient = this.createPipeClient()) + { + if (!pipeClient.Connect(NamedPipeMessages.ConeManagement.ConnectTimeoutMs, out _)) + { + return false; + } + + while (true) + { + pipeClient.SendRequest(request); + NamedPipeMessages.Message reply = pipeClient.ReadResponse(); + if (reply == null) + { + return false; + } + + NamedPipeMessages.AcquireLock.Response response = new NamedPipeMessages.AcquireLock.Response(reply); + switch (response.Result) + { + case NamedPipeMessages.AcquireLock.AcceptResult: + return true; + + case NamedPipeMessages.AcquireLock.DenyGVFSResult: + // The mount is still processing working-tree changes, which can be + // the change that this command must see. Wait for it. + if (stopwatch.ElapsedMilliseconds + LockRetryDelayMs > lockWaitBudgetMs) + { + this.trace($"apply skipped: GVFS lock result {response.Result}"); + return false; + } + + Thread.Sleep(LockRetryDelayMs); + break; + + default: + this.trace($"apply skipped: GVFS lock result {response.Result}"); + return false; + } + } + } + } + + private void ReleaseLock(NamedPipeMessages.LockRequest lockRequest) + { + using (NamedPipeClient pipeClient = this.createPipeClient()) + { + if (!pipeClient.Connect(ReleaseConnectTimeoutMs, out Exception error)) + { + this.trace($"apply could not release the GVFS lock: {error?.Message}"); + return; + } + + pipeClient.SendRequest(lockRequest.CreateMessage(NamedPipeMessages.ReleaseLock.Request)); + NamedPipeMessages.Message reply = pipeClient.ReadResponse(); + if (reply?.Header != NamedPipeMessages.ReleaseLock.SuccessResult) + { + this.trace($"apply could not release the GVFS lock: {reply?.Header}"); + } + } + } + + private ApplyRequest StartApply(string commandId) + { + string body = new NamedPipeMessages.ConeManagement.ApplyParameters(commandId).ToBody(); + ApplyRequest apply = new ApplyRequest(); + apply.Reply = Task.Run(() => + { + using (NamedPipeClient pipeClient = this.createPipeClient()) + { + if (!pipeClient.Connect(NamedPipeMessages.ConeManagement.ConnectTimeoutMs, out _)) + { + return ConeRequestOutcome.MountUnavailable; + } + + // After the send budget ends, the hook lets Git run. A request sent after + // that could make the mount run Git while the user's Git runs. + if (!apply.TryMarkSent()) + { + return ConeRequestOutcome.TimedOut; + } + + pipeClient.SendRequest(new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.ApplyRequest, body)); + string result = pipeClient.ReadResponse()?.Header; + switch (result) + { + case NamedPipeMessages.ConeManagement.SuccessResult: + return ConeRequestOutcome.Applied; + + case NamedPipeMessages.ConeManagement.NotEnabledResult: + case NamedPipeMessages.UnknownRequest: + // This mount never applies the change, so the file is stale. + this.deletePendingFile(); + return result == NamedPipeMessages.UnknownRequest ? ConeRequestOutcome.Rejected : ConeRequestOutcome.FeatureDisabled; + + default: + return ConeRequestOutcome.Rejected; + } + } + }); + + return apply; + } + + private ConeRequestOutcome WaitForApply(ApplyRequest apply, int sendBudgetMs, int replyCeilingMs) + { + if (Task.WaitAny(new Task[] { apply.Reply, apply.Sending }, sendBudgetMs) < 0 && apply.TryAbandon()) + { + // The request was not sent, and now it never is. + return ConeRequestOutcome.TimedOut; + } + + // The request was sent, or the task ended. Git must not run while the mount can + // still run Git for the request, up to the ceiling. + return apply.Reply.Wait(replyCeilingMs) ? apply.Reply.Result : ConeRequestOutcome.ReplyTimedOut; + } + + /// One ConeApply request: the send gate and the task that reads the reply. + private sealed class ApplyRequest + { + private readonly object gate = new object(); + private readonly TaskCompletionSource sending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + private bool abandoned; + private bool sent; + + public Task Reply { get; set; } + + public Task Sending => this.sending.Task; + + public bool WasSent + { + get + { + lock (this.gate) + { + return this.sent; + } + } + } + + /// Return false when the hook gave up before the send. + public bool TryMarkSent() + { + lock (this.gate) + { + if (this.abandoned) + { + return false; + } + + this.sent = true; + } + + this.sending.TrySetResult(true); + return true; + } + + /// Return false when the request was already sent. + public bool TryAbandon() + { + lock (this.gate) + { + if (this.sent) + { + return false; + } + + this.abandoned = true; + return true; + } + } + } + } +} diff --git a/GVFS/GVFS.Hooks/Program.ConeManagement.cs b/GVFS/GVFS.Hooks/Program.ConeManagement.cs index 31353c435..dd1cc6d4e 100644 --- a/GVFS/GVFS.Hooks/Program.ConeManagement.cs +++ b/GVFS/GVFS.Hooks/Program.ConeManagement.cs @@ -4,6 +4,7 @@ using GVFS.Common.Sparse; using GVFS.Common.Tracing; using GVFS.Hooks.HooksPlatform; +using GVFS.Platform.Windows; using System; using System.IO; @@ -20,18 +21,90 @@ public partial class Program // expands the index for the command. private const long MaxConeFileBytes = 16 * 1024 * 1024; - private static void TrySendConeWiden(string[] args) + // True when the pre-command hook took the GVFS lock for the Git command. + private static bool commandHoldsGVFSLock; + + private static ConeRequestOutcome TrySendConeWiden(string[] args) { try { - CreateConeManagementHook().TrySendWiden(args); + return CreateConeManagementHook().TrySendWiden(args); } catch (Exception e) { TraceConeDiagnostic($"widen failed: {e.Message}"); + return ConeRequestOutcome.Failed; + } + } + + /// + /// Before Git reads the index, make sure that the cone includes every working-tree change + /// that the mount saw. A widen that the mount applied already includes them. + /// + private static void TryApplyPendingConeChange(string[] args, bool wasPending, ConeRequestOutcome widenOutcome) + { + if (!wasPending || widenOutcome == ConeRequestOutcome.Applied) + { + return; + } + + try + { + new PendingConeChangeHook(IsConeChangePending, DeleteConeChangePendingFile, () => new NamedPipeClient(enlistmentPipename), TraceConeDiagnostic) + .TryApply( + args, + commandHoldsGVFSLock, + processId => new NamedPipeMessages.LockRequest( + processId, + GVFSHooksPlatform.IsElevated(), + checkAvailabilityOnly: false, + GenerateFullCommand(args), + GetGitCommandSessionId())); + } + catch (Exception e) + { + TraceConeDiagnostic($"apply failed: {e.Message}"); } } + /// + /// Return true when the mount's pending file exists (see + /// ). When nothing is pending, this + /// is the only cost that cone management adds to a command that names no paths. + /// + private static bool IsConeChangePending() + { + try + { + return File.Exists(GetConeChangePendingPath()); + } + catch (Exception e) + { + TraceConeDiagnostic($"cannot check for a pending cone change: {e.Message}"); + return false; + } + } + + private static void DeleteConeChangePendingFile() + { + try + { + File.Delete(GetConeChangePendingPath()); + } + catch (Exception e) + { + TraceConeDiagnostic($"cannot delete the pending cone change file: {e.Message}"); + } + } + + private static string GetConeChangePendingPath() + { + string dotGVFSRoot = currentWorktreeInfo != null + ? Path.Combine(currentWorktreeInfo.WorktreeGitDir, WindowsPlatform.DotGVFSRoot) + : Path.Combine(enlistmentRoot, WindowsPlatform.DotGVFSRoot); + return Path.Combine(dotGVFSRoot, GVFSConstants.DotGVFS.ConeChangePending); + } + private static void TrySendConeNarrow(string[] args) { try diff --git a/GVFS/GVFS.Hooks/Program.cs b/GVFS/GVFS.Hooks/Program.cs index c4cee26be..104a3f129 100644 --- a/GVFS/GVFS.Hooks/Program.cs +++ b/GVFS/GVFS.Hooks/Program.cs @@ -137,7 +137,10 @@ private static void RunPreCommands(string[] args) break; } - TrySendConeWiden(args); + // 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); } private static bool ArgsBlockHydrationStatus(string[] args) @@ -401,6 +404,8 @@ private static void AcquireGVFSLockForProcess(bool unattended, string[] args, in { ExitWithError(result); } + + commandHoldsGVFSLock = !checkGvfsLockAvailabilityOnly; } private static void ReleaseGVFSLock(bool unattended, string[] args, int pid, NamedPipeClient pipeClient) diff --git a/GVFS/GVFS.Mount/InProcessMount.cs b/GVFS/GVFS.Mount/InProcessMount.cs index edcb99ffd..10def9a65 100644 --- a/GVFS/GVFS.Mount/InProcessMount.cs +++ b/GVFS/GVFS.Mount/InProcessMount.cs @@ -953,6 +953,7 @@ private void HandleRequest(ITracer tracer, string request, NamedPipeServer.Conne case NamedPipeMessages.ConeManagement.WidenRequest: case NamedPipeMessages.ConeManagement.NarrowRequest: + case NamedPipeMessages.ConeManagement.ApplyRequest: this.HandleConeRequest(message, connection); break; @@ -1188,6 +1189,9 @@ private void HandleReleaseLockRequest(string messageBody, NamedPipeServer.Connec if (response.Result == NamedPipeMessages.ReleaseLock.SuccessResult) { this.tracer.SetGitCommandSessionId(string.Empty); + + // The command can have committed or restored modified files. + this.coneManager?.OnGitCommandCompleted(); } connection.TrySendResponse(response.CreateMessage()); @@ -1792,11 +1796,34 @@ private void MountAndStartWorkingDirectoryCallbacks(CacheServerInfo cache, bool } this.coneManager = this.CreateConeManagerIfEnabled(); + if (this.coneManager != null) + { + this.fileSystemCallbacks.SetWorkingDirectoryChangeObserver(this.coneManager); + this.coneManager.Start(); + } + else + { + // A pending file from an earlier mount with the feature on would make every hook + // send a request that this mount does not apply. + this.DeleteConeChangePendingFile(); + } this.heartbeat = new HeartbeatThread(this.tracer, this.fileSystemCallbacks); this.heartbeat.Start(); } + private void DeleteConeChangePendingFile() + { + string pendingFilePath = MountConeManagerEnvironment.GetPendingFilePath(this.enlistment); + if (!this.context.FileSystem.TryDeleteFile(pendingFilePath, out Exception error) && error != null) + { + EventMetadata metadata = new EventMetadata(); + metadata.Add("Area", "Mount"); + metadata.Add("Exception", error.ToString()); + this.tracer.RelatedWarning(metadata, nameof(this.DeleteConeChangePendingFile) + " failed"); + } + } + private AutoSparseIndexConeManager CreateConeManagerIfEnabled() { // Use the value that the projection read, so that the mount never makes the index @@ -2339,7 +2366,12 @@ private void UnmountAndStopWorkingDirectoryCallbacks(bool willRemountInSameProce this.heartbeat = null; } - this.coneManager = null; + if (this.coneManager != null) + { + this.fileSystemCallbacks?.SetWorkingDirectoryChangeObserver(null); + this.coneManager.Stop(); + this.coneManager = null; + } if (this.fileSystemCallbacks != null) { diff --git a/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs b/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs index e57cfd559..d6f200fcb 100644 --- a/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs +++ b/GVFS/GVFS.Mount/MountConeManagerEnvironment.cs @@ -14,9 +14,13 @@ namespace GVFS.Mount /// internal class MountConeManagerEnvironment : IConeManagerEnvironment { + // The background check stops Git after this long. The cone then keeps the files. + private const int ListPathsTimeoutMs = 2 * 60 * 1000; + private readonly GVFSContext context; private readonly FileSystemCallbacks fileSystemCallbacks; private readonly string coneFileLockPath; + private readonly string pendingFilePath; public MountConeManagerEnvironment(GVFSContext context, FileSystemCallbacks fileSystemCallbacks, string sparseCheckoutPath) { @@ -27,6 +31,20 @@ public MountConeManagerEnvironment(GVFSContext context, FileSystemCallbacks file this.context = context; this.fileSystemCallbacks = fileSystemCallbacks; this.coneFileLockPath = sparseCheckoutPath + GVFSConstants.DotGit.LockExtension; + this.pendingFilePath = GetPendingFilePath(context.Enlistment); + } + + /// + /// The mount creates the manager only for a Git that shows + /// , and such a Git changes only + /// the index when the cone changes. + /// + public bool SparsityChangeIsIndexOnly => true; + + /// The path of the file that tells the hooks that a cone change is pending. + public static string GetPendingFilePath(GVFSEnlistment enlistment) + { + return Path.Combine(enlistment.DotGVFSRoot, GVFSConstants.DotGVFS.ConeChangePending); } public IEnumerable GetModifiedPaths() @@ -116,5 +134,64 @@ public ProcessStartTimeResult TryGetProcessStartTime(int processId, out long sta { return GVFSPlatform.Instance.TryGetActiveProcessStartTime(processId, out startTime); } + + public bool TrySetConeChangePending(bool pending, out Exception error) + { + error = null; + try + { + if (pending) + { + // The hook only checks that the file exists. + using (new FileStream(this.pendingFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete)) + { + } + } + else + { + File.Delete(this.pendingFilePath); + } + + return true; + } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) + { + error = e; + return false; + } + } + + public bool TryGetPathsThatDifferFromHead(out ICollection paths, out string error) + { + List differing = new List(); + GitProcess.Result result = new GitProcess(this.context.Enlistment).ListPathsThatDifferFromHead(differing.Add, ListPathsTimeoutMs); + if (result.ExitCodeIsFailure) + { + paths = null; + error = result.Errors; + return false; + } + + paths = differing; + error = null; + return true; + } + + public long GetRepositoryStamp() + { + try + { + // "git reset --soft" moves HEAD without a write to the index, but Git logs the + // move in the HEAD reflog. + long index = File.GetLastWriteTimeUtc(this.context.Enlistment.GitIndexPath).Ticks; + long headLog = File.GetLastWriteTimeUtc(this.context.Enlistment.GitHeadLogPath).Ticks; + return unchecked((index * 31) + headLog); + } + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) + { + // Unknown: the manager checks again. + return DateTime.UtcNow.Ticks; + } + } } } diff --git a/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs b/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs index 841613988..ec50a9454 100644 --- a/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs +++ b/GVFS/GVFS.Platform.Windows/WindowsFileSystemVirtualizer.cs @@ -1959,7 +1959,7 @@ private void NotifyFileHandleClosedFileModifiedOrDeletedHandler( } else { - this.FileSystemCallbacks.InvalidateGitStatusCache(); + this.FileSystemCallbacks.OnFileModified(virtualPath); } } else if (isFileDeleted) diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs index ea7f67497..fb67ab4d3 100644 --- a/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs +++ b/GVFS/GVFS.UnitTests/Common/Sparse/AutoSparseIndexConeManagerTests.cs @@ -45,7 +45,13 @@ public void SetUp() this.environment = new MockEnvironment(this.fileSystem); this.environment.RunningProcesses[FirstGit] = 1; this.environment.RunningProcesses[SecondGit] = 2; - this.manager = new AutoSparseIndexConeManager(this.tracer, this.fileSystem, SparseCheckoutPath, ignoreCase: false, this.environment); + this.manager = this.CreateManager(ignoreCase: false, changeCheckDelayMs: Timeout.Infinite); + } + + [TearDown] + public void TearDown() + { + this.manager.Stop(); } [TestCase("git version 2.56.1.vfs.0.0.6\nfeature: fsmonitor--daemon\nfeature: vfs-sparse-index\n", 0, true)] @@ -367,6 +373,38 @@ public void WidenIsRefusedWhenItCannotStartGitInTime() this.LastEvent("ConeWiden").Metadata["Result"].ShouldEqual("TooLateToApply"); } + [TestCase] + public void ApplyIsRefusedWhenTheRequesterLosesTheGVFSLockBeforeGitRuns() + { + // A deleted file makes the manager list the sparse directories with Git first. + this.environment.ModifiedPaths.AddRange(new[] { "C/c.txt", "D/deleted.txt" }); + this.environment.DeletedFiles.Add("D/deleted.txt"); + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.DuringListSparseDirectories = () => this.environment.LockHolder = SecondGit; + + this.Apply(FirstGit).ShouldBeFalse(); + + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + this.environment.IsPending.ShouldBeTrue(); + this.LastEvent("ConeApply").Metadata["Result"].ShouldEqual("NotLockHolder"); + } + + [TestCase] + public void ApplyIsRefusedWhenItCannotStartGitInTime() + { + this.UseMaxElapsedBeforeApply(500); + this.environment.ModifiedPaths.AddRange(new[] { "C/c.txt", "D/deleted.txt" }); + this.environment.DeletedFiles.Add("D/deleted.txt"); + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.DuringListSparseDirectories = () => Thread.Sleep(600); + + this.Apply(FirstGit).ShouldBeFalse(); + + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + this.environment.IsPending.ShouldBeTrue(); + this.LastEvent("ConeApply").Metadata["Result"].ShouldEqual("TooLateToApply"); + } + [TestCase] public void WidenIsRefusedWhenTheSparseDirectoriesAreNotKnown() { @@ -636,11 +674,444 @@ public void HandleRequestRepliesFailureForANarrowBodyThatIsNotValid() .ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); } + [TestCase] + public void StartMakesTheFirstCommandApplyTheConeOfTheModifiedPaths() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + + this.manager.Start(); + this.environment.IsPending.ShouldBeTrue(); + + this.Apply(FirstGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithC); + this.environment.IsPending.ShouldBeFalse(); + this.LastEvent("ConeApply").Level.ShouldEqual(EventLevel.Informational); + } + + [TestCase] + public void ChangeOutsideTheAppliedConeIsPendingUntilTheNextApply() + { + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.IsPending.ShouldBeFalse(); + + // The callback runs before the mount adds the path to the modified paths. + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.ModifiedPaths.Add("C/c.txt"); + this.environment.IsPending.ShouldBeTrue(); + + this.Apply(FirstGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + this.environment.ConeFilesAtApply.Last().ShouldEqual(ConeWithC); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void ChangeInsideTheAppliedConeIsNotPending() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.OnWorkingDirectoryPathChanged(@"C\other.txt", isFolder: false); + this.manager.OnWorkingDirectoryPathChanged("root.txt", isFolder: false); + + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void FolderChangeIsPendingUntilTheConeIncludesItsWholeSubtree() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.OnWorkingDirectoryPathChanged(@"C\new", isFolder: true); + this.environment.ModifiedPaths.Add("C/new/"); + this.environment.IsPending.ShouldBeTrue(); + + this.Apply(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC + "/C/new/\n"); + } + + [TestCase] + public void WidenAlsoAppliesThePendingChanges() + { + this.Apply(FirstGit).ShouldBeTrue(); + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.ModifiedPaths.Add("C/c.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n/C/\n!/C/*/\n"); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void ApplyForACommandThatDoesNotHoldTheGVFSLockKeepsTheChangePending() + { + this.manager.Start(); + this.environment.LockHolder = SecondGit; + + this.Apply(FirstGit).ShouldBeFalse(); + + this.environment.IsPending.ShouldBeTrue(); + this.environment.ConeFilesAtApply.ShouldBeEmpty(); + } + + [TestCase] + public void FailedApplyKeepsTheChangePendingUntilAnApplySucceeds() + { + this.manager.Start(); + this.environment.ApplyExitCode = 1; + + for (int attempt = 0; attempt < 5; attempt++) + { + this.Apply(FirstGit).ShouldBeFalse(); + this.environment.IsPending.ShouldBeTrue("Git has no fallback for a change that the index does not show"); + } + + this.environment.ApplyExitCode = 0; + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void ApplyIncludesAChangeBeforeTheModifiedPathsHaveIt() + { + this.Apply(FirstGit).ShouldBeTrue(); + + // The background task that adds the modified path waits while Git holds the lock. + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.Apply(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + + // The cone keeps the path until the modified paths have it. + this.Widen(SecondGit, "A/B/b.txt").ShouldBeTrue(); + this.Narrow(SecondGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + + this.environment.ModifiedPaths.Add("C/c.txt"); + this.environment.DifferingPaths.Add("C/c.txt"); + this.manager.TryReconcile().ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void ChangedPathThatIsNotAModifiedPathLeavesTheConeWhenItIsClean() + { + this.Apply(FirstGit).ShouldBeTrue(); + + // For example, Git wrote the file with the content of HEAD. + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.Apply(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void PendingFileThatCannotBeDeletedIsDeletedByTheNextApply() + { + this.manager.Start(); + this.environment.PendingFileDeleteFails = true; + + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.IsPending.ShouldBeTrue(); + + this.environment.PendingFileDeleteFails = false; + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void PendingFileThatCannotBeCreatedIsCreatedByTheNextChange() + { + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.PendingFileFails = true; + + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.IsPending.ShouldBeFalse(); + + this.environment.PendingFileFails = false; + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.IsPending.ShouldBeTrue(); + } + + [TestCase] + public void ReconcileRemovesAModifiedFileThatMatchesHeadWithoutRunningGitToApply() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + this.environment.DiffCount.ShouldEqual(1); + this.environment.ConeFilesAtApply.Count.ShouldEqual(1, "Only Git can apply a cone"); + this.environment.IsPending.ShouldBeFalse(); + // The root file .gitattributes is clean too. + this.LastEvent("ConeReconcile").Metadata["NewlyCleanCount"].ShouldEqual(2); + } + + [TestCase] + public void ReconcileKeepsFilesThatDifferFromHead() + { + // C differs, D is untracked, E is a deleted tracked file, and F was created and + // deleted again. + this.environment.ModifiedPaths.AddRange(new[] { "C/c.txt", "D/d.txt", "E/e.txt", "F/f.txt" }); + this.environment.DifferingPaths.Add("C/c.txt"); + this.environment.UntrackedFiles.Add("D/d.txt"); + this.environment.DeletedFiles.Add("E/e.txt"); + this.environment.DeletedFiles.Add("F/f.txt"); + this.environment.UntrackedFiles.Add("F/f.txt"); + this.environment.SparsityChangeIsIndexOnly = true; + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header + "/C/\n!/C/*/\n/D/\n!/D/*/\n/E/\n!/E/*/\n"); + } + + [TestCase] + public void ReconcileKeepsAFileInAnUntrackedFolderAndRemovesAnIgnoredFile() + { + // Git lists the untracked folder A/B/, not the file in it. Git does not list the + // ignored file C/c.log. + this.environment.ModifiedPaths.AddRange(new[] { "A/B/new.txt", "C/c.log" }); + this.environment.DifferingPaths.Add("A/B/"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithAB); + } + + [TestCase] + public void ReconcileUsesTheRepositoryCaseRule() + { + this.manager = this.CreateManager(ignoreCase: true, changeCheckDelayMs: Timeout.Infinite); + this.environment.ModifiedPaths.Add("C/c.txt"); + this.environment.DifferingPaths.Add("c/C.TXT"); + this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void CleanFileThatChangesAgainIsPendingAndTheApplyWidensTheCone() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.manager.TryReconcile().ShouldBeTrue(); + this.ConeFile.ShouldEqual(Header); + + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + this.environment.IsPending.ShouldBeTrue(); + this.Apply(FirstGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + this.environment.ConeFilesAtApply.Last().ShouldEqual(ConeWithC); + } + + [TestCase] + public void CleanFileThatDiffersAfterAHeadChangeIsPending() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.manager.TryReconcile().ShouldBeTrue(); + this.ConeFile.ShouldEqual(Header); + + // For example "git reset --soft HEAD~1" after a commit of the file. + this.environment.DifferingPaths.Add("C/c.txt"); + this.environment.RepositoryStamp++; + this.manager.TryReconcile().ShouldBeTrue(); + + this.environment.IsPending.ShouldBeTrue(); + this.Apply(FirstGit).ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void ReconcileDoesNotRunGitWhileAChangeIsPendingOrWhenNothingChanged() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.manager.Start(); + + this.manager.TryReconcile().ShouldBeTrue(); + this.environment.DiffCount.ShouldEqual(0, "A pending change can be in a directory that the index does not expand"); + + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DifferingPaths.Add("C/c.txt"); + this.manager.TryReconcile().ShouldBeTrue(); + this.manager.TryReconcile().ShouldBeTrue(); + this.environment.DiffCount.ShouldEqual(1); + } + + [TestCase] + public void ChangeDuringTheCheckKeepsTheFileInTheCone() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DuringDiff = () => this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void ChangeInsideTheAppliedConeStartsACheckWhenTheChangesStop() + { + this.manager.Stop(); + this.manager = this.CreateManager(ignoreCase: false, changeCheckDelayMs: 10); + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + + // For example, an editor wrote the content of HEAD back. + this.manager.OnWorkingDirectoryPathChanged(@"C\c.txt", isFolder: false); + + SpinWait.SpinUntil(() => this.tracer.SnapshotRelatedEvents().Any(recorded => recorded.Name == "ConeReconcile"), TimeSpan.FromSeconds(10)) + .ShouldBeTrue("The check did not run"); + this.ConeFile.ShouldEqual(Header); + this.environment.IsPending.ShouldBeFalse(); + } + + [TestCase] + public void CheckThatCannotWriteTheConeFileTriesAgainWithoutGit() + { + this.manager = this.CreateManager(ignoreCase: false, changeCheckDelayMs: 200); + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.ConeFileLocked = true; + + this.manager.TryReconcile().ShouldBeFalse(); + this.ConeFile.ShouldEqual(ConeWithC); + this.environment.ConeFileLocked = false; + + SpinWait.SpinUntil(() => this.ConeFile == Header, TimeSpan.FromSeconds(10)).ShouldBeTrue("The check did not try again"); + this.environment.DiffCount.ShouldEqual(1); + } + + [TestCase] + public void ApplyRunsGitForANewModifiedPathThatACheckWroteToTheConeFile() + { + const string ConeWithD = Header + "/D/\n!/D/*/\n"; + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DuringDiff = () => + { + this.environment.ModifiedPaths.Add("D/d.txt"); + this.manager.OnWorkingDirectoryPathChanged(@"D\d.txt", isFolder: false); + }; + + // The check writes D into the cone file, but the index does not expand D yet. + this.manager.TryReconcile().ShouldBeTrue(); + this.ConeFile.ShouldEqual(ConeWithD); + + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.ConeFilesAtApply.Last().ShouldEqual(ConeWithD); + } + + [TestCase] + public void ApplyDuringTheCheckDiscardsTheResult() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DuringDiff = () => this.Apply(FirstGit).ShouldBeTrue(); + + this.manager.TryReconcile().ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithC); + } + + [TestCase] + public void ReconcileFailureKeepsTheCone() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.DiffFails = true; + + this.manager.TryReconcile().ShouldBeFalse(); + + this.ConeFile.ShouldEqual(ConeWithC); + this.LastEvent("ConeReconcile").Level.ShouldEqual(EventLevel.Warning); + } + + [TestCase] + public void NarrowDoesNotPutACleanFileBackInTheCone() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.manager.TryReconcile().ShouldBeTrue(); + + this.Widen(SecondGit, "A/B/b.txt").ShouldBeTrue(); + this.Narrow(SecondGit).ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header); + } + + [TestCase] + public void WhenGitChangesOnlyTheIndexADeletedFileInASparseDirectoryIsInTheCone() + { + this.environment.SparsityChangeIsIndexOnly = true; + this.environment.SparseDirectories.Add("A/"); + this.environment.ModifiedPaths.Add("A/B/deleted.txt"); + this.environment.DeletedFiles.Add("A/B/deleted.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(ConeWithAB); + this.environment.ConeFilesAtApply.ShouldMatchInOrder(ConeWithAB); + } + + [TestCase] + public void DeletedFileInTheAppliedConeDoesNotNeedTheSparseDirectories() + { + this.environment.ModifiedPaths.Add("C/c.txt"); + this.Apply(FirstGit).ShouldBeTrue(); + this.environment.SparseDirectoriesFail = true; + this.environment.ModifiedPaths.Add("C/deleted.txt"); + this.environment.DeletedFiles.Add("C/deleted.txt"); + + this.Widen(FirstGit, "A/B/b.txt").ShouldBeTrue(); + + this.ConeFile.ShouldEqual(Header + "/A/\n!/A/*/\n/A/B/\n!/A/B/*/\n/C/\n!/C/*/\n"); + } + + [TestCase] + public void HandleRequestAppliesAnApplyRequest() + { + this.manager.Start(); + + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.ApplyRequest, FirstGit.ToString())) + .ShouldEqual(NamedPipeMessages.ConeManagement.SuccessResult); + AutoSparseIndexConeManager.HandleRequest(this.manager, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.ApplyRequest, "x")) + .ShouldEqual(NamedPipeMessages.ConeManagement.FailureResult); + AutoSparseIndexConeManager.HandleRequest(null, this.tracer, new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.ApplyRequest, FirstGit.ToString())) + .ShouldEqual(NamedPipeMessages.ConeManagement.NotEnabledResult); + this.environment.IsPending.ShouldBeFalse(); + } + private string ConeFile => this.fileSystem.ReadAllText(SparseCheckoutPath); private void UseMaxElapsedBeforeApply(int milliseconds) { - this.manager = new AutoSparseIndexConeManager(this.tracer, this.fileSystem, SparseCheckoutPath, ignoreCase: false, this.environment, milliseconds); + this.manager = new AutoSparseIndexConeManager(this.tracer, this.fileSystem, SparseCheckoutPath, ignoreCase: false, this.environment, milliseconds, Timeout.Infinite); + } + + private AutoSparseIndexConeManager CreateManager(bool ignoreCase, int changeCheckDelayMs) + { + return new AutoSparseIndexConeManager(this.tracer, this.fileSystem, SparseCheckoutPath, ignoreCase, this.environment, AutoSparseIndexConeManager.DefaultMaxElapsedBeforeApplyMs, changeCheckDelayMs); + } + + private bool Apply(int processId) + { + return this.manager.TryApply(new NamedPipeMessages.ConeManagement.ApplyParameters(processId.ToString())); } private bool Widen(int processId, params string[] paths) @@ -729,6 +1200,71 @@ public MockEnvironment(MockFileSystem fileSystem) public bool IsConeFileLockHeld => this.lockHeld != 0; + public bool SparsityChangeIsIndexOnly { get; set; } + + public bool IsPending { get; private set; } + + public int PendingFileCreateCount { get; private set; } + + public bool PendingFileFails { get; set; } + + public bool PendingFileDeleteFails { get; set; } + + public HashSet DifferingPaths { get; } = new HashSet(); + + public HashSet UntrackedFiles { get; } = new HashSet(); + + public bool DiffFails { get; set; } + + public int DiffCount { get; private set; } + + public Action DuringDiff { get; set; } + + public long RepositoryStamp { get; set; } + + public bool TrySetConeChangePending(bool pending, out Exception error) + { + if (this.PendingFileFails || (!pending && this.PendingFileDeleteFails)) + { + error = new IOException("Injected pending file failure"); + return false; + } + + if (pending && !this.IsPending) + { + this.PendingFileCreateCount++; + } + + this.IsPending = pending; + error = null; + return true; + } + + public bool TryGetPathsThatDifferFromHead(out ICollection paths, out string error) + { + this.DiffCount++; + this.DuringDiff?.Invoke(); + if (this.DiffFails) + { + paths = null; + error = "fatal: injected failure"; + return false; + } + + // Like Git: an untracked file that exists, and a tracked file that was deleted. + paths = this.DifferingPaths + .Concat(this.UntrackedFiles.Except(this.DeletedFiles)) + .Concat(this.DeletedFiles.Except(this.UntrackedFiles)) + .ToList(); + error = null; + return true; + } + + public long GetRepositoryStamp() + { + return this.RepositoryStamp; + } + public IEnumerable GetModifiedPaths() { return this.ModifiedPaths.ToList(); diff --git a/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj index 68275bd68..45cdb7d8e 100644 --- a/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj +++ b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj @@ -34,6 +34,9 @@ Hooks\ConeRequestOutcome.cs + + Hooks\PendingConeChangeHook.cs + Hooks\GitCommandLock.cs diff --git a/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs b/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs index 6af3f9c9c..cff508e14 100644 --- a/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs +++ b/GVFS/GVFS.UnitTests/Git/GitProcessTests.cs @@ -30,6 +30,19 @@ public void ReadStdOutTokens_SplitsOnNul() tokens.ShouldMatchInOrder("a.txt", "d/b.txt", "d/c.txt"); } + [TestCase("1 .M N... 100644 100644 100644 0123 0123 d/a.txt", "d/a.txt")] + [TestCase("1 D. N... 100644 000000 000000 0123 0000 d/with space.txt", "d/with space.txt")] + [TestCase("u UU N... 100644 100644 100644 100644 0123 0456 0789 d/conflict.txt", "d/conflict.txt")] + [TestCase("? d/untracked.txt", "d/untracked.txt")] + [TestCase("? d/new folder/", "d/new folder/")] + [TestCase("! d/ignored.txt", null)] + [TestCase("# branch.oid 0123", null)] + [TestCase("1 .M N... 100644", null)] + public void GetPorcelainV2PathReturnsThePathOfAChangedEntry(string record, string expectedPath) + { + GitProcess.GetPorcelainV2Path(record).ShouldEqual(expectedPath); + } + [TestCase] public void ReadStdOutTokens_EmptyInputYieldsNoTokens() { diff --git a/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs b/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs new file mode 100644 index 000000000..7c7563cb0 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Hooks/PendingConeChangeHookTests.cs @@ -0,0 +1,299 @@ +using GVFS.Common.NamedPipes; +using GVFS.Hooks; +using GVFS.Tests.Should; +using GVFS.UnitTests.Mock.Common; +using NUnit.Framework; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Threading; + +namespace GVFS.UnitTests.Hooks +{ + [TestFixture] + public class PendingConeChangeHookTests + { + private const string GitPid = "--git-pid=1234"; + + // Tests that expect a reply use a long budget, so that a slow test machine cannot turn + // the reply into a timeout. + private const int ReplyBudgetMs = 30000; + + private bool pending; + private bool pendingFileDeleted; + private Queue clients; + private List createdClients; + private int lockRequestCount; + private int lockProcessId; + + [SetUp] + public void SetUp() + { + this.pending = true; + this.pendingFileDeleted = false; + this.clients = new Queue(); + this.createdClients = new List(); + this.lockRequestCount = 0; + this.lockProcessId = 0; + } + + [TestCase] + public void NothingPendingSendsNothing() + { + this.pending = false; + + this.Apply(holdsLock: true, "status").ShouldEqual(ConeRequestOutcome.NothingPending); + this.Apply(holdsLock: false, "diff").ShouldEqual(ConeRequestOutcome.NothingPending); + + this.createdClients.ShouldBeEmpty(); + } + + [TestCase] + public void CommandThatHoldsTheLockSendsAnApplyWithItsCommandId() + { + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ConeManagement.SuccessResult)); + + this.Apply(holdsLock: true, "commit", "-a", "-m", "message").ShouldEqual(ConeRequestOutcome.Applied); + + this.RequestHeaders().ShouldMatchInOrder(NamedPipeMessages.ConeManagement.ApplyRequest); + this.createdClients[0].Requests[0].Body.ShouldEqual("1234"); + this.lockRequestCount.ShouldEqual(0); + } + + [TestCase("log")] + [TestCase("fetch")] + [TestCase("git-diff")] + public void UnlockedCommandThatDoesNotReadTheIndexSendsNothing(string command) + { + this.Apply(holdsLock: false, command).ShouldEqual(ConeRequestOutcome.NotAnIndexReader); + + this.createdClients.ShouldBeEmpty(); + } + + [TestCase("diff")] + [TestCase("ls-files")] + [TestCase("rev-parse")] + [TestCase("show")] + [TestCase("status")] + public void UnlockedIndexReaderTakesTheLockForTheApplyAndReleasesIt(string command) + { + this.clients.Enqueue(ReplyWith(NamedPipeMessages.AcquireLock.AcceptResult)); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ConeManagement.SuccessResult)); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ReleaseLock.SuccessResult)); + + this.Apply(holdsLock: false, command).ShouldEqual(ConeRequestOutcome.Applied); + + this.RequestHeaders().ShouldMatchInOrder( + NamedPipeMessages.AcquireLock.AcquireRequest, + NamedPipeMessages.ConeManagement.ApplyRequest, + NamedPipeMessages.ReleaseLock.Request); + this.lockProcessId.ShouldEqual(1234, "The lock and the apply must name the same process"); + } + + [TestCase] + public void UnlockedIndexReaderWaitsWhileTheMountProcessesChanges() + { + Queue results = new Queue(new[] { NamedPipeMessages.AcquireLock.DenyGVFSResult, NamedPipeMessages.AcquireLock.AcceptResult }); + this.clients.Enqueue(new MockNamedPipeClient { ReadResponseCallback = () => new NamedPipeMessages.Message(results.Dequeue(), null) }); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ConeManagement.SuccessResult)); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.ReleaseLock.SuccessResult)); + + this.Apply(holdsLock: false, "diff").ShouldEqual(ConeRequestOutcome.Applied); + + this.createdClients[0].Requests.Count.ShouldEqual(2); + } + + [TestCase] + public void UnlockedIndexReaderDoesNotWaitForAnotherGitCommand() + { + this.clients.Enqueue(ReplyWith(NamedPipeMessages.AcquireLock.DenyGitResult)); + + this.Apply(holdsLock: false, "diff").ShouldEqual(ConeRequestOutcome.LockUnavailable); + + this.RequestHeaders().ShouldMatchInOrder(NamedPipeMessages.AcquireLock.AcquireRequest); + } + + [TestCase] + public void UnlockedIndexReaderKeepsTheLockUntilTheMountFinishesAfterATimeout() + { + List events = new List(); + this.clients.Enqueue(ReplyWith(NamedPipeMessages.AcquireLock.AcceptResult)); + this.clients.Enqueue(new MockNamedPipeClient + { + ReadResponseCallback = () => + { + // The mount replies after the hook stopped its wait. + Thread.Sleep(300); + lock (events) + { + events.Add("apply reply"); + } + + return new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null); + }, + }); + this.clients.Enqueue(new MockNamedPipeClient + { + ReadResponseCallback = () => + { + lock (events) + { + events.Add("release"); + } + + return new NamedPipeMessages.Message(NamedPipeMessages.ReleaseLock.SuccessResult, null); + }, + }); + + this.CreateHook().TryApply(BuildArgs("diff"), holdsLock: false, this.CreateLockRequest, replyCeilingMs: 10) + .ShouldEqual(ConeRequestOutcome.ReplyTimedOut); + + events.ShouldMatchInOrder("apply reply", "release"); + } + + [TestCase] + public void SentApplyWaitsForTheReplyAfterTheSendBudget() + { + this.clients.Enqueue(new MockNamedPipeClient + { + ReadResponseCallback = () => + { + Thread.Sleep(300); + return new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null); + }, + }); + + Stopwatch stopwatch = Stopwatch.StartNew(); + this.CreateHook().TryApply(BuildArgs("status"), holdsLock: true, this.CreateLockRequest, replyCeilingMs: ReplyBudgetMs, sendBudgetMs: 10) + .ShouldEqual(ConeRequestOutcome.Applied); + + (stopwatch.ElapsedMilliseconds >= 300).ShouldBeTrue("The hook let Git run before the reply"); + } + + [TestCase] + public void SentApplyLetsGitRunAtTheReplyCeiling() + { + ManualResetEventSlim releaseReply = new ManualResetEventSlim(initialState: false); + this.clients.Enqueue(new MockNamedPipeClient + { + ReadResponseCallback = () => + { + releaseReply.Wait(); + return new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null); + }, + }); + + Stopwatch stopwatch = Stopwatch.StartNew(); + this.CreateHook().TryApply(BuildArgs("status"), holdsLock: true, this.CreateLockRequest, replyCeilingMs: 200, sendBudgetMs: ReplyBudgetMs) + .ShouldEqual(ConeRequestOutcome.ReplyTimedOut); + stopwatch.Stop(); + releaseReply.Set(); + + (stopwatch.ElapsedMilliseconds < 5000).ShouldBeTrue("The hook waited after the reply ceiling"); + this.RequestHeaders().ShouldMatchInOrder(NamedPipeMessages.ConeManagement.ApplyRequest); + } + + [TestCase] + public void ApplyThatCannotSendInTheSendBudgetLetsGitRunAndNeverSends() + { + ManualResetEventSlim releaseConnect = new ManualResetEventSlim(initialState: false); + MockNamedPipeClient client = new MockNamedPipeClient + { + ConnectCallback = () => releaseConnect.Wait(), + Response = new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null), + }; + this.clients.Enqueue(client); + + Stopwatch stopwatch = Stopwatch.StartNew(); + this.CreateHook().TryApply(BuildArgs("status"), holdsLock: true, this.CreateLockRequest, replyCeilingMs: ReplyBudgetMs, sendBudgetMs: 50) + .ShouldEqual(ConeRequestOutcome.TimedOut); + stopwatch.Stop(); + (stopwatch.ElapsedMilliseconds < 5000).ShouldBeTrue("The hook waited for the reply ceiling without a send"); + + // The test lets the abandoned task connect, then checks that the task did not send. + releaseConnect.Set(); + SpinWait.SpinUntil(() => client.Disposed, 5000).ShouldBeTrue(); + client.Requests.ShouldBeEmpty(); + } + + [TestCase(NamedPipeMessages.ConeManagement.NotEnabledResult, "FeatureDisabled")] + [TestCase(NamedPipeMessages.UnknownRequest, "Rejected")] + public void MountThatNeverAppliesTheChangeDeletesThePendingFile(string reply, string expected) + { + this.clients.Enqueue(ReplyWith(reply)); + + this.Apply(holdsLock: true, "status").ToString().ShouldEqual(expected); + + this.pendingFileDeleted.ShouldBeTrue(); + } + + [TestCase] + public void MountThatIsNotReadyKeepsThePendingFile() + { + this.clients.Enqueue(ReplyWith(NamedPipeMessages.MountNotReadyResult)); + + this.Apply(holdsLock: true, "status").ShouldEqual(ConeRequestOutcome.Rejected); + + this.pendingFileDeleted.ShouldBeFalse(); + } + + [TestCase] + public void UnlockedIndexReaderWithoutAProcessIdSendsNothing() + { + this.CreateHook().TryApply(new[] { "pre-command", "diff" }, holdsLock: false, this.CreateLockRequest, ReplyBudgetMs) + .ShouldEqual(ConeRequestOutcome.Failed); + + this.createdClients.ShouldBeEmpty(); + } + + private static string[] BuildArgs(params string[] command) + { + List args = new List { "pre-command" }; + args.AddRange(command); + args.Add(GitPid); + return args.ToArray(); + } + + private static MockNamedPipeClient ReplyWith(string responseHeader) + { + return new MockNamedPipeClient { Response = new NamedPipeMessages.Message(responseHeader, null) }; + } + + private ConeRequestOutcome Apply(bool holdsLock, params string[] command) + { + return this.CreateHook().TryApply(BuildArgs(command), holdsLock, this.CreateLockRequest, ReplyBudgetMs); + } + + private NamedPipeMessages.LockRequest CreateLockRequest(int processId) + { + this.lockRequestCount++; + this.lockProcessId = processId; + return new NamedPipeMessages.LockRequest(processId, isElevated: false, checkAvailabilityOnly: false, "git diff", gitCommandSessionId: string.Empty); + } + + private List RequestHeaders() + { + lock (this.createdClients) + { + return this.createdClients.SelectMany(client => client.Requests).Select(request => request.Header).ToList(); + } + } + + private PendingConeChangeHook CreateHook() + { + return new PendingConeChangeHook( + () => this.pending, + () => this.pendingFileDeleted = true, + () => + { + lock (this.createdClients) + { + MockNamedPipeClient client = this.clients.Dequeue(); + this.createdClients.Add(client); + return client; + } + }, + trace: null); + } + } +} \ No newline at end of file diff --git a/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs b/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs index 0ceb04e21..66b7a3821 100644 --- a/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs +++ b/GVFS/GVFS.UnitTests/Virtualization/FileSystemCallbacksTests.cs @@ -2,6 +2,7 @@ using GVFS.Common.Database; using GVFS.Common.FileSystem; using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; using GVFS.Common.Tracing; using GVFS.Tests.Should; using GVFS.UnitTests.Category; @@ -426,6 +427,54 @@ public void WorktreeLogsHeadWatcherRefreshesWorktreeProperties() } } + [TestCase] + public void WorkingDirectoryChangesReachTheObserver() + { + Mock mockPlaceholderDb = new Mock(MockBehavior.Strict); + mockPlaceholderDb.Setup(x => x.GetCount()).Returns(1); + Mock mockSparseDb = new Mock(MockBehavior.Strict); + mockSparseDb.Setup(x => x.GetAll()).Returns(new HashSet()); + using (MockBackgroundFileSystemTaskRunner backgroundTaskRunner = new MockBackgroundFileSystemTaskRunner()) + using (FileSystemCallbacks fileSystemCallbacks = new FileSystemCallbacks( + this.Repo.Context, + this.Repo.GitObjects, + RepoMetadata.Instance, + new MockBlobSizes(), + gitIndexProjection: null, + backgroundFileSystemTaskRunner: backgroundTaskRunner, + fileSystemVirtualizer: null, + placeholderDatabase: mockPlaceholderDb.Object, + sparseCollection: mockSparseDb.Object)) + { + RecordingObserver observer = new RecordingObserver(); + fileSystemCallbacks.SetWorkingDirectoryChangeObserver(observer); + + fileSystemCallbacks.OnFileModified(@"A\modified.txt"); + fileSystemCallbacks.OnFileConvertedToFull(@"A\full.txt"); + fileSystemCallbacks.OnFileCreated(@"A\created.txt"); + fileSystemCallbacks.OnFileDeleted(@"A\deleted.txt"); + fileSystemCallbacks.OnFileRenamed(@"A\old.txt", @"B\new.txt"); + fileSystemCallbacks.OnFolderRenamed(@"A\OldFolder", @"B\NewFolder"); + fileSystemCallbacks.OnFolderDeleted(@"A\DeletedFolder"); + fileSystemCallbacks.OnFileModified(@".git\config"); + + observer.Changes.ShouldMatchInOrder( + @"A\modified.txt", + @"A\full.txt", + @"A\created.txt", + @"A\deleted.txt", + @"A\old.txt", + @"B\new.txt", + @"A\OldFolder\", + @"B\NewFolder\", + @"A\DeletedFolder\"); + + fileSystemCallbacks.SetWorkingDirectoryChangeObserver(null); + fileSystemCallbacks.OnFileModified(@"A\after.txt"); + observer.Changes.Count.ShouldEqual(9); + } + } + [TestCase] public void FileAndFolderCallbacksScheduleBackgroundTasks() { @@ -597,5 +646,15 @@ private void CallbackSchedulesBackgroundTask( backgroundTaskRunner.BackgroundTasks[0].VirtualPath.ShouldEqual(newPath); backgroundTaskRunner.BackgroundTasks.Clear(); } + + private sealed class RecordingObserver : IWorkingDirectoryChangeObserver + { + public List Changes { get; } = new List(); + + public void OnWorkingDirectoryPathChanged(string relativePath, bool isFolder) + { + this.Changes.Add(isFolder ? relativePath + Path.DirectorySeparatorChar : relativePath); + } + } } } diff --git a/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs b/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs index 16ef07d80..310bd4414 100644 --- a/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs +++ b/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs @@ -3,6 +3,7 @@ using GVFS.Common.FileSystem; using GVFS.Common.Git; using GVFS.Common.NamedPipes; +using GVFS.Common.Sparse; using GVFS.Common.Tracing; using GVFS.Virtualization.Background; using GVFS.Virtualization.BlobSize; @@ -48,6 +49,9 @@ public class FileSystemCallbacks : IDisposable, IHeartBeatMetadataProvider private GitStatusCache gitStatusCache; private bool enableGitStatusCache; + // Receives the working-tree changes, or null. See SetWorkingDirectoryChangeObserver. + private IWorkingDirectoryChangeObserver workingDirectoryChangeObserver; + public FileSystemCallbacks( GVFSContext context, GVFSGitObjects gitObjects, @@ -729,25 +733,48 @@ public void OnExcludeFileChanged() this.InvalidateGitStatusCache(); } + /// + /// Set the receiver of working-tree changes, or null to stop the notifications. The + /// receiver runs in file system callbacks. + /// + public void SetWorkingDirectoryChangeObserver(IWorkingDirectoryChangeObserver observer) + { + Volatile.Write(ref this.workingDirectoryChangeObserver, observer); + } + + /// + /// A handle to a file that was written was closed. This happens for every change, also + /// for a file that already is a full file. + /// + public void OnFileModified(string relativePath) + { + this.InvalidateGitStatusCache(); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); + } + public void OnFileCreated(string relativePath) { this.AddToNewlyCreatedList(relativePath, isFolder: false); this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileCreated(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFileOverwritten(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileOverwritten(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFileSuperseded(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileSuperseded(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFileConvertedToFull(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileConvertedToFull(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFailedFileHydration(string relativePath) @@ -758,21 +785,26 @@ public void OnFailedFileHydration(string relativePath) public virtual void OnFileRenamed(string oldRelativePath, string newRelativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileRenamed(oldRelativePath, newRelativePath)); + this.NotifyWorkingDirectoryChange(oldRelativePath, isFolder: false); + this.NotifyWorkingDirectoryChange(newRelativePath, isFolder: false); } public virtual void OnFileHardLinkCreated(string newLinkRelativePath, string existingRelativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileHardLinkCreated(newLinkRelativePath, existingRelativePath)); + this.NotifyWorkingDirectoryChange(newLinkRelativePath, isFolder: false); } public virtual void OnFileSymLinkCreated(string newLinkRelativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileSymLinkCreated(newLinkRelativePath)); + this.NotifyWorkingDirectoryChange(newLinkRelativePath, isFolder: false); } public void OnFileDeleted(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFileDeleted(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: false); } public void OnFilePreDelete(string relativePath) @@ -803,16 +835,20 @@ public void OnFolderCreated(string relativePath, out bool sparseFoldersUpdated) this.AddToNewlyCreatedList(relativePath, isFolder: true); this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFolderCreated(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: true); } public virtual void OnFolderRenamed(string oldRelativePath, string newRelativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFolderRenamed(oldRelativePath, newRelativePath)); + this.NotifyWorkingDirectoryChange(oldRelativePath, isFolder: true); + this.NotifyWorkingDirectoryChange(newRelativePath, isFolder: true); } public void OnFolderDeleted(string relativePath) { this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFolderDeleted(relativePath)); + this.NotifyWorkingDirectoryChange(relativePath, isFolder: true); } public void OnPossibleTombstoneFolderCreated(string relativePath) @@ -825,6 +861,15 @@ public void OnFolderPreDelete(string relativePath) this.backgroundFileSystemTaskRunner.Enqueue(FileSystemTask.OnFolderPreDelete(relativePath)); } + private void NotifyWorkingDirectoryChange(string relativePath, bool isFolder) + { + IWorkingDirectoryChangeObserver observer = Volatile.Read(ref this.workingDirectoryChangeObserver); + if (observer != null && !string.IsNullOrEmpty(relativePath) && !IsPathInsideDotGit(relativePath)) + { + observer.OnWorkingDirectoryPathChanged(relativePath, isFolder); + } + } + public void OnPlaceholderFileCreated(string relativePath, string sha, string triggeringProcessImageFileName) { this.GitIndexProjection.OnPlaceholderFileCreated(relativePath, sha);