From 9bee91dede285569acbe37cbcdfb2e1554ab1cd7 Mon Sep 17 00:00:00 2001 From: Tyrie Vella Date: Mon, 16 Nov 2026 11:09:53 -0800 Subject: [PATCH] Expand sparse-directory entries in the projection With a sparse index (git index.sparse), git stores each folder outside the sparse-checkout cone as one sparse-directory entry. The entry has mode 040000, a path that ends in '/', and the id of the folder tree. The projection must still contain every file, because the user sees the full working directory. Add the gvfs.auto-sparse-index setting (default false). When it is false, the projection rejects a sparse index, as before. When it is true, the projection reads the tree behind each sparse-directory entry through libgit2, and adds every file under it. The result is the same projection that the full index gives: - The walk reads the trees depth first, in tree order, which is the same as index order. Folder names that differ only in case merge as they do for a full index, and the first name wins. - A folder is added only when a file under it is added, because a full index has no entry for an empty tree. - A file is not added if the file, or a folder above it, is in the modified paths. For a full index, git clears the skip-worktree bit of these entries, so the projection does not contain them. - A missing tree is downloaded once. The download stops when the mount stops. If a tree is still missing, is not a tree, or cannot be read, or if a tree has an entry that git cannot add to an index (for example '..', '.git', or a path longer than 4095 bytes), the build fails with SparseIndexExpansionException. The mount shows its message, which tells the user what to do next, without a stack. Keep the other index consumers correct for a sparse index: - The placeholder scan treats a placeholder under a sparse-directory entry as an index entry with the skip-worktree bit only if the file is in the tree of the entry. Otherwise, as for a full index, the file moves to the modified paths and stays on disk. If the tree cannot be read, the scan treats the file as not in the index. If the sparse-directory entry has no skip-worktree bit, the scan adds the folder to the modified paths. - The hydration summary of a mounted enlistment gets the file count from the projection, because the index header counts a collapsed folder as one entry. - 'gvfs repair' validates a sparse-directory entry, but does not read the trees, and does not replace a valid sparse index. - GVFS.PerfProfiling accepts a sparse index when the setting is true. Fix LazyUTF8String.BytePool.MakeFreeSpace, which expanded the pool only once. A name longer than one expansion was copied past the end of the pool. A sparse index has few entries, so its pools start small. Add LibGit2Repo.EnumerateTree, which reads a tree with git_object_lookup and reports a missing tree, a non-tree object, and an unreadable tree as different results. Add GitRepo.TryEnumerateTree, GitRepo.GetConfigBoolOrDefault, a cancellable GVFSGitObjects.TryDownloadAndSaveObject overload, and the RequestSource.ProjectionBuild value. The projection build telemetry records the expansion counts, also when the build fails. Add unit tests that build the projection from a full index and from sparse indexes of the same trees, and compare every folder, file, SHA, folder inclusion, and file mode. Other unit tests check the modified-paths rule, the placeholder scan, the failure paths, small string pools, and the hydration file count. Unit tests also read trees through LibGit2Repo.EnumerateTree from a repository that libgit2 writes in a temporary folder. Add a functional test that mounts an enlistment with a sparse index. Assisted-by: Claude Opus 5.5 Signed-off-by: Tyrie Vella --- GVFS/GVFS.Common/GVFSConstants.cs | 7 + GVFS/GVFS.Common/Git/GVFSGitObjects.cs | 7 + GVFS/GVFS.Common/Git/GitRepo.cs | 36 + GVFS/GVFS.Common/Git/LibGit2Repo.cs | 87 ++ GVFS/GVFS.Common/Git/TreeEnumeration.cs | 49 + GVFS/GVFS.Common/GitStatusCache.cs | 13 +- .../EnlistmentHydrationSummary.cs | 12 +- .../SparseIndexMountTests.cs | 96 ++ GVFS/GVFS.Mount/InProcessMount.cs | 5 + GVFS/GVFS.PerfProfiling/Program.cs | 5 +- .../Common/EnlistmentHydrationSummaryTests.cs | 13 + .../Common/LibGit2TreeEnumerationTests.cs | 231 ++++ .../Projection/SparseIndexExpansionTests.cs | 1023 +++++++++++++++++ .../FileSystemCallbacks.cs | 2 + .../GitIndexProjection.FolderData.cs | 25 + .../GitIndexProjection.GitIndexEntry.cs | 38 + .../GitIndexProjection.GitIndexParser.cs | 244 +++- .../GitIndexProjection.LazyUTF8String.cs | 3 +- .../GitIndexProjection.SortedFolderEntries.cs | 26 + ...IndexProjection.SparseDirectoryExpander.cs | 965 ++++++++++++++++ .../Projection/GitIndexProjection.cs | 146 ++- GVFS/GVFS.Virtualization/Projection/Readme.md | 13 + .../SparseIndexExpansionException.cs | 20 + .../SparseIndexNotSupportedException.cs | 3 +- GVFS/GVFS/RepairJobs/RepairJob.cs | 11 +- 25 files changed, 3020 insertions(+), 60 deletions(-) create mode 100644 GVFS/GVFS.Common/Git/TreeEnumeration.cs create mode 100644 GVFS/GVFS.UnitTests/Common/LibGit2TreeEnumerationTests.cs create mode 100644 GVFS/GVFS.UnitTests/Virtualization/Projection/SparseIndexExpansionTests.cs create mode 100644 GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SparseDirectoryExpander.cs create mode 100644 GVFS/GVFS.Virtualization/Projection/SparseIndexExpansionException.cs diff --git a/GVFS/GVFS.Common/GVFSConstants.cs b/GVFS/GVFS.Common/GVFSConstants.cs index a9bdccaf9f..0f6ce06deb 100644 --- a/GVFS/GVFS.Common/GVFSConstants.cs +++ b/GVFS/GVFS.Common/GVFSConstants.cs @@ -103,6 +103,13 @@ public static class GitConfig public const string PrefetchOffload = GVFSPrefix + "prefetch-offload"; public const bool PrefetchOffloadDefault = false; + + /* Gates sparse-index support (git index.sparse). When true, the projection expands each + * sparse-directory entry from its tree, so the working directory stays full. When false + * (default), the projection rejects a sparse index. The mount reads it when it starts, + * and 'gvfs repair' reads it when it checks the index. */ + public const string AutoSparseIndex = GVFSPrefix + "auto-sparse-index"; + public const bool AutoSparseIndexDefault = false; } public static class LocalGVFSConfig diff --git a/GVFS/GVFS.Common/Git/GVFSGitObjects.cs b/GVFS/GVFS.Common/Git/GVFSGitObjects.cs index 582d6b464b..e6f7d4a4df 100644 --- a/GVFS/GVFS.Common/Git/GVFSGitObjects.cs +++ b/GVFS/GVFS.Common/Git/GVFSGitObjects.cs @@ -32,6 +32,7 @@ public enum RequestSource GVFSVerb, NamedPipeMessage, SymLinkCreation, + ProjectionBuild, } /// @@ -261,6 +262,12 @@ public DownloadAndSaveObjectResult TryDownloadAndSaveObject(string objectId, Req return this.TryDownloadAndSaveObject(objectId, CancellationToken.None, requestSource, retryOnFailure: true).Result; } + /// was canceled + public DownloadAndSaveObjectResult TryDownloadAndSaveObject(string objectId, CancellationToken cancellationToken, RequestSource requestSource) + { + return this.TryDownloadAndSaveObject(objectId, cancellationToken, requestSource, retryOnFailure: true).Result; + } + public bool TryGetBlobSizeLocally(string sha, out long length) { return this.Context.Repository.TryGetBlobLength(sha, out length); diff --git a/GVFS/GVFS.Common/Git/GitRepo.cs b/GVFS/GVFS.Common/Git/GitRepo.cs index 1d74c911a8..56709a208a 100644 --- a/GVFS/GVFS.Common/Git/GitRepo.cs +++ b/GVFS/GVFS.Common/Git/GitRepo.cs @@ -216,6 +216,42 @@ public virtual bool TryGetConfigValue(string name, out string value) return this.libgit2RepoInvoker.TryInvoke(repo => repo.GetConfigString(name), out value); } + /// + /// Reads a boolean git config value through , + /// which uses git.exe instead of libgit2 when the environment changes git config. + /// Virtual so that unit tests can supply config values. + /// + /// + /// The config value, or if the setting is unset or no + /// libgit2 repo is available. + /// + /// git.exe cannot read the setting. + public virtual bool GetConfigBoolOrDefault(string name, bool defaultValue) + { + if (this.libgit2RepoInvoker == null) + { + return defaultValue; + } + + return this.libgit2RepoInvoker.GetConfigBoolOrDefault(name, defaultValue); + } + + /// + /// Reads the entries of a tree object from the local object store. Does not download objects. + /// + /// The 20-byte object id of the tree + /// Receives each entry, in tree order. The spans are valid only during the call. + public virtual TreeEnumerationResult TryEnumerateTree(byte[] treeId, TreeEntryVisitor visitor) + { + if (this.libgit2RepoInvoker == null || + !this.libgit2RepoInvoker.TryInvoke(repo => repo.EnumerateTree(treeId, visitor), out TreeEnumerationResult result)) + { + return TreeEnumerationResult.RepositoryUnavailable; + } + + return result; + } + public void Dispose() { if (this.libgit2RepoInvoker != null) diff --git a/GVFS/GVFS.Common/Git/LibGit2Repo.cs b/GVFS/GVFS.Common/Git/LibGit2Repo.cs index 06c703e86d..c1429472c1 100644 --- a/GVFS/GVFS.Common/Git/LibGit2Repo.cs +++ b/GVFS/GVFS.Common/Git/LibGit2Repo.cs @@ -28,6 +28,8 @@ namespace GVFS.Common.Git /// public class LibGit2Repo : IDisposable { + private const int GitOidLength = 20; + // git.exe reads config from these variables, or uses them to select config files. // libgit2 does not. // @@ -338,6 +340,80 @@ public virtual string[] GetMissingSubTrees(string treeSha) return missingSubtreesList.ToArray(); } + /// + /// Reads the entries of a tree object from the local object store, and calls + /// once for each entry, in tree order. Does not download objects. + /// + /// The 20-byte object id of the tree + /// Receives each entry. The spans are valid only during the call. + public virtual unsafe TreeEnumerationResult EnumerateTree(byte[] treeId, TreeEntryVisitor visitor) + { + if (treeId == null || treeId.Length != GitOidLength) + { + throw new ArgumentException($"A tree id must have {GitOidLength} bytes", nameof(treeId)); + } + + GitOid oid = new GitOid { Id = treeId }; + Native.ResultCode lookupResult = Native.Object.Lookup(out IntPtr treeHandle, this.RepoHandle, ref oid, Native.Object.AnyType); + if (lookupResult == Native.ResultCode.NotFound) + { + return TreeEnumerationResult.MissingTree; + } + + if (lookupResult != Native.ResultCode.Success || treeHandle == IntPtr.Zero) + { + EventMetadata metadata = new EventMetadata(); + metadata.Add("TreeSha", oid.ToString()); + metadata.Add("ResultCode", (int)lookupResult); + metadata.Add("NativeError", this.GetLastNativeError()); + this.Tracer?.RelatedWarning(metadata, $"{nameof(this.EnumerateTree)}: git_object_lookup failed"); + return TreeEnumerationResult.CorruptTree; + } + + try + { + if (Native.Object.GetType(treeHandle) != Native.ObjectTypes.Tree) + { + return TreeEnumerationResult.NotTree; + } + + uint entryCount = Native.Tree.GetEntryCount(treeHandle); + for (uint i = 0; i < entryCount; i++) + { + // The entry, its name, and its id belong to the tree. Do not free them. + IntPtr entryHandle = Native.Tree.GetEntryByIndex(treeHandle, i); + if (entryHandle == IntPtr.Zero) + { + return TreeEnumerationResult.CorruptTree; + } + + byte* name = Native.Tree.GetEntryName(entryHandle); + IntPtr entryId = Native.Tree.GetEntryId(entryHandle); + if (name == null || entryId == IntPtr.Zero) + { + return TreeEnumerationResult.CorruptTree; + } + + int nameLength = 0; + while (name[nameLength] != 0) + { + nameLength++; + } + + visitor( + new ReadOnlySpan(name, nameLength), + new ReadOnlySpan((byte*)entryId, GitOidLength), + Native.Tree.GetEntryFileMode(entryHandle)); + } + } + finally + { + Native.Object.Free(treeHandle); + } + + return TreeEnumerationResult.Success; + } + /// /// Get a config value from the repo's git config. /// @@ -1267,6 +1343,12 @@ private static string MarshalUtf8String(IntPtr ptr) public static class Object { + // GIT_OBJECT_ANY: git_object_lookup returns an object of any type. + public const int AnyType = -2; + + [DllImport(Git2NativeLibName, EntryPoint = "git_object_lookup")] + public static extern ResultCode Lookup(out IntPtr objectHandle, IntPtr repoHandle, ref GitOid id, int type); + [DllImport(Git2NativeLibName, EntryPoint = "git_object_type")] public static extern ObjectTypes GetType(IntPtr objectHandle); @@ -1302,6 +1384,11 @@ public static class Tree [DllImport(Git2NativeLibName, EntryPoint = "git_tree_entry_id")] public static extern IntPtr GetEntryId(IntPtr entryHandle); + // Returns a borrowed, NUL-terminated UTF-8 name that the tree owns. It is read as raw + // bytes, so the marshaller does not copy or free it. + [DllImport(Git2NativeLibName, EntryPoint = "git_tree_entry_name")] + public static unsafe extern byte* GetEntryName(IntPtr entryHandle); + /* git_tree_entry_type requires the object to exist, so we can't use it to check if * a missing entry is a tree. Instead, we can use the file mode to determine if it is a tree. */ [DllImport(Git2NativeLibName, EntryPoint = "git_tree_entry_filemode")] diff --git a/GVFS/GVFS.Common/Git/TreeEnumeration.cs b/GVFS/GVFS.Common/Git/TreeEnumeration.cs new file mode 100644 index 0000000000..189e1199c1 --- /dev/null +++ b/GVFS/GVFS.Common/Git/TreeEnumeration.cs @@ -0,0 +1,49 @@ +using System; + +namespace GVFS.Common.Git +{ + /// + /// The result of an attempt to read the entries of a tree object from the local object store. + /// + public enum TreeEnumerationResult + { + /// + /// The object is a tree. The visitor received every entry, in tree order. + /// + Success, + + /// + /// The object is not in the local object store. The visitor received no entries. + /// A download can make the object available. + /// + MissingTree, + + /// + /// The object is in the local object store, but it is not a tree. The visitor received no entries. + /// + NotTree, + + /// + /// The object is in the local object store, but it cannot be read. The visitor can have + /// received some entries before the failure. The caller must discard them. + /// + CorruptTree, + + /// + /// The repository is not available, for example because it is shutting down. + /// The visitor received no entries. + /// + RepositoryUnavailable, + } + + /// + /// Receives one entry of a tree object. + /// + /// The UTF-8 name of the entry. It is valid only during the call. + /// The 20-byte object id of the entry. It is valid only during the call. + /// + /// The git file mode of the entry, for example 0100644 (file), 0100755 (executable), + /// 0120000 (symbolic link), 0160000 (gitlink), or 040000 (tree). + /// + public delegate void TreeEntryVisitor(ReadOnlySpan name, ReadOnlySpan objectId, uint fileMode); +} diff --git a/GVFS/GVFS.Common/GitStatusCache.cs b/GVFS/GVFS.Common/GitStatusCache.cs index 3ac34f287b..a48cfe96f3 100644 --- a/GVFS/GVFS.Common/GitStatusCache.cs +++ b/GVFS/GVFS.Common/GitStatusCache.cs @@ -58,6 +58,7 @@ public class GitStatusCache : IDisposable private readonly Lock hydrationStatisticsLock = new Lock(); private Func projectedFolderCountProvider; + private Func projectedFileCountProvider; private Func> modifiedPathsProvider; private volatile CacheState cacheState = CacheState.Dirty; @@ -99,6 +100,15 @@ public void SetProjectedFolderCountProvider(Func provider) this.projectedFolderCountProvider = provider; } + /// + /// Sets the provider of the projected file count for the hydration summary. The provider + /// returns -1 when the index entry count is the file count (a full index). + /// + public void SetProjectedFileCountProvider(Func provider) + { + this.projectedFileCountProvider = provider; + } + public void SetModifiedPathsProvider(Func> provider) { ArgumentNullException.ThrowIfNull(provider); @@ -566,7 +576,8 @@ internal virtual HydrationStatusCircuitBreaker CreateHydrationCircuitBreaker() internal virtual EnlistmentHydrationSummary CreateHydrationSummary(HydrationSummaryDiagnostics diagnostics) { return EnlistmentHydrationSummary.CreateSummary(this.context.Enlistment, this.context.FileSystem, this.context.Tracer, - this.projectedFolderCountProvider, new EnlistmentPathData(this.modifiedPathsProvider), this.shutdownTokenSource.Token, diagnostics); + this.projectedFolderCountProvider, new EnlistmentPathData(this.modifiedPathsProvider), this.shutdownTokenSource.Token, diagnostics, + this.projectedFileCountProvider); } private void RecordHydrationSkip(NamedPipeMessages.HydrationStatus.CacheState state) diff --git a/GVFS/GVFS.Common/HealthCalculator/EnlistmentHydrationSummary.cs b/GVFS/GVFS.Common/HealthCalculator/EnlistmentHydrationSummary.cs index 5d3ea16ea6..5c4c41e9dd 100644 --- a/GVFS/GVFS.Common/HealthCalculator/EnlistmentHydrationSummary.cs +++ b/GVFS/GVFS.Common/HealthCalculator/EnlistmentHydrationSummary.cs @@ -65,7 +65,8 @@ internal static EnlistmentHydrationSummary CreateSummary( Func projectedFolderCountProvider, EnlistmentPathData pathData, CancellationToken cancellationToken = default, - HydrationSummaryDiagnostics diagnostics = null) + HydrationSummaryDiagnostics diagnostics = null, + Func projectedFileCountProvider = null) { diagnostics = diagnostics ?? new HydrationSummaryDiagnostics(); EnlistmentHydrationSummary summary = new EnlistmentHydrationSummary { Diagnostics = diagnostics }; @@ -74,6 +75,15 @@ internal static EnlistmentHydrationSummary CreateSummary( { diagnostics.StartPhase(HydrationSummaryPhase.IndexRead); summary.TotalFileCount = GetIndexFileCount(enlistment, fileSystem, diagnostics); + + // A sparse index has one entry for each collapsed folder. The projection then + // knows the file count, and the index header does not. + int projectedFileCount = summary.TotalFileCount >= 0 && projectedFileCountProvider != null ? projectedFileCountProvider() : -1; + if (projectedFileCount >= 0) + { + summary.TotalFileCount = projectedFileCount; + } + diagnostics.TotalFileCount = summary.TotalFileCount >= 0 ? summary.TotalFileCount : null; diagnostics.FinishPhase(summary.TotalFileCount >= 0 ? HydrationDataState.Complete : HydrationDataState.Failed); cancellationToken.ThrowIfCancellationRequested(); diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerTestCase/SparseIndexMountTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerTestCase/SparseIndexMountTests.cs index 6266955524..35fb7a1a29 100644 --- a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerTestCase/SparseIndexMountTests.cs +++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerTestCase/SparseIndexMountTests.cs @@ -1,8 +1,12 @@ using GVFS.FunctionalTests.Tools; using GVFS.Tests.Should; using NUnit.Framework; +using System; +using System.Collections.Generic; using System.IO; using System.Linq; +using System.Security.Cryptography; +using System.Text; using System.Text.RegularExpressions; namespace GVFS.FunctionalTests.Tests.EnlistmentPerTestCase @@ -73,11 +77,103 @@ public void MountRejectsSparseIndexAndRecoveryStepsWork() File.Exists(this.Enlistment.GetVirtualPathTo(fileInCollapsedFolder)).ShouldBeTrue("Projection is missing " + fileInCollapsedFolder); } + [TestCase] + public void MountExpandsSparseIndexWhenSparseIndexSupportIsOn() + { + // A git without sparse-index support for VFS expands a sparse index when it reads it, or + // reports files under a collapsed folder as changed. + string buildOptions = GitProcess.Invoke(this.Enlistment.RepoRoot, "version --build-options"); + if (!buildOptions.Contains("feature: vfs-sparse-index")) + { + Assert.Ignore("This git does not support a sparse index with VFS (git version --build-options has no 'feature: vfs-sparse-index')"); + } + + // The expected files come from the HEAD tree, not from the working directory, so that + // the test does not create placeholders before the index collapses. + Dictionary headFiles = this.GitShouldSucceed("-c core.quotepath=false ls-tree -r HEAD") + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Select(line => line.Split('\t')) + .Where(parts => parts[0].Split(' ')[1] == "blob") + .ToDictionary(parts => parts[1].Trim(), parts => parts[0].Split(' ')[2], StringComparer.OrdinalIgnoreCase); + headFiles.Count.ShouldBeAtLeast(100, "HEAD has too few files"); + + this.Enlistment.UnmountGVFS(); + + // Turn on sparse-index support and the sparse index. The cone keeps only the files at the + // root, so git collapses every top-level folder into a sparse-directory entry when it + // writes the index. The persisted projection gets the same index, as it does when git + // collapses the index while the repository is mounted. + this.GitShouldSucceed("-c core.hookspath= config gvfs.auto-sparse-index true"); + this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckout true"); + this.GitShouldSucceed("-c core.hookspath= config core.sparseCheckoutCone true"); + this.GitShouldSucceed("-c core.hookspath= config index.sparse true"); + File.WriteAllText(this.Enlistment.GetDotGitPath("info", "sparse-checkout"), "/*\n!/*/\n"); + this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true update-index --force-write-index"); + List collapsedFolders = this.SparseDirectoryEntries(); + collapsedFolders.ShouldBeNonEmpty(); + File.Copy(this.Enlistment.GetDotGitPath("index"), Path.Combine(this.Enlistment.DotGVFSRoot, "GVFS_projection"), overwrite: true); + + this.Enlistment.MountGVFS(); + + // Every file of HEAD is visible, and no other file is + string workingDirectory = this.Enlistment.RepoRoot; + string dotGit = Path.Combine(workingDirectory, ".git") + Path.DirectorySeparatorChar; + List projectedFiles = Directory.EnumerateFiles(workingDirectory, "*", SearchOption.AllDirectories) + .Where(path => !path.StartsWith(dotGit, StringComparison.OrdinalIgnoreCase)) + .Select(path => path.Substring(workingDirectory.Length + 1).Replace(Path.DirectorySeparatorChar, '/')) + .ToList(); + List missing = headFiles.Keys.Except(projectedFiles, StringComparer.OrdinalIgnoreCase).OrderBy(path => path, StringComparer.Ordinal).ToList(); + List extra = projectedFiles.Except(headFiles.Keys, StringComparer.OrdinalIgnoreCase).OrderBy(path => path, StringComparer.Ordinal).ToList(); + missing.ShouldBeEmpty("Files of HEAD that the mount does not project: " + string.Join(", ", missing.Take(20))); + extra.ShouldBeEmpty("Files that the mount projects, but HEAD does not have: " + string.Join(", ", extra.Take(20))); + + // Every regular file hydrates to the content of its blob in HEAD + HashSet regularFiles = new HashSet( + this.GitShouldSucceed("-c core.quotepath=false ls-tree -r HEAD") + .Split('\n', StringSplitOptions.RemoveEmptyEntries) + .Where(line => line.StartsWith("100")) + .Select(line => line.Split('\t')[1].Trim()), + StringComparer.OrdinalIgnoreCase); + List wrongContent = headFiles + .Where(file => regularFiles.Contains(file.Key)) + .Where(file => BlobSha(File.ReadAllBytes(this.Enlistment.GetVirtualPathTo(file.Key))) != file.Value) + .Select(file => file.Key) + .ToList(); + wrongContent.ShouldBeEmpty("Files whose content is not the blob in HEAD: " + string.Join(", ", wrongContent.Take(20))); + + this.GitShouldSucceed("status --porcelain").ShouldEqual(string.Empty); + + // The index is still sparse, so the projection came from the sparse-directory entries + this.SparseDirectoryEntries().ShouldMatchInOrder(collapsedFolders); + } + private string GitShouldSucceed(string command, string workingDirectory = null) { ProcessResult result = GitProcess.InvokeProcess(workingDirectory ?? this.Enlistment.RepoRoot, command); result.ExitCode.ShouldEqual(0, $"git {command} failed: {result.Errors}"); return result.Output; } + + private static string BlobSha(byte[] content) + { + byte[] header = Encoding.ASCII.GetBytes($"blob {content.Length}\0"); + using (SHA1 sha1 = SHA1.Create()) + { + sha1.TransformBlock(header, 0, header.Length, null, 0); + sha1.TransformFinalBlock(content, 0, content.Length); + return BitConverter.ToString(sha1.Hash).Replace("-", string.Empty).ToLowerInvariant(); + } + } + + private List SparseDirectoryEntries() + { + // Without the virtual file system, git sees the projected folders outside the cone. By + // default it then clears their skip-worktree bits and expands the index in memory. + return this.GitShouldSucceed($"{BypassGVFS} -c sparse.expectFilesOutsideOfPatterns=true ls-files --sparse") + .Split('\n') + .Select(line => line.Trim()) + .Where(line => line.EndsWith("/")) + .ToList(); + } } } diff --git a/GVFS/GVFS.Mount/InProcessMount.cs b/GVFS/GVFS.Mount/InProcessMount.cs index 0f6c1d096f..91ff8c7cc9 100644 --- a/GVFS/GVFS.Mount/InProcessMount.cs +++ b/GVFS/GVFS.Mount/InProcessMount.cs @@ -1760,6 +1760,11 @@ private void MountAndStartWorkingDirectoryCallbacks(CacheServerInfo cache, bool // The message tells the user how to recover. GitIndexProjection already logged the stack trace. this.FailMountAndExit("Error: {0}", e.Message); } + catch (SparseIndexExpansionException e) + { + // The message tells the user what to do next. GitIndexProjection already logged the stack trace. + this.FailMountAndExit("Error: {0}", e.Message); + } catch (Exception e) { this.FailMountAndExit("Failed to initialize src folder callbacks. {0}", e.ToString()); diff --git a/GVFS/GVFS.PerfProfiling/Program.cs b/GVFS/GVFS.PerfProfiling/Program.cs index cf4bc49330..3bb9dc9e44 100644 --- a/GVFS/GVFS.PerfProfiling/Program.cs +++ b/GVFS/GVFS.PerfProfiling/Program.cs @@ -40,10 +40,13 @@ private static void Main(string[] args) } ProfilingEnvironment environment = new ProfilingEnvironment(enlistmentRootPath); + bool sparseIndexEnabled = environment.Context.Repository.GetConfigBoolOrDefault( + GVFSConstants.GitConfig.AutoSparseIndex, + GVFSConstants.GitConfig.AutoSparseIndexDefault); Dictionary allTests = new Dictionary { - { TestsToRun.ValidateIndex, () => GitIndexProjection.ReadIndex(environment.Context.Tracer, Path.Combine(environment.Enlistment.WorkingDirectoryRoot, GVFSConstants.DotGit.Index)) }, + { TestsToRun.ValidateIndex, () => GitIndexProjection.ReadIndex(environment.Context.Tracer, Path.Combine(environment.Enlistment.WorkingDirectoryRoot, GVFSConstants.DotGit.Index), acceptSparseDirectories: sparseIndexEnabled) }, { TestsToRun.RebuildProjection, () => environment.FileSystemCallbacks.GitIndexProjectionProfiler.ForceRebuildProjection() }, { TestsToRun.ValidateModifiedPaths, () => environment.FileSystemCallbacks.GitIndexProjectionProfiler.ForceAddMissingModifiedPaths(environment.Context.Tracer) }, }; diff --git a/GVFS/GVFS.UnitTests/Common/EnlistmentHydrationSummaryTests.cs b/GVFS/GVFS.UnitTests/Common/EnlistmentHydrationSummaryTests.cs index 3fe6b21044..cb9a52525d 100644 --- a/GVFS/GVFS.UnitTests/Common/EnlistmentHydrationSummaryTests.cs +++ b/GVFS/GVFS.UnitTests/Common/EnlistmentHydrationSummaryTests.cs @@ -232,6 +232,19 @@ public void CreateSummary_CancelledToken_ReturnsInvalidSummary() Assert.IsNull(result.Error); } + [TestCase(42, 42)] + [TestCase(-1, 100)] + public void ProjectedFileCountReplacesTheIndexEntryCount(int projectedFileCount, int expectedTotalFileCount) + { + // The index header of a sparse index counts each collapsed folder as one entry. + // The projection provides the file count then, and -1 for a full index. + this.AddIndex(100); + EnlistmentHydrationSummary summary = EnlistmentHydrationSummary.CreateSummary( + this.context.Enlistment, this.fileSystem, this.tracer, () => 20, new TestPathData(), projectedFileCountProvider: () => projectedFileCount); + + Assert.AreEqual(expectedTotalFileCount, summary.TotalFileCount); + } + [TestCase(100, 20, "None")] [TestCase(100, 1, "HydratedFoldersExceedTotal")] [TestCase(4, 1, "HydratedFilesExceedTotal, HydratedFoldersExceedTotal")] diff --git a/GVFS/GVFS.UnitTests/Common/LibGit2TreeEnumerationTests.cs b/GVFS/GVFS.UnitTests/Common/LibGit2TreeEnumerationTests.cs new file mode 100644 index 0000000000..5af48c88d9 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Common/LibGit2TreeEnumerationTests.cs @@ -0,0 +1,231 @@ +using GVFS.Common; +using GVFS.Common.FileSystem; +using GVFS.Common.Git; +using GVFS.Tests.Should; +using GVFS.UnitTests.Mock.Common; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; + +namespace GVFS.UnitTests.Common +{ + /// + /// Tests against a repository in a temporary folder. + /// The repository-built libgit2 writes the objects, so the tests do not start git.exe. + /// + [TestFixture] + public class LibGit2TreeEnumerationTests + { + // "café.txt", from a \u escape so that the test does not depend on the encoding of this file + private const string NonAsciiName = "caf\u00e9.txt"; + + private const uint BlobMode = 0x81A4; // 100644 + private const uint ExecutableMode = 0x81ED; // 100755 + private const uint LinkMode = 0xA000; // 120000 + private const uint CommitMode = 0xE000; // 160000 + private const uint TreeMode = 0x4000; // 040000 + + private const int OidLength = 20; + private const int ObjectTypeTree = 2; + + private string repoRoot; + private byte[] blob; + private byte[] script; + private byte[] emptyTree; + private byte[] subTree; + private byte[] rootTree; + private byte[] corruptTree; + private byte[] submoduleCommit; + + [OneTimeSetUp] + public void CreateRepo() + { + this.repoRoot = Path.Combine(Path.GetTempPath(), "GVFS.LibGit2TreeEnumerationTests_" + Path.GetRandomFileName()); + + LibGit2Repo.Native.Init(); + try + { + Check(Native.InitRepository(out IntPtr repo, this.repoRoot, isBare: 0), "git_repository_init"); + try + { + this.blob = WriteBlob(repo, "hello\n"); + this.script = WriteBlob(repo, "#!/bin/sh\n"); + this.submoduleCommit = Enumerable.Repeat((byte)0x11, OidLength).ToArray(); + + this.emptyTree = WriteTree(repo); + this.subTree = WriteTree(repo, ("b.txt", this.blob, BlobMode)); + + // The tree builder sorts the entries, so the insert order does not matter. + this.rootTree = WriteTree( + repo, + ("sub", this.subTree, TreeMode), + ("sub.txt", this.blob, BlobMode), + ("run.sh", this.script, ExecutableMode), + ("module", this.submoduleCommit, CommitMode), + ("link", this.blob, LinkMode), + ("empty", this.emptyTree, TreeMode), + (NonAsciiName, this.blob, BlobMode), + ("a.txt", this.blob, BlobMode)); + + // An entry without the NUL after its name and without an object id + this.corruptTree = WriteRawObject(repo, Encoding.ASCII.GetBytes("100644 a.txt"), ObjectTypeTree); + } + finally + { + LibGit2Repo.Native.Repo.Free(repo); + } + } + finally + { + LibGit2Repo.Native.Shutdown(); + } + } + + [OneTimeTearDown] + public void DeleteRepo() + { + if (this.repoRoot != null) + { + // libgit2 makes loose objects read-only. DeleteDirectory clears that attribute. + new PhysicalFileSystem().DeleteDirectory(this.repoRoot); + } + } + + [TestCase] + public void EnumerateTreeReturnsEveryEntryInTreeOrder() + { + List actual = new List(); + using (LibGit2Repo repo = new LibGit2Repo(new MockTracer(), this.repoRoot)) + { + repo.EnumerateTree(this.rootTree, (name, objectId, fileMode) => + { + actual.Add(Describe(Encoding.UTF8.GetString(name), objectId.ToArray(), fileMode)); + }).ShouldEqual(TreeEnumerationResult.Success); + } + + // Git sorts a tree entry as if its name ends with '/', so "sub.txt" comes before "sub". + actual.ShouldMatchInOrder( + Describe("a.txt", this.blob, BlobMode), + Describe(NonAsciiName, this.blob, BlobMode), + Describe("empty", this.emptyTree, TreeMode), + Describe("link", this.blob, LinkMode), + Describe("module", this.submoduleCommit, CommitMode), + Describe("run.sh", this.script, ExecutableMode), + Describe("sub.txt", this.blob, BlobMode), + Describe("sub", this.subTree, TreeMode)); + } + + [TestCase] + public void EnumerateTreeReportsMissingTreeAndNonTree() + { + using (LibGit2Repo repo = new LibGit2Repo(new MockTracer(), this.repoRoot)) + { + int calls = 0; + TreeEntryVisitor visitor = (name, objectId, fileMode) => calls++; + + repo.EnumerateTree(Enumerable.Repeat((byte)0x22, OidLength).ToArray(), visitor).ShouldEqual(TreeEnumerationResult.MissingTree); + repo.EnumerateTree(this.blob, visitor).ShouldEqual(TreeEnumerationResult.NotTree); + repo.EnumerateTree(this.emptyTree, visitor).ShouldEqual(TreeEnumerationResult.Success); + calls.ShouldEqual(0); + } + } + + [TestCase] + public void EnumerateTreeReportsCorruptTreeAndLogsTheNativeError() + { + MockTracer tracer = new MockTracer(); + using (LibGit2Repo repo = new LibGit2Repo(tracer, this.repoRoot)) + { + int calls = 0; + repo.EnumerateTree(this.corruptTree, (name, objectId, fileMode) => calls++).ShouldEqual(TreeEnumerationResult.CorruptTree); + calls.ShouldEqual(0); + } + + tracer.RelatedWarningEvents.ShouldContain(message => message.Contains("git_object_lookup failed")); + } + + private static string Describe(string name, byte[] objectId, uint fileMode) + { + return Convert.ToString(fileMode, 8).PadLeft(6, '0') + " " + SHA1Util.HexStringFromBytes(objectId) + " " + name; + } + + private static byte[] WriteBlob(IntPtr repo, string content) + { + byte[] bytes = Encoding.UTF8.GetBytes(content); + byte[] id = new byte[OidLength]; + Check(Native.CreateBlobFromBuffer(id, repo, bytes, (UIntPtr)bytes.Length), "git_blob_create_from_buffer"); + return id; + } + + private static byte[] WriteTree(IntPtr repo, params (string Name, byte[] Id, uint Mode)[] entries) + { + Check(Native.NewTreeBuilder(out IntPtr builder, repo, IntPtr.Zero), "git_treebuilder_new"); + try + { + foreach ((string name, byte[] id, uint mode) in entries) + { + Check(Native.InsertTreeEntry(IntPtr.Zero, builder, name, id, mode), "git_treebuilder_insert " + name); + } + + byte[] treeId = new byte[OidLength]; + Check(Native.WriteTree(treeId, builder), "git_treebuilder_write"); + return treeId; + } + finally + { + Native.FreeTreeBuilder(builder); + } + } + + private static byte[] WriteRawObject(IntPtr repo, byte[] content, int objectType) + { + Check((int)LibGit2Repo.Native.Odb.GetOdb(out IntPtr odb, repo), "git_repository_odb"); + try + { + byte[] id = new byte[OidLength]; + Check(Native.WriteObject(id, odb, content, (UIntPtr)content.Length, objectType), "git_odb_write"); + return id; + } + finally + { + LibGit2Repo.Native.Odb.Free(odb); + } + } + + private static void Check(int result, string operation) + { + result.ShouldEqual(0, operation + " failed: " + LibGit2Repo.Native.GetLastError()); + } + + /// + /// libgit2 functions that only these tests use, to write objects. + /// + private static class Native + { + [DllImport(LibGit2Repo.Native.Git2NativeLibName, EntryPoint = "git_repository_init")] + public static extern int InitRepository(out IntPtr repo, [MarshalAs(UnmanagedType.LPUTF8Str)] string path, uint isBare); + + [DllImport(LibGit2Repo.Native.Git2NativeLibName, EntryPoint = "git_blob_create_from_buffer")] + public static extern int CreateBlobFromBuffer([Out] byte[] id, IntPtr repo, byte[] buffer, UIntPtr length); + + [DllImport(LibGit2Repo.Native.Git2NativeLibName, EntryPoint = "git_treebuilder_new")] + public static extern int NewTreeBuilder(out IntPtr builder, IntPtr repo, IntPtr source); + + [DllImport(LibGit2Repo.Native.Git2NativeLibName, EntryPoint = "git_treebuilder_insert")] + public static extern int InsertTreeEntry(IntPtr entry, IntPtr builder, [MarshalAs(UnmanagedType.LPUTF8Str)] string fileName, byte[] id, uint fileMode); + + [DllImport(LibGit2Repo.Native.Git2NativeLibName, EntryPoint = "git_treebuilder_write")] + public static extern int WriteTree([Out] byte[] id, IntPtr builder); + + [DllImport(LibGit2Repo.Native.Git2NativeLibName, EntryPoint = "git_treebuilder_free")] + public static extern void FreeTreeBuilder(IntPtr builder); + + [DllImport(LibGit2Repo.Native.Git2NativeLibName, EntryPoint = "git_odb_write")] + public static extern int WriteObject([Out] byte[] id, IntPtr odb, byte[] data, UIntPtr length, int objectType); + } + } +} diff --git a/GVFS/GVFS.UnitTests/Virtualization/Projection/SparseIndexExpansionTests.cs b/GVFS/GVFS.UnitTests/Virtualization/Projection/SparseIndexExpansionTests.cs new file mode 100644 index 0000000000..30cd84d622 --- /dev/null +++ b/GVFS/GVFS.UnitTests/Virtualization/Projection/SparseIndexExpansionTests.cs @@ -0,0 +1,1023 @@ +using GVFS.Common; +using GVFS.Common.Database; +using GVFS.Common.FileSystem; +using GVFS.Common.Git; +using GVFS.Common.Tracing; +using GVFS.Tests.Should; +using GVFS.UnitTests.Category; +using GVFS.UnitTests.Mock.Common; +using GVFS.UnitTests.Mock.FileSystem; +using GVFS.UnitTests.Mock.Git; +using GVFS.Virtualization.Background; +using GVFS.Virtualization.Projection; +using Moq; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Security.Cryptography; +using System.Text; +using static GVFS.Virtualization.Projection.GitIndexProjection; +using static GVFS.Virtualization.Projection.GitIndexProjection.GitIndexParser; +using Entry = GVFS.UnitTests.Mock.Git.GitIndexV4Writer.Entry; + +namespace GVFS.UnitTests.Virtualization.Projection +{ + /// + /// Tests for the expansion of the sparse-directory entries of a sparse index (git index.sparse), + /// when gvfs.auto-sparse-index is true. Each test builds a repository of trees in memory, and + /// writes the full index and a sparse index for the same files. The projection of the sparse + /// index must be the same as the projection of the full index: every folder, every file, every + /// SHA, and every file mode. + /// + [TestFixture] + public class SparseIndexExpansionTests + { + private const uint RegularMode = 0x81A4; // 100644 + private const uint ExecutableMode = 0x81ED; // 100755 + private const uint SymLinkMode = 0xA000; // 120000 + private const uint GitLinkMode = 0xE000; // 160000 + private const uint TreeMode = 0x4000; // 040000 + + private string testRoot; + private List disposables; + + public static IEnumerable EquivalentRepositories() + { + foreach (bool supportsFileMode in new[] { true, false }) + { + yield return new TestCaseData( + supportsFileMode, + new[] { "a/x/b.txt", "a/x/deep/er/c.txt", "a/x/deep/d.txt", "a/y.txt", "b.txt", "z/1.txt" }, + new string[0], + new[] { "a/x", "z" }) + .SetName($"NestedSparseDirectoryNextToInConeFiles(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "big/a/1.txt", "big/a/b/2.txt", "big/a/b/c/3.txt", "big/a/b/c/d/4.txt", "big/e/5.txt", "big/6.txt" }, + new string[0], + new[] { "big" }) + .SetName($"DeeplyNestedTrees(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "p/a.b", "p/a/1.txt", "p/a-", "p/a0", "p/A/2.txt", "q/a.b", "q/a/1.txt", "q/a-", "q/a0", "r.txt" }, + new string[0], + new[] { "p" }) + .SetName($"TreeOrderDiffersFromProjectionOrder(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "c/Foo/Sub/1.txt", "c/foo/sub/2.txt", "c/foo/3.txt", "c/FOO.txt", "d.txt" }, + new string[0], + new[] { "c" }) + .SetName($"FolderNamesThatDifferOnlyInCase(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "e/file.txt", "e/inner/f.txt" }, + new[] { "e/empty", "e/inner/empty", "onlyempty/a", "onlyempty/b/c" }, + new[] { "e", "onlyempty" }) + .SetName($"EmptyTrees(supportsFileMode={supportsFileMode})"); + + yield return new TestCaseData( + supportsFileMode, + new[] { "m/1.txt", "n/2.txt", "o/3.txt", "o/p/4.txt" }, + new string[0], + new[] { "m", "n", "o/p" }) + .SetName($"AdjacentSparseDirectories(supportsFileMode={supportsFileMode})"); + } + } + + [SetUp] + public void SetUp() + { + if (GVFSPlatform.Instance == null) + { + GVFSPlatform.Register(new MockPlatform()); + } + + RepoMetadata.Shutdown(); + this.disposables = new List(); + this.testRoot = Path.Combine(Path.GetTempPath(), "SparseIndexExpansionTests_" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(this.testRoot); + } + + [TearDown] + public void TearDown() + { + // GVFSPlatform.Instance is shared by every fixture, so restore its default. + SetSupportsFileMode(true); + RepoMetadata.Shutdown(); + this.disposables.ForEach(disposable => disposable.Dispose()); + + if (Directory.Exists(this.testRoot)) + { + Directory.Delete(this.testRoot, recursive: true); + } + } + + [TestCaseSource(nameof(EquivalentRepositories))] + public void SparseIndexProjectsTheSameAsFullIndex(bool supportsFileMode, string[] files, string[] emptyTrees, string[] sparseDirectories) + { + SetSupportsFileMode(supportsFileMode); + TestRepository repository = new TestRepository(); + foreach (string file in files) + { + repository.AddFile(file); + } + + foreach (string emptyTree in emptyTrees) + { + repository.AddEmptyTree(emptyTree); + } + + this.ShouldProjectTheSame(repository, sparseDirectories); + } + + [TestCase(true)] + [TestCase(false)] + public void SparseIndexProjectsFileModesTheSameAsFullIndex(bool supportsFileMode) + { + SetSupportsFileMode(supportsFileMode); + TestRepository repository = new TestRepository(); + repository.AddFile("tools/run.sh", ExecutableMode); + repository.AddFile("tools/link", SymLinkMode); + repository.AddFile("tools/module", GitLinkMode); + repository.AddFile("tools/plain.txt", RegularMode); + repository.AddFile("tools/nested/run2.sh", ExecutableMode); + repository.AddFile("top.txt", RegularMode); + + List projection = this.ShouldProjectTheSame(repository, "tools"); + + if (supportsFileMode) + { + projection.ShouldContain(line => line.StartsWith("tools/run.sh=") && line.EndsWith(" Regular 755")); + projection.ShouldContain(line => line.StartsWith("tools/link=") && line.EndsWith(" SymLink 0")); + projection.ShouldContain(line => line.StartsWith("tools/module=") && line.EndsWith(" GitLink 0")); + projection.ShouldContain(line => line.StartsWith("tools/nested/run2.sh=") && line.EndsWith(" Regular 755")); + } + } + + [TestCase] + public void SparseIndexIncludesFoldersTheSameAsFullIndex() + { + // The gvfs sparse folders (ISparseCollection) mark folders as included or excluded + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + foreach (string file in new[] { "a/b/c/1.txt", "a/b/c/d/e/7.txt", "a/b/d/2.txt", "a/e/3.txt", "a/4.txt", "f/g/5.txt", "h/6.txt", "h/i/8.txt" }) + { + repository.AddFile(file); + } + + // "a/b/c" is a recursive sparse folder with folders under it. "h" is a recursive sparse + // folder above the sparse directory "h/i". + Mock sparseCollection = new Mock(MockBehavior.Strict); + sparseCollection + .Setup(x => x.GetAll()) + .Returns(new HashSet(StringComparer.OrdinalIgnoreCase) { Path.Combine("a", "b", "c"), "h" }); + + this.ShouldProjectTheSame(repository, new[] { "a", "f" }, sparseCollection: sparseCollection.Object); + this.ShouldProjectTheSame(repository, new[] { "a/b", "a/e", "f/g", "h/i" }, sparseCollection: sparseCollection.Object); + } + + [TestCase] + public void ModifiedPathsUnderSparseDirectoryAreProjectedAsInFullIndex() + { + // For a full index, the virtual file system hook reports the modified paths, and git + // clears the skip-worktree bit of each index entry that they match. The full index does + // not project those entries. Matches ignore case. + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + foreach (string file in new[] { "s/keep.txt", "s/edited.txt", "s/dir/1.txt", "s/dir/sub/2.txt", "s/only/3.txt", "s/other/4.txt", "t/5.txt", "u/6.txt", "p/x/7.txt", "p/y.txt" }) + { + repository.AddFile(file); + } + + // "p/" is a modified folder above the sparse directory "p/x" + ModifiedPathsDatabase modifiedPaths = this.CreateModifiedPaths( + "S/EDITED.txt", + "s/dir/", + "s/only/3.txt", + "t/", + "p/", + "new-folder/", + "s/other/not-in-tree.txt"); + + string[] nonSkipWorktree = { "s/edited.txt", "s/dir/1.txt", "s/dir/sub/2.txt", "s/only/3.txt", "t/5.txt", "p/x/7.txt", "p/y.txt" }; + List full = this.BuildProjection(repository.CreateFullIndex(nonSkipWorktree), repository, modifiedPaths: null); + List sparse = this.BuildProjection(repository.CreateSparseIndex(new[] { "s", "t", "u", "p/x" }, "p/y.txt"), repository, modifiedPaths); + + sparse.ShouldMatchInOrder(full); + sparse.ShouldContain(line => line.StartsWith("s/keep.txt=")); + sparse.ShouldNotContain(line => line.StartsWith("s/edited.txt=") || line.StartsWith("s/dir/") || line.StartsWith("s/only/") || line.StartsWith("t/") || line.StartsWith("p/")); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void FeatureFlagEnablesExpansionThroughRepository() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b/c.txt"); + repository.AddFile("d.txt"); + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, repository.CreateSparseIndex("a")); + + MockTracer tracer = new MockTracer(); + MockGVFSEnlistment enlistment = new MockGVFSEnlistment(this.testRoot, "mock://repoUrl", Path.Combine("mock:", "git"), gitProcess: null); + ConfiguredGitRepo gitRepo = new ConfiguredGitRepo(tracer, enlistment, repository.Store); + gitRepo.Config[GVFSConstants.GitConfig.AutoSparseIndex] = true; + GVFSContext context = new GVFSContext(tracer, new PhysicalFileSystem(), gitRepo, enlistment); + + using (GitIndexProjection projection = new GitIndexProjection(context, null, null, null, null, null, null, null)) + { + projection.BuildProjectionFromPath(tracer, indexPath); + DumpProjection(projection).ShouldMatchInOrder( + "a/", + "a/b/", + "a/b/c.txt=" + TestRepository.HashOf("blob a/b/c.txt"), + "d.txt=" + TestRepository.HashOf("blob d.txt")); + } + + gitRepo.Config[GVFSConstants.GitConfig.AutoSparseIndex] = false; + using (GitIndexProjection projection = new GitIndexProjection(context, null, null, null, null, null, null, null)) + { + Assert.Throws(() => projection.BuildProjectionFromPath(tracer, indexPath)); + } + } + + [TestCase] + public void FullIndexWithExpansionEnabledReadsNoTrees() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b.txt"); + repository.AddFile("c.txt"); + + List withoutExpansion = this.BuildProjection(repository.CreateFullIndex(), treeReader: null); + List withExpansion = this.BuildProjection(repository.CreateFullIndex(), repository); + + withExpansion.ShouldMatchInOrder(withoutExpansion); + repository.Store.ReadCount.ShouldEqual(0); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void SparseIndexWithExpansionDisabledStillFails() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b.txt"); + + SparseIndexNotSupportedException error = Assert.Throws( + () => this.BuildProjection(repository.CreateSparseIndex("a"), treeReader: null)); + error.Message.ShouldContain("sparse-directory entry 'a/'", "1. If the enlistment is mounted, run 'gvfs unmount'."); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void FileNamesThatDifferOnlyInCaseFailAsInFullIndex() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("c/A.txt"); + repository.AddFile("c/a.txt"); + + Exception fullError = Assert.Catch(() => this.BuildProjection(repository.CreateFullIndex(), repository)); + Exception sparseError = Assert.Catch(() => this.BuildProjection(repository.CreateSparseIndex("c"), repository)); + sparseError.GetType().ShouldEqual(fullError.GetType()); + sparseError.Message.ShouldEqual(fullError.Message); + } + + [TestCase] + public void MissingTreeIsDownloadedOnce() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b/c.txt"); + repository.AddFile("a/d.txt"); + string subtree = repository.GetTreeSha("a/b"); + repository.Store.MissingTrees.Add(subtree); + repository.Store.DownloadableTrees.Add(subtree); + + List full = this.BuildProjection(repository.CreateFullIndex(), treeReader: null); + List sparse = this.BuildProjection(repository.CreateSparseIndex("a"), repository); + + sparse.ShouldMatchInOrder(full); + repository.Store.Downloads.ShouldMatchInOrder(subtree); + } + + [TestCase(TreeEnumerationResult.MissingTree, false)] + [TestCase(TreeEnumerationResult.MissingTree, true)] + [TestCase(TreeEnumerationResult.CorruptTree, false)] + [TestCase(TreeEnumerationResult.NotTree, false)] + [TestCase(TreeEnumerationResult.RepositoryUnavailable, false)] + [Category(CategoryConstants.ExceptionExpected)] + public void UnreadableTreeFailsTheBuild(TreeEnumerationResult readResult, bool downloadSucceedsButTreeStaysMissing) + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b/c.txt"); + repository.AddFile("a/d.txt"); + string subtree = repository.GetTreeSha("a/b"); + repository.Store.FailingTrees[subtree] = readResult; + if (downloadSucceedsButTreeStaysMissing) + { + repository.Store.DownloadSucceedsWithoutEffect.Add(subtree); + } + + SparseIndexExpansionException error = Assert.Throws( + () => this.BuildProjection(repository.CreateSparseIndex("a"), repository)); + error.Message.ShouldContain( + "Cannot read tree " + subtree + " for the folder 'a/b' in the sparse index (" + readResult + ")", + "run 'git -c core.hookspath= config gvfs.auto-sparse-index false'"); + + // Only a missing tree can become readable after a download + repository.Store.Downloads.Count.ShouldEqual(readResult == TreeEnumerationResult.MissingTree ? 1 : 0); + } + + [TestCase("..")] + [TestCase(".")] + [TestCase(".GIT")] + [TestCase(".git.")] + [TestCase(".Git ")] + [TestCase("GIT~1")] + [TestCase("a\\b")] + [TestCase("a/b")] + [TestCase("a\0b")] + [TestCase("")] + [Category(CategoryConstants.ExceptionExpected)] + public void InvalidTreeEntryNameFailsTheBuild(string name) + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + string blob = TestRepository.HashOf("blob"); + string badTree = repository.Store.AddTree(new TreeEntry(name, RegularMode, blob)); + byte[] index = GitIndexV4Writer.Create(new Entry("bad/", GitIndexV4Writer.SparseDirectoryMode, badTree)); + + SparseIndexExpansionException error = Assert.Throws(() => this.BuildProjection(index, repository)); + error.Message.ShouldContain("The folder 'bad' in the sparse index has a tree entry with the name", "Git cannot add this name to an index."); + } + + [TestCase("a{0}b")] + [TestCase("{")] + [Category(CategoryConstants.ExceptionExpected)] + public void TreeEntryNameWithBracesIsReportedLiterally(string folderName) + { + // The name reaches the message without string.Format, so braces do not throw FormatException + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + string badTree = repository.Store.AddTree(new TreeEntry("..", RegularMode, TestRepository.HashOf("blob"))); + string parent = repository.Store.AddTree(new TreeEntry(folderName, TreeMode, badTree)); + byte[] index = GitIndexV4Writer.Create(new Entry("top/", GitIndexV4Writer.SparseDirectoryMode, parent)); + + SparseIndexExpansionException error = Assert.Throws(() => this.BuildProjection(index, repository)); + error.Message.ShouldContain("The folder 'top/" + folderName + "' in the sparse index"); + } + + [TestCase(0x81B6u)] // 100666 + [TestCase(0xA1A4u)] // 120644 + [TestCase(0x6000u)] // unknown type + [Category(CategoryConstants.ExceptionExpected)] + public void InvalidFileModeFailsTheBuildWhenThePlatformRecordsModes(uint mode) + { + SetSupportsFileMode(true); + TestRepository repository = new TestRepository(); + string badTree = repository.Store.AddTree(new TreeEntry("file", mode, TestRepository.HashOf("blob"))); + byte[] index = GitIndexV4Writer.Create(new Entry("bad/", GitIndexV4Writer.SparseDirectoryMode, badTree)); + + SparseIndexExpansionException error = Assert.Throws(() => this.BuildProjection(index, repository)); + error.Message.ShouldContain("The file 'bad/file' in the folder 'bad' of the sparse index has the invalid type"); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void PathLongerThanTheIndexLimitFailsTheBuild() + { + // Also a tree that is deeper than the projection can hold. The walk does not recurse, + // so the depth cannot exhaust the stack. + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + string tree = repository.Store.AddTree(new TreeEntry("file.txt", RegularMode, TestRepository.HashOf("blob"))); + for (int i = 0; i < SparseDirectoryExpander.MaxPathLength; i++) + { + tree = repository.Store.AddTree(new TreeEntry("d", TreeMode, tree)); + } + + byte[] index = GitIndexV4Writer.Create(new Entry("deep/", GitIndexV4Writer.SparseDirectoryMode, tree)); + + SparseIndexExpansionException error = Assert.Throws(() => this.BuildProjection(index, repository)); + error.Message.ShouldContain("has a path that is longer than " + SparseDirectoryExpander.MaxPathLength + " bytes"); + } + + [TestCase] + public void LongNamesAndWideTreesProjectTheSameAsFullIndexWithSmallPools() + { + // A sparse index has few entries, so the string pools start small. A name that is + // longer than one pool expansion must not overrun the pool. + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + for (int i = 0; i < 150; i++) + { + repository.AddFile("wide/" + i.ToString("D3") + new string('x', 200) + ".txt"); + } + + repository.AddFile("top.txt"); + + List full = this.BuildProjection(repository.CreateFullIndex(), treeReader: null); + ResetStringPools(indexEntryCount: 1); + List sparse = this.BuildProjection(repository.CreateSparseIndex("wide"), repository); + + sparse.ShouldMatchInOrder(full); + sparse.Count.ShouldEqual(152); + } + + [TestCase] + public void RebuildUsesTheCurrentModifiedPaths() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("s/a.txt"); + repository.AddFile("s/b.txt"); + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, repository.CreateSparseIndex("s")); + ModifiedPathsDatabase modifiedPaths = this.CreateModifiedPaths(); + + GitIndexProjection projection = this.CreateProjection(new Mock(MockBehavior.Strict).Object, modifiedPaths, sparseCollection: null); + try + { + projection.EnableSparseIndexExpansionForTests(repository.Store); + projection.BuildProjectionFromPath(new MockTracer(), indexPath); + DumpProjection(projection).ShouldContain(line => line.StartsWith("s/a.txt=")); + + modifiedPaths.TryAdd("s/a.txt", isFolder: false, out bool _).ShouldBeTrue(); + projection.BuildProjectionFromPath(new MockTracer(), indexPath); + DumpProjection(projection).ShouldNotContain(line => line.StartsWith("s/a.txt=")); + DumpProjection(projection).ShouldContain(line => line.StartsWith("s/b.txt=")); + } + finally + { + projection.Dispose(); + } + } + + [TestCase] + public void SparseDirectoryWithoutSkipWorktreeIsNotProjected() + { + // As a full index does not project an entry without the skip-worktree bit + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("gone/a.txt"); + repository.AddFile("kept.txt"); + byte[] index = GitIndexV4Writer.Create( + new Entry("gone/", GitIndexV4Writer.SparseDirectoryMode, repository.GetTreeSha("gone")) { SkipWorktree = false }, + new Entry("kept.txt", GitIndexV4Writer.RegularFileMode, TestRepository.HashOf("blob kept.txt"))); + + this.BuildProjection(index, repository).ShouldMatchInOrder("kept.txt=" + TestRepository.HashOf("blob kept.txt")); + repository.Store.ReadCount.ShouldEqual(0); + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void InitializeFailsAndInvalidatesProjectionWhenATreeCannotBeRead() + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b.txt"); + MockGVFSEnlistment enlistment = this.CreateEnlistmentWithMetadata(); + File.WriteAllBytes(enlistment.GitIndexPath, repository.CreateSparseIndex("a")); + repository.Store.FailingTrees[repository.GetTreeSha("a")] = TreeEnumerationResult.MissingTree; + + GitIndexProjection projection = this.CreateProjection(new Mock(MockBehavior.Strict).Object, modifiedPaths: null, sparseCollection: null, RepoMetadata.Instance); + try + { + projection.EnableSparseIndexExpansionForTests(repository.Store); + Assert.Throws(() => projection.Initialize(backgroundFileSystemTaskRunner: null)); + RepoMetadata.Instance.GetProjectionInvalid().ShouldBeTrue(); + } + finally + { + projection.Dispose(); + } + } + + [TestCase(true)] + [TestCase(false)] + public void ProjectedFileCountIsReportedOnlyForASparseIndex(bool sparse) + { + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("a/b.txt"); + repository.AddFile("a/c/d.txt"); + repository.AddFile("e.txt"); + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, sparse ? repository.CreateSparseIndex("a") : repository.CreateFullIndex()); + + GitIndexProjection projection = this.CreateProjection(new Mock(MockBehavior.Strict).Object, modifiedPaths: null, sparseCollection: null); + try + { + projection.EnableSparseIndexExpansionForTests(repository.Store); + projection.BuildProjectionFromPath(new MockTracer(), indexPath); + projection.GetProjectedFileCountIfSparseIndex().ShouldEqual(sparse ? 3 : -1); + } + finally + { + projection.Dispose(); + } + } + + [TestCase("src", true)] + [TestCase("src//x/", false)] + [TestCase("/src/", false)] + [TestCase("src/", false, (int)MergeStage.Theirs)] + [Category(CategoryConstants.ExceptionExpected)] + public void MalformedSparseDirectoryEntryFailsValidation(string path, bool supportsFileMode, int mergeStage = 0) + { + SetSupportsFileMode(supportsFileMode); + byte[] index = GitIndexV4Writer.Create(new Entry(path, GitIndexV4Writer.SparseDirectoryMode) { MergeState = (MergeStage)mergeStage }); + + using (MemoryStream stream = new MemoryStream(index)) + { + InvalidDataException error = Assert.Throws( + () => GitIndexParser.ValidateIndex(new MockTracer(), stream, GitIndexParser.SparseDirectoryHandling.Accept)); + error.Message.ShouldContain("The sparse-directory entry '" + path + "'"); + } + } + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void SparseDirectoryPathWithFileModeFailsValidation() + { + SetSupportsFileMode(true); + byte[] index = GitIndexV4Writer.Create(new Entry("src/", GitIndexV4Writer.RegularFileMode)); + + using (MemoryStream stream = new MemoryStream(index)) + { + InvalidDataException error = Assert.Throws( + () => GitIndexParser.ValidateIndex(new MockTracer(), stream, GitIndexParser.SparseDirectoryHandling.Accept)); + error.Message.ShouldContain("does not have the directory mode"); + } + } + + + [TestCase] + [Category(CategoryConstants.ExceptionExpected)] + public void RepairValidationAcceptsSparseIndexWithoutReadingTrees() + { + SetSupportsFileMode(false); + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, GitIndexV4Writer.Create(new Entry("README.md"), new Entry("src/", GitIndexV4Writer.SparseDirectoryMode))); + + GitIndexProjection projection = this.CreateProjection(placeholders: null, modifiedPaths: null, sparseCollection: null); + try + { + projection.BuildProjectionFromPath(new MockTracer(), indexPath, acceptSparseDirectories: true); + + // The setting applies to one call only + Assert.Throws(() => projection.BuildProjectionFromPath(new MockTracer(), indexPath)); + } + finally + { + projection.Dispose(); + } + } + + [TestCase] + public void PlaceholderScanTreatsFilesInSparseDirectoryTreeAsInIndex() + { + // A full index has an entry, with the skip-worktree bit, for each file in the tree of a + // collapsed folder. The placeholder scan must not move their placeholders to the + // modified paths. A placeholder for a file that is not in the tree (for example after + // 'git reset --mixed') is not in the index, so it moves to the modified paths and the + // file stays on disk. + SetSupportsFileMode(false); + TestRepository repository = new TestRepository(); + repository.AddFile("src/deep/file.txt"); + repository.AddFile("src/Foo/1.txt"); + repository.AddFile("src/foo/2.txt"); + repository.AddFile("unreadable/x.txt"); + repository.Store.FailingTrees[repository.GetTreeSha("unreadable")] = TreeEnumerationResult.CorruptTree; + ModifiedPathsDatabase modifiedPaths = this.CreateModifiedPaths(); + + string inTree = Path.Combine("src", "DEEP", "File.txt"); + string inSecondCaseFolder = Path.Combine("src", "FOO", "2.txt"); + string notInTree = Path.Combine("src", "deep", "stale.txt"); + string folderNotFile = Path.Combine("src", "deep"); + string underUnreadableTree = Path.Combine("unreadable", "x.txt"); + string underNotSkipWorktree = Path.Combine("gone", "file.txt"); + string notInIndex = Path.Combine("other", "file.txt"); + string similarPrefix = Path.Combine("src2", "file.txt"); + + Mock placeholders = new Mock(MockBehavior.Strict); + placeholders + .Setup(x => x.GetAllFilePaths()) + .Returns(new HashSet(StringComparer.OrdinalIgnoreCase) + { + inTree, inSecondCaseFolder, notInTree, folderNotFile, underUnreadableTree, underNotSkipWorktree, notInIndex, similarPrefix, "README.md" + }); + foreach (string removed in new[] { notInTree, folderNotFile, underUnreadableTree, underNotSkipWorktree, notInIndex, similarPrefix }) + { + placeholders.Setup(x => x.Remove(removed)); + } + + byte[] index = GitIndexV4Writer.Create( + new Entry("README.md"), + new Entry("gone/", GitIndexV4Writer.SparseDirectoryMode) { SkipWorktree = false }, + new Entry("src/", GitIndexV4Writer.SparseDirectoryMode, repository.GetTreeSha("src")), + new Entry("unreadable/", GitIndexV4Writer.SparseDirectoryMode, repository.GetTreeSha("unreadable"))); + + GitIndexProjection projection = this.CreateProjection(placeholders.Object, modifiedPaths, sparseCollection: null); + try + { + projection.EnableSparseIndexExpansionForTests(repository.Store); + GitIndexParser parser = new GitIndexParser(projection); + using (MemoryStream stream = new MemoryStream(index)) + { + parser.AddMissingModifiedFilesAndRemoveThemFromPlaceholderList(new MockTracer(), stream).ShouldEqual(FileSystemTaskResult.Success); + } + + placeholders.VerifyAll(); + placeholders.Verify(x => x.Remove(It.IsAny()), Times.Exactly(6)); + modifiedPaths.Contains("gone", isFolder: true).ShouldBeTrue(); + modifiedPaths.Contains("src/deep/stale.txt", isFolder: false).ShouldBeTrue(); + modifiedPaths.Contains("unreadable/x.txt", isFolder: false).ShouldBeTrue(); + modifiedPaths.Contains("other/file.txt", isFolder: false).ShouldBeTrue(); + modifiedPaths.Contains("src2/file.txt", isFolder: false).ShouldBeTrue(); + modifiedPaths.Contains("src/deep/file.txt", isFolder: false).ShouldBeFalse(); + modifiedPaths.Contains("src/foo/2.txt", isFolder: false).ShouldBeFalse(); + } + finally + { + projection.Dispose(); + } + } + + private static void SetSupportsFileMode(bool value) + { + ((MockPlatformFileSystem)GVFSPlatform.Instance.FileSystem).SupportsFileMode = value; + } + + private static void ResetStringPools(uint indexEntryCount) + { + LazyUTF8String.ResetPool(new MockTracer(), indexEntryCount); + } + + /// + /// Lists every folder and file of the projection, depth first in projection order. A + /// folder line shows whether the folder is included. A file line shows the SHA, and the + /// file type and mode when the platform supports file modes. + /// + private static List DumpProjection(GitIndexProjection projection) + { + FieldInfo rootField = typeof(GitIndexProjection).GetField("rootFolderData", BindingFlags.Instance | BindingFlags.NonPublic); + FolderData root = (FolderData)rootField.GetValue(projection); + List lines = new List(); + DumpFolder(projection, root, string.Empty, lines); + return lines; + } + + private static void DumpFolder(GitIndexProjection projection, FolderData folder, string folderPath, List lines) + { + for (int i = 0; i < folder.ChildEntries.Count; i++) + { + FolderEntryData child = folder.ChildEntries[i]; + string childPath = folderPath + child.Name.GetString(); + if (child.IsFolder) + { + FolderData childFolder = (FolderData)child; + lines.Add(childPath + "/" + (childFolder.IsIncluded ? string.Empty : " excluded")); + DumpFolder(projection, childFolder, childPath + "/", lines); + } + else + { + string line = childPath + "=" + ((FileData)child).ConvertShaToString().ToLowerInvariant(); + if (GVFSPlatform.Instance.FileSystem.SupportsFileMode) + { + projection.GetFileTypeAndMode(childPath, out FileType fileType, out ushort fileMode); + line += " " + fileType + " " + Convert.ToString(fileMode, 8); + } + + lines.Add(line); + } + } + } + + private List ShouldProjectTheSame(TestRepository repository, params string[] sparseDirectories) + { + return this.ShouldProjectTheSame(repository, sparseDirectories, sparseCollection: null); + } + + private List ShouldProjectTheSame(TestRepository repository, string[] sparseDirectories, ISparseCollection sparseCollection) + { + List full = this.BuildProjection(repository.CreateFullIndex(), treeReader: null, sparseCollection: sparseCollection); + List sparse = this.BuildProjection(repository.CreateSparseIndex(sparseDirectories), repository, sparseCollection: sparseCollection); + + full.Count.ShouldBeAtLeast(1); + sparse.ShouldMatchInOrder(full); + return sparse; + } + + private List BuildProjection(byte[] index, TestRepository treeReader, ModifiedPathsDatabase modifiedPaths = null, ISparseCollection sparseCollection = null) + { + string indexPath = Path.Combine(this.testRoot, "index"); + File.WriteAllBytes(indexPath, index); + + GitIndexProjection projection = this.CreateProjection(new Mock(MockBehavior.Strict).Object, modifiedPaths, sparseCollection); + try + { + if (treeReader != null) + { + projection.EnableSparseIndexExpansionForTests(treeReader.Store); + } + + projection.BuildProjectionFromPath(new MockTracer(), indexPath); + return DumpProjection(projection); + } + finally + { + projection.Dispose(); + } + } + + private ModifiedPathsDatabase CreateModifiedPaths(params string[] paths) + { + string dataPath = Path.Combine(this.testRoot, "ModifiedPaths_" + Guid.NewGuid().ToString("N") + ".dat"); + ModifiedPathsDatabase.TryLoadOrCreate(new MockTracer(), dataPath, new PhysicalFileSystem(), out ModifiedPathsDatabase modifiedPaths, out string error).ShouldBeTrue(error); + this.disposables.Add(modifiedPaths); + foreach (string path in paths) + { + bool isFolder = path.EndsWith("/"); + modifiedPaths.TryAdd(isFolder ? path.TrimEnd('/') : path, isFolder, out bool _).ShouldBeTrue(); + } + + return modifiedPaths; + } + + private GitIndexProjection CreateProjection(IPlaceholderCollection placeholders, ModifiedPathsDatabase modifiedPaths, ISparseCollection sparseCollection, RepoMetadata repoMetadata = null) + { + MockTracer tracer = new MockTracer(); + MockGVFSEnlistment enlistment = this.CreateEnlistment(); + GVFSContext context = new GVFSContext(tracer, new PhysicalFileSystem(), new MockGitRepo(tracer, enlistment, fileSystem: null), enlistment); + return new GitIndexProjection( + context, + gitObjects: null, + blobSizes: null, + repoMetadata: repoMetadata, + fileSystemVirtualizer: null, + placeholderDatabase: placeholders, + sparseCollection: sparseCollection, + modifiedPaths: modifiedPaths); + } + + private MockGVFSEnlistment CreateEnlistment() + { + return new MockGVFSEnlistment(this.testRoot, "mock://repoUrl", Path.Combine("mock:", "git"), gitProcess: null); + } + + private MockGVFSEnlistment CreateEnlistmentWithMetadata() + { + MockGVFSEnlistment enlistment = this.CreateEnlistment(); + Directory.CreateDirectory(Path.GetDirectoryName(enlistment.GitIndexPath)); + Directory.CreateDirectory(enlistment.DotGVFSRoot); + RepoMetadata.TryInitialize(new MockTracer(), new OverwritingFileSystem(), enlistment.DotGVFSRoot, out string error).ShouldBeTrue(error); + RepoMetadata.Instance.SetProjectionInvalid(false); + return enlistment; + } + + private class OverwritingFileSystem : PhysicalFileSystem + { + // RepoMetadata flushes through MoveAndOverwriteFile, which MockPlatform does not support + public override void MoveAndOverwriteFile(string sourceFileName, string destinationFilename) + { + File.Move(sourceFileName, destinationFilename, overwrite: true); + } + } + + private class ConfiguredGitRepo : MockGitRepo + { + private readonly IProjectionTreeReader trees; + + public ConfiguredGitRepo(ITracer tracer, Enlistment enlistment, IProjectionTreeReader trees) + : base(tracer, enlistment, fileSystem: null) + { + this.trees = trees; + } + + public Dictionary Config { get; } = new Dictionary(); + + public override bool GetConfigBoolOrDefault(string name, bool defaultValue) + { + return this.Config.TryGetValue(name, out bool value) ? value : defaultValue; + } + + public override TreeEnumerationResult TryEnumerateTree(byte[] treeId, TreeEntryVisitor visitor) + { + return this.trees.TryReadTree(treeId, visitor); + } + } + + private class TreeEntry + { + public TreeEntry(string name, uint mode, string sha) + { + this.Name = name; + this.Mode = mode; + this.Sha = sha; + } + + public string Name { get; } + public uint Mode { get; } + public string Sha { get; } + + public bool IsTree => this.Mode == TreeMode; + + // Git sorts the entries of a tree as if the name of a tree ends in '/' + public string SortKey => this.IsTree ? this.Name + "/" : this.Name; + } + + /// + /// An object store with trees only, that the expander reads through . + /// + private class FakeTreeStore : IProjectionTreeReader + { + private readonly Dictionary> trees = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + public HashSet MissingTrees { get; } = new HashSet(StringComparer.OrdinalIgnoreCase); + public HashSet DownloadableTrees { get; } = new HashSet(StringComparer.OrdinalIgnoreCase); + + // Trees whose read always gives this result + public Dictionary FailingTrees { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); + + // Trees whose download reports success, but does not make the tree readable + public HashSet DownloadSucceedsWithoutEffect { get; } = new HashSet(StringComparer.OrdinalIgnoreCase); + public List Downloads { get; } = new List(); + public int ReadCount { get; private set; } + + public string AddTree(params TreeEntry[] entries) + { + List sorted = entries.OrderBy(entry => entry.SortKey, StringComparer.Ordinal).ToList(); + string sha = TestRepository.HashOf("tree " + string.Join("|", sorted.Select(entry => $"{entry.Mode:X} {entry.Name} {entry.Sha}"))); + this.trees[sha] = sorted; + return sha; + } + + public TreeEnumerationResult TryReadTree(byte[] treeId, TreeEntryVisitor visitor) + { + this.ReadCount++; + string sha = SHA1Util.HexStringFromBytes(treeId); + if (this.FailingTrees.TryGetValue(sha, out TreeEnumerationResult failure)) + { + return failure; + } + + if (this.MissingTrees.Contains(sha) || !this.trees.TryGetValue(sha, out List entries)) + { + return TreeEnumerationResult.MissingTree; + } + + foreach (TreeEntry entry in entries) + { + visitor(Encoding.UTF8.GetBytes(entry.Name), SHA1Util.BytesFromHexString(entry.Sha), entry.Mode); + } + + return TreeEnumerationResult.Success; + } + + public bool TryDownloadTree(string treeSha) + { + this.Downloads.Add(treeSha); + if (this.DownloadSucceedsWithoutEffect.Contains(treeSha)) + { + return true; + } + + if (this.DownloadableTrees.Remove(treeSha)) + { + this.MissingTrees.Remove(treeSha); + return true; + } + + return false; + } + } + + /// + /// A set of files and empty trees. It builds the trees in a , and + /// writes a full index or a sparse index for the files. + /// + private class TestRepository + { + private readonly SortedDictionary files = new SortedDictionary(StringComparer.Ordinal); + private readonly HashSet emptyTrees = new HashSet(StringComparer.Ordinal); + private Dictionary treeShas; + + public FakeTreeStore Store { get; } = new FakeTreeStore(); + + public static string HashOf(string value) + { + using (SHA1 sha1 = SHA1.Create()) + { + return SHA1Util.HexStringFromBytes(sha1.ComputeHash(Encoding.UTF8.GetBytes(value))).ToLowerInvariant(); + } + } + + public void AddFile(string path, uint mode = RegularMode) + { + this.files.Add(path, new TreeEntry(path, mode, HashOf("blob " + path))); + this.treeShas = null; + } + + public void AddEmptyTree(string path) + { + this.emptyTrees.Add(path); + this.treeShas = null; + } + + public string GetTreeSha(string folderPath) + { + return this.BuildTrees()[folderPath]; + } + + public byte[] CreateFullIndex(params string[] notSkipWorktree) + { + return GitIndexV4Writer.Create(this.files.Values + .Select(file => new Entry(file.Name, (ushort)file.Mode, file.Sha) { SkipWorktree = !notSkipWorktree.Contains(file.Name) }) + .ToArray()); + } + + public byte[] CreateSparseIndex(params string[] sparseDirectories) + { + return this.CreateSparseIndex(sparseDirectories, new string[0]); + } + + public byte[] CreateSparseIndex(string[] sparseDirectories, params string[] notSkipWorktree) + { + Dictionary trees = this.BuildTrees(); + List entries = this.files.Values + .Where(file => !sparseDirectories.Any(folder => file.Name.StartsWith(folder + "/", StringComparison.Ordinal))) + .Select(file => new Entry(file.Name, (ushort)file.Mode, file.Sha) { SkipWorktree = !notSkipWorktree.Contains(file.Name) }) + .ToList(); + entries.AddRange(sparseDirectories.Select(folder => new Entry(folder + "/", GitIndexV4Writer.SparseDirectoryMode, trees[folder]))); + return GitIndexV4Writer.Create(entries.OrderBy(entry => entry.Path, StringComparer.Ordinal).ToArray()); + } + + /// + /// Adds a tree for every folder to the store, and returns the tree SHA of each folder path. + /// + private Dictionary BuildTrees() + { + if (this.treeShas != null) + { + return this.treeShas; + } + + Dictionary> folderEntries = new Dictionary>(StringComparer.Ordinal) { { string.Empty, new List() } }; + foreach (string folder in this.files.Keys.Select(GetParent).Concat(this.emptyTrees).ToList()) + { + for (string current = folder; current.Length > 0; current = GetParent(current)) + { + if (!folderEntries.ContainsKey(current)) + { + folderEntries.Add(current, new List()); + } + } + } + + foreach (TreeEntry file in this.files.Values) + { + folderEntries[GetParent(file.Name)].Add(new TreeEntry(GetName(file.Name), file.Mode, file.Sha)); + } + + this.treeShas = new Dictionary(StringComparer.Ordinal); + foreach (string folder in folderEntries.Keys.OrderByDescending(path => path.Count(c => c == '/')).ThenByDescending(path => path.Length)) + { + if (folder.Length == 0) + { + continue; + } + + string sha = this.Store.AddTree(folderEntries[folder].ToArray()); + this.treeShas.Add(folder, sha); + folderEntries[GetParent(folder)].Add(new TreeEntry(GetName(folder), TreeMode, sha)); + } + + return this.treeShas; + } + + private static string GetParent(string path) + { + int separator = path.LastIndexOf('/'); + return separator < 0 ? string.Empty : path.Substring(0, separator); + } + + private static string GetName(string path) + { + return path.Substring(path.LastIndexOf('/') + 1); + } + } + } +} diff --git a/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs b/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs index c3410cd73f..16ef07d809 100644 --- a/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs +++ b/GVFS/GVFS.Virtualization/FileSystemCallbacks.cs @@ -120,6 +120,8 @@ public FileSystemCallbacks( this.gitStatusCache = gitStatusCache ?? new GitStatusCache(context, TimeSpan.Zero); this.gitStatusCache.SetProjectedFolderCountProvider( () => this.GitIndexProjection.GetProjectedFolderCount()); + this.gitStatusCache.SetProjectedFileCountProvider( + () => this.GitIndexProjection.GetProjectedFileCountIfSparseIndex()); this.gitStatusCache.SetModifiedPathsProvider(this.GetAllModifiedPaths); this.logsHeadPath = this.context.Enlistment.GitHeadLogPath; diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.FolderData.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.FolderData.cs index f4866a6b4f..2492595b9a 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.FolderData.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.FolderData.cs @@ -44,6 +44,31 @@ public int GetRecursiveFolderCount() return count; } + public int GetRecursiveFileCount() + { + int count = 0; + Stack stack = new Stack(); + stack.Push(this); + + while (stack.Count > 0) + { + FolderData current = stack.Pop(); + for (int i = 0; i < current.ChildEntries.Count; i++) + { + if (current.ChildEntries[i] is FolderData childFolder) + { + stack.Push(childFolder); + } + else + { + count++; + } + } + } + + return count; + } + public void ResetData(LazyUTF8String name, bool isIncluded) { this.Name = name; diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexEntry.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexEntry.cs index 4c0a7b7151..f8f8d36853 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexEntry.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexEntry.cs @@ -59,6 +59,12 @@ public bool PathEndsInSlash get { return this.PathLength > 0 && this.PathBuffer[this.PathLength - 1] == PathSeparatorCode; } } + /// + /// True when the entry is a sparse-directory entry that the parser accepted. Its path ends + /// in '/', and its is the id of the tree of the collapsed folder. + /// + public bool IsSparseDirectory { get; set; } + public FolderData BuildingProjection_LastParent { get; set; } // Only used when buildingNewProjection is true @@ -155,6 +161,38 @@ public unsafe void BuildingProjection_ParsePath() } } + /// + /// Parses the path of a sparse-directory entry, without its trailing '/', into + /// . The final part is the name of the + /// collapsed folder. It should only be called when building a new projection. + /// + /// + /// Call before and after this method. This method does not + /// change , so the prefix compression of the next entry stays correct. + /// + public unsafe void BuildingProjection_ParseSparseDirectoryPath() + { + int length = this.PathLength - 1; + int currentPartStartIndex = 0; + this.BuildingProjection_NumParts = 0; + + fixed (byte* pathPtr = this.PathBuffer) + { + for (int i = 0; i < length; i++) + { + if (pathPtr[i] == PathSeparatorCode) + { + this.BuildingProjection_PathParts[this.BuildingProjection_NumParts] = LazyUTF8String.FromByteArray(pathPtr + currentPartStartIndex, i - currentPartStartIndex); + this.BuildingProjection_NumParts++; + currentPartStartIndex = i + 1; + } + } + + this.BuildingProjection_PathParts[this.BuildingProjection_NumParts] = LazyUTF8String.FromByteArray(pathPtr + currentPartStartIndex, length - currentPartStartIndex); + this.BuildingProjection_NumParts++; + } + } + /// /// Parses the path from the index as platform-specific relative path. /// It should only be called when running a background task. diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexParser.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexParser.cs index f1498566f6..06249914a2 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexParser.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.GitIndexParser.cs @@ -19,6 +19,7 @@ internal partial class GitIndexParser private const ushort ExtendedBit = 0x4000; private const ushort SkipWorktreeBit = 0x4000; + private const byte PathSeparatorByte = (byte)'/'; private Stream indexStream; private byte[] page; @@ -50,10 +51,28 @@ public enum MergeStage : byte Theirs = 3 } - public static void ValidateIndex(ITracer tracer, Stream indexStream) + /// + /// What does with a sparse-directory entry of a sparse index. + /// + public enum SparseDirectoryHandling + { + /// + /// Throw . The default, when + /// gvfs.auto-sparse-index is false. + /// + Reject, + + /// + /// Validate the entry, and give it to the entry action with + /// set. + /// + Accept, + } + + public static void ValidateIndex(ITracer tracer, Stream indexStream, SparseDirectoryHandling sparseDirectoryHandling = SparseDirectoryHandling.Reject) { GitIndexParser indexParser = new GitIndexParser(null); - FileSystemTaskResult result = indexParser.ParseIndex(tracer, indexStream, indexParser.resuableProjectionBuildingIndexEntry, ValidateIndexEntry); + FileSystemTaskResult result = indexParser.ParseIndex(tracer, indexStream, indexParser.resuableProjectionBuildingIndexEntry, sparseDirectoryHandling, ValidateIndexEntry); if (result != FileSystemTaskResult.Success) { @@ -75,6 +94,7 @@ public static int CountIndexFolders(ITracer tracer, Stream indexStream) tracer, indexStream, indexParser.resuableProjectionBuildingIndexEntry, + SparseDirectoryHandling.Reject, entry => { // Match the same filter as AddIndexEntryToProjection so the @@ -117,10 +137,13 @@ public void RebuildProjection(ITracer tracer, Stream indexStream) } this.projection.ClearProjectionCaches(); + this.projection.projectionHasExpandedSparseDirectories = false; + this.projection.sparseDirectoryExpander?.StartBuild(this.projection.GetModifiedPathsForExpansion); FileSystemTaskResult result = this.ParseIndex( tracer, indexStream, this.resuableProjectionBuildingIndexEntry, + this.projection.ProjectionSparseDirectoryHandling, this.AddIndexEntryToProjection); if (result != FileSystemTaskResult.Success) @@ -128,6 +151,8 @@ public void RebuildProjection(ITracer tracer, Stream indexStream) // RebuildProjection should always result in FileSystemTaskResult.Success (or a thrown exception) throw new InvalidOperationException($"{nameof(this.RebuildProjection)}: {nameof(GitIndexParser.ParseIndex)} failed to {nameof(this.AddIndexEntryToProjection)}"); } + + this.projection.projectionHasExpandedSparseDirectories = this.projection.sparseDirectoryExpander?.SparseDirectoryCount > 0; } public FileSystemTaskResult AddMissingModifiedFilesAndRemoveThemFromPlaceholderList( @@ -149,21 +174,34 @@ public FileSystemTaskResult AddMissingModifiedFilesAndRemoveThemFromPlaceholderL { "FilePlaceholderCount", filePlaceholders.Count } }); + // The tree id of each sparse-directory entry, by the platform-relative folder path + Dictionary sparseDirectories = new Dictionary(GVFSPlatform.Instance.Constants.PathComparer); + FileSystemTaskResult result = this.ParseIndex( tracer, indexStream, this.resuableBackgroundTaskThreadIndexEntry, - (data) => this.AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfNeeded(data, filePlaceholders)); + this.projection.ProjectionSparseDirectoryHandling, + (data) => this.AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfNeeded(data, filePlaceholders, sparseDirectories)); if (result != FileSystemTaskResult.Success) { return result; } + SparseDirectoryTreeLookup treeLookup = sparseDirectories.Count > 0 && this.projection.sparseDirectoryExpander != null + ? new SparseDirectoryTreeLookup(this.projection.sparseDirectoryExpander.TreeReader) + : null; + // Any paths that were not found in the index need to be added to ModifiedPaths // and removed from the placeholder list foreach (string path in filePlaceholders) { + if (treeLookup != null && this.IsInSparseDirectoryTree(tracer, path, sparseDirectories, treeLookup)) + { + continue; + } + result = this.projection.AddModifiedPath(path); if (result != FileSystemTaskResult.Success) { @@ -176,6 +214,34 @@ public FileSystemTaskResult AddMissingModifiedFilesAndRemoveThemFromPlaceholderL return FileSystemTaskResult.Success; } + /// + /// Replaces control and format characters with \uXXXX escapes, so that a path read from + /// the index cannot add lines or terminal escape sequences to a message. + /// + internal static string EscapeForDisplay(string value) + { + StringBuilder escaped = null; + for (int i = 0; i < value.Length; i++) + { + char c = value[i]; + if (char.IsControl(c) || CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Format) + { + if (escaped == null) + { + escaped = new StringBuilder(value, 0, i, value.Length + 16); + } + + escaped.Append("\\u").Append(((int)c).ToString("X4")); + } + else + { + escaped?.Append(c); + } + } + + return escaped?.ToString() ?? value; + } + private static FileSystemTaskResult ValidateIndexEntry(GitIndexEntry data) { if (data.PathLength <= 0 || data.PathBuffer[0] == 0) @@ -212,56 +278,61 @@ private static string GetSparseDirectoryEntryErrorMessage(string entryPath, stri } /// - /// Replaces control and format characters with \uXXXX escapes, so that a path read from - /// the index cannot add lines or terminal escape sequences to a message. + /// Handles a sparse-directory entry from a sparse index (git index.sparse). Such an entry + /// has mode 040000, a tree id, the skip-worktree bit, and a path that ends in '/'. It + /// stands in for a collapsed subtree. /// - private static string EscapeForDisplay(string value) + /// + /// ParseIndex calls this for every entry, before the entry callback. A callback that does + /// not know about sparse-directory entries would treat the entry as a file: the projection + /// would omit every file in the collapsed subtree and contain a folder with an empty name, + /// and the placeholder scan would treat every placeholder in the subtree as absent from + /// the index. Thus throws, and + /// sets . + /// The check uses the trailing '/' because ParseIndex reads the mode field only when + /// SupportsFileMode is true, and it is false on Windows. + /// + private void HandleSparseDirectoryEntry(GitIndexEntry data, SparseDirectoryHandling sparseDirectoryHandling, bool parseMode) { - StringBuilder escaped = null; - for (int i = 0; i < value.Length; i++) + data.IsSparseDirectory = false; + if (!data.PathEndsInSlash && data.TypeAndMode.Type != FileType.Directory) { - char c = value[i]; - if (char.IsControl(c) || CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Format) - { - if (escaped == null) - { - escaped = new StringBuilder(value, 0, i, value.Length + 16); - } - - escaped.Append("\\u").Append(((int)c).ToString("X4")); - } - else - { - escaped?.Append(c); - } + return; } - return escaped?.ToString() ?? value; - } - - /// - /// Throws if is a sparse-directory entry from a sparse index - /// (git index.sparse). Such an entry has mode 040000, a tree id, the skip-worktree bit, - /// and a path that ends in '/'. It stands in for a collapsed subtree. - /// - /// - /// ParseIndex calls this for every entry, before the entry callback. A callback that - /// received the entry would treat it as a file: the projection would omit every file in - /// the collapsed subtree and contain a folder with an empty name, and the placeholder scan - /// would treat every placeholder in the subtree as absent from the index. The check uses - /// the trailing '/' because ParseIndex reads the mode field only when SupportsFileMode is - /// true, and it is false on Windows. - /// - private void FailIfSparseDirectoryEntry(GitIndexEntry data) - { - if (data.PathEndsInSlash || data.TypeAndMode.Type == FileType.Directory) + string entryPath = Encoding.UTF8.GetString(data.PathBuffer, 0, data.PathLength); + if (sparseDirectoryHandling == SparseDirectoryHandling.Reject) { - string entryPath = Encoding.UTF8.GetString(data.PathBuffer, 0, data.PathLength); throw new SparseIndexNotSupportedException(GetSparseDirectoryEntryErrorMessage( entryPath, this.projection?.context.Enlistment.WorkingDirectoryRoot, this.projection?.projectionIndexBackupPath)); } + + string error = null; + if (!data.PathEndsInSlash) + { + error = "has the directory mode, but its path does not end in '/'"; + } + else if (parseMode && data.TypeAndMode.Type != FileType.Directory) + { + error = "has a path that ends in '/', but it does not have the directory mode"; + } + else if (data.PathLength < 2 || data.PathBuffer[0] == PathSeparatorByte || entryPath.Contains("//", StringComparison.Ordinal)) + { + error = "has an empty path component"; + } + else if (data.MergeState != MergeStage.NoConflicts) + { + error = "has a merge stage"; + } + + if (error != null) + { + throw new InvalidDataException($"The sparse-directory entry '{EscapeForDisplay(entryPath)}' in the index {error}"); + } + + data.IsSparseDirectory = true; } private FileSystemTaskResult AddIndexEntryToProjection(GitIndexEntry data) @@ -269,8 +340,15 @@ private FileSystemTaskResult AddIndexEntryToProjection(GitIndexEntry data) // Never want to project the common ancestor even if the skip worktree bit is on if ((data.MergeState != MergeStage.CommonAncestor && data.SkipWorktree) || data.MergeState == MergeStage.Yours) { - data.BuildingProjection_ParsePath(); - this.projection.AddItemFromIndexEntry(data); + if (data.IsSparseDirectory) + { + this.projection.AddSparseDirectoryEntry(data); + } + else + { + data.BuildingProjection_ParsePath(); + this.projection.AddItemFromIndexEntry(data); + } } else { @@ -290,15 +368,40 @@ private FileSystemTaskResult AddIndexEntryToProjection(GitIndexEntry data) /// AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfNeeded is called for all entries in the index /// filePlaceholders will contain only those placeholders that are not in the index. /// + /// + /// Receives the tree id of each sparse-directory entry that has the skip-worktree bit, by + /// the platform-relative folder path. Git sets the bit on every entry of a collapsed + /// folder, so a placeholder for a file in the tree of the entry is in the index with the bit. + /// private FileSystemTaskResult AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfNeeded( GitIndexEntry gitIndexEntry, - HashSet filePlaceholders) + HashSet filePlaceholders, + Dictionary sparseDirectories) { gitIndexEntry.BackgroundTask_ParsePath(); string placeholderRelativePath = gitIndexEntry.BackgroundTask_GetPlatformRelativePath(); FileSystemTaskResult result = FileSystemTaskResult.Success; + if (gitIndexEntry.IsSparseDirectory) + { + string folderRelativePath = placeholderRelativePath.TrimEnd(GVFSPlatform.GVFSPlatformConstants.PathSeparator); + if (gitIndexEntry.SkipWorktree) + { + sparseDirectories[folderRelativePath] = (byte[])gitIndexEntry.Sha.Clone(); + } + else + { + // Git cleared the skip-worktree bit of the collapsed folder, as it does for each + // entry under a modified folder. The folder path covers every file under it. The + // placeholders under the folder stay in filePlaceholders, so the caller removes + // them from the placeholder list, as it does for a file that is not in the index. + result = this.projection.AddModifiedPath(folderRelativePath, isFolder: true); + } + + return result; + } + if (!gitIndexEntry.SkipWorktree) { // A git command (e.g. 'git reset --mixed') may have cleared a file's skip worktree bit without @@ -324,6 +427,44 @@ private FileSystemTaskResult AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfN return result; } + /// + /// True if is under a sparse-directory entry, and the + /// file is in the tree of that entry. Such a file is in the index with the skip-worktree bit. + /// + /// + /// If a tree cannot be read, this returns false, so the caller treats the placeholder as + /// a file that is not in the index: GVFS keeps the file and adds it to the modified paths. + /// + private bool IsInSparseDirectoryTree( + ITracer tracer, + string placeholderPath, + Dictionary sparseDirectories, + SparseDirectoryTreeLookup treeLookup) + { + char separator = GVFSPlatform.GVFSPlatformConstants.PathSeparator; + for (int separatorIndex = placeholderPath.IndexOf(separator); + separatorIndex > 0; + separatorIndex = placeholderPath.IndexOf(separator, separatorIndex + 1)) + { + if (sparseDirectories.TryGetValue(placeholderPath.Substring(0, separatorIndex), out byte[] treeId)) + { + string[] relativePathParts = placeholderPath.Substring(separatorIndex + 1).Split(separator); + SparseDirectoryFileLookupResult lookupResult = treeLookup.FindFile(treeId, relativePathParts); + if (lookupResult == SparseDirectoryFileLookupResult.TreeUnreadable) + { + EventMetadata metadata = CreateEventMetadata(); + metadata.Add("PlaceholderPath", placeholderPath); + metadata.Add(TracingConstants.MessageKey.WarningMessage, "Cannot read a tree of a sparse directory. The placeholder is treated as a file that is not in the index."); + tracer.RelatedWarning(metadata, $"{nameof(this.IsInSparseDirectoryTree)}: Tree unreadable"); + } + + return lookupResult == SparseDirectoryFileLookupResult.Found; + } + } + + return false; + } + /// /// Takes an action on a GitIndexEntry using the index in indexStream /// @@ -335,13 +476,14 @@ private FileSystemTaskResult AddEntryToModifiedPathsAndRemoveFromPlaceholdersIfN /// /// Only the AddToModifiedFiles method because it updates the modified paths file can result /// in TryIndexAction returning a FileSystemTaskResult other than Success. All other actions result in success (or an exception in the - /// case of a corrupt index). ParseIndex throws SparseIndexNotSupportedException for a sparse - /// index, before any action receives a sparse-directory entry. + /// case of a corrupt index). See for the + /// sparse-directory entries of a sparse index. /// private FileSystemTaskResult ParseIndex( ITracer tracer, Stream indexStream, GitIndexEntry resuableParsedIndexEntry, + SparseDirectoryHandling sparseDirectoryHandling, Func entryAction) { this.indexStream = indexStream; @@ -385,7 +527,7 @@ private FileSystemTaskResult ParseIndex( // 4-bit object type // valid values in binary are 1000(regular file), 1010(symbolic link) and 1110(gitlink) - // 0100(directory) is a sparse-directory entry, which FailIfSparseDirectoryEntry rejects + // 0100(directory) is a sparse-directory entry, which HandleSparseDirectoryEntry handles // 3-bit unused // 9-bit unix permission. Only 0755 and 0644 are valid for regular files. (Legacy repos can also contain 664) // Symbolic links and gitlinks have value 0 in this field. @@ -415,8 +557,8 @@ private FileSystemTaskResult ParseIndex( break; case FileType.Directory: - // A sparse-directory entry. FailIfSparseDirectoryEntry rejects it - // with an actionable message after the parser reads its path. + // A sparse-directory entry. HandleSparseDirectoryEntry handles it + // after the parser reads its path. if (typeAndMode.Mode != 0) { throw new InvalidDataException($"Invalid file mode {typeAndMode.GetModeAsOctalString()} found for sparse directory in index"); @@ -462,7 +604,7 @@ private FileSystemTaskResult ParseIndex( this.ReadPath(resuableParsedIndexEntry, resuableParsedIndexEntry.ReplaceIndex, bytesToRead); previousPathLength = resuableParsedIndexEntry.PathLength; - this.FailIfSparseDirectoryEntry(resuableParsedIndexEntry); + this.HandleSparseDirectoryEntry(resuableParsedIndexEntry, sparseDirectoryHandling, parseMode); result = entryAction.Invoke(resuableParsedIndexEntry); if (result != FileSystemTaskResult.Success) diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.LazyUTF8String.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.LazyUTF8String.cs index 973c5077a3..c69f1f783e 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.LazyUTF8String.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.LazyUTF8String.cs @@ -265,7 +265,8 @@ public BytePool(ITracer tracer, uint indexEntryCount) public void MakeFreeSpace(int count) { - if (this.FreeIndex + count > this.Pool.Length) + // One expansion adds 15% of the pool, which can be less than a long name + while (this.FreeIndex + count > this.Pool.Length) { this.ExpandPool(); } diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SortedFolderEntries.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SortedFolderEntries.cs index ac0aa18c2f..e163f2450d 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SortedFolderEntries.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SortedFolderEntries.cs @@ -2,6 +2,7 @@ using GVFS.Common.Tracing; using System; using System.Collections.Generic; +using System.IO; namespace GVFS.Virtualization.Projection { @@ -142,6 +143,31 @@ public FolderData GetOrAddFolder( return this.InsertFolder(pathParts[partIndex], ~index, isIncluded: isIncluded); } + /// + /// Returns the child folder with the given name, or adds it if no entry has the name. + /// Name matching is the same as , + /// so two folder names that differ only in case share one folder on a case-insensitive + /// file system. The new folder gets . An existing folder + /// keeps its own inclusion state. + /// + /// A file has the name + public FolderData GetOrAddFolder(LazyUTF8String name, bool isIncluded) + { + int index = this.GetSortedEntriesIndexOfName(name); + if (index >= 0) + { + FolderData existingFolder = this.sortedEntries[index] as FolderData; + if (existingFolder == null) + { + throw new InvalidDataException($"Found a file where a folder was expected: {GitIndexParser.EscapeForDisplay(name.GetString())}"); + } + + return existingFolder; + } + + return this.InsertFolder(name, ~index, isIncluded); + } + public bool TryGetValue(LazyUTF8String name, out FolderEntryData value) { int index = this.GetSortedEntriesIndexOfName(name); diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SparseDirectoryExpander.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SparseDirectoryExpander.cs new file mode 100644 index 0000000000..83e25f9415 --- /dev/null +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.SparseDirectoryExpander.cs @@ -0,0 +1,965 @@ +using GVFS.Common; +using GVFS.Common.Git; +using GVFS.Common.Tracing; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Text; +using System.Threading; + +namespace GVFS.Virtualization.Projection +{ + public partial class GitIndexProjection + { + /// + /// The result of . + /// + internal enum SparseDirectoryFileLookupResult + { + Found, + NotFound, + TreeUnreadable, + } + + /// + /// Reads the tree objects behind the sparse-directory entries of a sparse index. + /// + /// Implementations must be safe to use from more than one thread. + internal interface IProjectionTreeReader + { + /// + /// Reads a tree from the local object store. Does not download objects. + /// + TreeEnumerationResult TryReadTree(byte[] treeId, TreeEntryVisitor visitor); + + /// + /// Downloads a tree into the local object store. + /// + /// True if the download succeeded + bool TryDownloadTree(string treeSha); + } + + /// + /// Reads trees through the libgit2 repository of the mount, and downloads a missing tree + /// through the object requestor of the mount. + /// + internal class ProjectionTreeReader : IProjectionTreeReader + { + private readonly GitRepo repository; + private readonly GVFSGitObjects gitObjects; + private readonly CancellationToken cancellationToken; + + /// Cancels a download when the mount stops + public ProjectionTreeReader(GitRepo repository, GVFSGitObjects gitObjects, CancellationToken cancellationToken) + { + this.repository = repository; + this.gitObjects = gitObjects; + this.cancellationToken = cancellationToken; + } + + public TreeEnumerationResult TryReadTree(byte[] treeId, TreeEntryVisitor visitor) + { + return this.repository.TryEnumerateTree(treeId, visitor); + } + + public bool TryDownloadTree(string treeSha) + { + if (this.gitObjects == null) + { + return false; + } + + try + { + return this.gitObjects.TryDownloadAndSaveObject(treeSha, this.cancellationToken, GVFSGitObjects.RequestSource.ProjectionBuild) + == GitObjects.DownloadAndSaveObjectResult.Success; + } + catch (OperationCanceledException) + { + return false; + } + } + } + + /// + /// Adds the files under a sparse-directory entry to the projection. The result is the same + /// projection that the full index (one entry for each file) gives. + /// + /// + /// + /// The walk is depth first and in tree order. Git tree order is the same as index order, + /// so folders and files are added in the order that the full index adds them. Thus folder + /// names that differ only in case merge as they do for a full index, and the first name wins. + /// + /// + /// A folder is added only when a file under it is added. A full index has no entry for an + /// empty tree, so an empty tree does not add a folder. + /// + /// + /// A file is not added if the file, or a folder above it, is in the modified paths. See + /// . + /// + /// + /// If a tree is not local, the expander downloads it once. If a tree is still missing, is + /// not a tree, or cannot be read, or if an entry cannot be in a full index, the expander + /// throws . The mount never serves a projection + /// that does not contain every file. + /// + /// + /// The expander is not thread safe. Use it only on the thread that builds the projection. + /// + /// + internal class SparseDirectoryExpander + { + // A full index cannot hold a longer path: GitIndexEntry has a 4096-byte path buffer. + internal const int MaxPathLength = 4095; + + private const int ShaLength = 20; + private const uint FileTypeMask = 0xF000; + private const uint TreeFileType = 0x4000; + private const byte GitPathSeparatorByte = (byte)'/'; + private const byte BackslashByte = (byte)'\\'; + + private const string MountWithoutSparseIndexSupport = + "To mount without sparse-index support, run 'git -c core.hookspath= config gvfs.auto-sparse-index false' " + + "in the 'src' folder of the enlistment. Then run 'gvfs mount', which shows the steps that expand the index."; + + private readonly ITracer tracer; + private readonly bool platformSupportsFileMode; + private readonly bool useWindowsNameRules; + private readonly SparseFolderData rootSparseFolder; + private readonly Dictionary nonDefaultFileTypesAndModes; + private readonly TreeEntryVisitor visitor; + private readonly List children = new List(); + private readonly List childFrames = new List(); + private readonly List framesWithoutFolder = new List(); + private readonly Stack stack = new Stack(); + private readonly byte[] shaBuffer = new byte[ShaLength]; + private readonly Stopwatch expansionTime = new Stopwatch(); + + private byte[] childIds = new byte[ShaLength * 64]; + private Func> getModifiedPaths; + private ModifiedPathsFilter modifiedPathsFilter; + + // Set during Expand + private FolderData rootFolderData; + private GitIndexEntry sparseDirectoryEntry; + private TreeFrame currentFrame; + + public SparseDirectoryExpander( + ITracer tracer, + IProjectionTreeReader treeReader, + SparseFolderData rootSparseFolder, + Dictionary nonDefaultFileTypesAndModes) + { + this.tracer = tracer; + this.TreeReader = treeReader; + this.platformSupportsFileMode = GVFSPlatform.Instance.FileSystem.SupportsFileMode; + this.useWindowsNameRules = GVFSPlatform.GVFSPlatformConstants.PathSeparator == '\\'; + this.rootSparseFolder = rootSparseFolder; + this.nonDefaultFileTypesAndModes = nonDefaultFileTypesAndModes; + this.visitor = this.AddChildEntry; + } + + public IProjectionTreeReader TreeReader { get; private set; } + + public int SparseDirectoryCount { get; private set; } + public int SkippedSparseDirectoryCount { get; private set; } + public int TreesRead { get; private set; } + public int TreesDownloaded { get; private set; } + public int FilesAdded { get; private set; } + public int FilesSkippedAsModified { get; private set; } + + public long ElapsedMilliseconds + { + get { return this.expansionTime.ElapsedMilliseconds; } + } + + /// + /// Resets the statistics, and sets the source of the modified paths for the next build. + /// + /// + /// Returns the modified paths, in git format. Called at most once, when the build + /// expands its first sparse-directory entry. Null if there are no modified paths. + /// + public void StartBuild(Func> getModifiedPaths) + { + this.getModifiedPaths = getModifiedPaths; + this.modifiedPathsFilter = null; + this.SparseDirectoryCount = 0; + this.SkippedSparseDirectoryCount = 0; + this.TreesRead = 0; + this.TreesDownloaded = 0; + this.FilesAdded = 0; + this.FilesSkippedAsModified = 0; + this.expansionTime.Reset(); + } + + public void AddMetadata(EventMetadata metadata) + { + metadata.Add("SparseDirectoryCount", this.SparseDirectoryCount); + metadata.Add("SkippedSparseDirectoryCount", this.SkippedSparseDirectoryCount); + metadata.Add("SparseTreesRead", this.TreesRead); + metadata.Add("SparseTreesDownloaded", this.TreesDownloaded); + metadata.Add("SparseFilesAdded", this.FilesAdded); + metadata.Add("SparseFilesSkippedAsModified", this.FilesSkippedAsModified); + metadata.Add("SparseExpansionMilliseconds", this.ElapsedMilliseconds); + } + + /// + /// Adds the files under a sparse-directory entry to the projection. + /// + /// The root folder of the projection + /// + /// The sparse-directory entry. Its path parts must contain the path of the collapsed + /// folder (see ). + /// + public void Expand(FolderData rootFolderData, GitIndexEntry entry) + { + this.expansionTime.Start(); + try + { + this.SparseDirectoryCount++; + + if (this.modifiedPathsFilter == null) + { + this.modifiedPathsFilter = ModifiedPathsFilter.Create(this.getModifiedPaths?.Invoke()); + } + + bool trackPaths = this.platformSupportsFileMode || !this.modifiedPathsFilter.IsEmpty; + string rootGitPath = trackPaths ? entry.BuildingProjection_GetGitRelativePath() : null; + bool checkModifiedPaths = false; + if (!this.modifiedPathsFilter.IsEmpty) + { + if (this.modifiedPathsFilter.ContainsFolderOrParentFolder(rootGitPath)) + { + this.SkippedSparseDirectoryCount++; + return; + } + + checkModifiedPaths = this.modifiedPathsFilter.HasEntriesUnder(rootGitPath); + } + + byte[] rootTreeId = new byte[ShaLength]; + Buffer.BlockCopy(entry.Sha, 0, rootTreeId, 0, ShaLength); + + this.rootFolderData = rootFolderData; + this.sparseDirectoryEntry = entry; + this.stack.Clear(); + this.stack.Push(new TreeFrame( + parent: null, + name: entry.BuildingProjection_GetChildName(), + treeId: rootTreeId, + pathLength: entry.PathLength - 1, + inclusion: this.GetSparseDirectoryInclusion(entry), + gitPath: this.NeedsGitPath(checkModifiedPaths) ? rootGitPath : null, + checkModifiedPaths: checkModifiedPaths)); + + while (this.stack.Count > 0) + { + this.ExpandTree(this.stack.Pop()); + } + } + finally + { + this.rootFolderData = null; + this.sparseDirectoryEntry = null; + this.currentFrame = null; + this.stack.Clear(); + this.childFrames.Clear(); + this.framesWithoutFolder.Clear(); + this.children.Clear(); + this.expansionTime.Stop(); + } + } + + /// + /// Replaces the tree reader. For unit tests only. + /// + internal void SetTreeReaderForTests(IProjectionTreeReader reader) + { + this.TreeReader = reader; + } + + private static string GetChildGitPath(string parentGitPath, LazyUTF8String name) + { + return parentGitPath + GVFSConstants.GitPathSeparatorString + name.GetString(); + } + + /// + /// True if a tree entry name is ".git" for git on Windows (core.protectNTFS): the name + /// with trailing dots and spaces removed is ".git", or the name is the short name "git~1". + /// + private static bool IsWindowsDotGitName(string name) + { + return name.TrimEnd('.', ' ').Equals(GVFSConstants.DotGit.Root, StringComparison.OrdinalIgnoreCase) || + name.Equals("git~1", StringComparison.OrdinalIgnoreCase); + } + + /// + /// True if a folder needs its git path: to match modified paths under it, or to + /// record the file modes of its files. + /// + private bool NeedsGitPath(bool checkModifiedPaths) + { + return checkModifiedPaths || this.platformSupportsFileMode; + } + + private void ExpandTree(TreeFrame frame) + { + this.ReadTree(frame); + + // Add the children in tree order. Push the child trees in reverse order, so that + // the walk reads them in tree order. + this.childFrames.Clear(); + for (int i = 0; i < this.children.Count; i++) + { + ChildEntry child = this.children[i]; + int childPathLength = frame.PathLength + 1 + child.NameLength; + if (childPathLength > MaxPathLength) + { + this.ThrowExpansionException( + frame, + folder => $"The folder '{folder}' in the sparse index has a path that is longer than {MaxPathLength} bytes. Git cannot add this path to an index."); + } + + string childGitPath = frame.GitPath != null ? GetChildGitPath(frame.GitPath, child.Name) : null; + bool isTree = (child.FileMode & FileTypeMask) == TreeFileType; + + if (isTree) + { + bool checkModifiedPaths = false; + if (frame.CheckModifiedPaths) + { + if (this.modifiedPathsFilter.ContainsFolder(childGitPath)) + { + continue; + } + + checkModifiedPaths = this.modifiedPathsFilter.HasEntriesUnder(childGitPath); + } + + byte[] childTreeId = new byte[ShaLength]; + Buffer.BlockCopy(this.childIds, i * ShaLength, childTreeId, 0, ShaLength); + this.childFrames.Add(new TreeFrame( + frame, + child.Name, + childTreeId, + childPathLength, + this.GetChildInclusion(frame.Inclusion, child.Name), + this.NeedsGitPath(checkModifiedPaths) ? childGitPath : null, + checkModifiedPaths)); + } + else + { + if (frame.CheckModifiedPaths && this.modifiedPathsFilter.ContainsFile(childGitPath)) + { + this.FilesSkippedAsModified++; + continue; + } + + FileTypeAndMode typeAndMode = default(FileTypeAndMode); + if (this.platformSupportsFileMode) + { + typeAndMode = new FileTypeAndMode((ushort)child.FileMode); + this.ValidateFileTypeAndMode(frame, typeAndMode, childGitPath); + } + + Buffer.BlockCopy(this.childIds, i * ShaLength, this.shaBuffer, 0, ShaLength); + this.GetOrAddFolder(frame).AddChildFile(child.Name, this.shaBuffer); + this.FilesAdded++; + + if (this.platformSupportsFileMode && + (typeAndMode.Type != FileType.Regular || typeAndMode.Mode != FileMode644)) + { + this.nonDefaultFileTypesAndModes.Add(childGitPath, typeAndMode); + } + } + } + + for (int i = this.childFrames.Count - 1; i >= 0; i--) + { + this.stack.Push(this.childFrames[i]); + } + } + + /// + /// Reads the entries of the tree of into . + /// + private void ReadTree(TreeFrame frame) + { + this.currentFrame = frame; + this.children.Clear(); + TreeEnumerationResult result = this.TreeReader.TryReadTree(frame.TreeId, this.visitor); + + string treeSha = null; + if (result == TreeEnumerationResult.MissingTree) + { + treeSha = SHA1Util.HexStringFromBytes(frame.TreeId); + if (this.TreeReader.TryDownloadTree(treeSha)) + { + this.TreesDownloaded++; + this.children.Clear(); + result = this.TreeReader.TryReadTree(frame.TreeId, this.visitor); + } + } + + if (result != TreeEnumerationResult.Success) + { + this.children.Clear(); + treeSha = treeSha ?? SHA1Util.HexStringFromBytes(frame.TreeId); + string folderPath = this.GetFolderPathForDisplay(frame); + + EventMetadata metadata = CreateEventMetadata(); + metadata.Add("TreeSha", treeSha); + metadata.Add("Result", result.ToString()); + metadata.Add("FolderPath", folderPath); + this.tracer.RelatedError(metadata, $"{nameof(SparseDirectoryExpander)}: Failed to read the tree of a sparse directory"); + + string nextStep = result == TreeEnumerationResult.MissingTree || result == TreeEnumerationResult.RepositoryUnavailable + ? "Make sure that the network connection works, and run 'gvfs mount' again. If the problem continues: " + : string.Empty; + throw new SparseIndexExpansionException( + $"Cannot read tree {treeSha} for the folder '{GitIndexParser.EscapeForDisplay(folderPath)}' in the sparse index ({result}). " + + "VFS for Git cannot project the files in this folder. " + nextStep + MountWithoutSparseIndexSupport); + } + + this.TreesRead++; + } + + /// + /// The visitor for . Copies an entry into + /// . The projection does not change until the read succeeds. + /// + private unsafe void AddChildEntry(ReadOnlySpan name, ReadOnlySpan objectId, uint fileMode) + { + if (objectId.Length != ShaLength) + { + int idLength = objectId.Length; + this.ThrowExpansionException(this.currentFrame, folder => $"The folder '{folder}' in the sparse index has a tree entry with a {idLength}-byte object id."); + } + + this.ValidateName(name); + + int idOffset = this.children.Count * ShaLength; + if (idOffset + ShaLength > this.childIds.Length) + { + Array.Resize(ref this.childIds, this.childIds.Length * 2); + } + + objectId.CopyTo(new Span(this.childIds, idOffset, ShaLength)); + + LazyUTF8String childName; + fixed (byte* namePtr = name) + { + childName = LazyUTF8String.FromByteArray(namePtr, name.Length); + } + + this.children.Add(new ChildEntry(childName, name.Length, fileMode)); + } + + /// + /// Throws if a tree entry name cannot be a path component of a full index. Git does not + /// add such a path to an index, so a full index cannot project it. + /// + private void ValidateName(ReadOnlySpan name) + { + bool isValid = name.Length > 0; + for (int i = 0; isValid && i < name.Length; i++) + { + byte b = name[i]; + isValid = b != GitPathSeparatorByte && b != 0 && !(this.useWindowsNameRules && b == BackslashByte); + } + + string nameString = null; + if (isValid && !name.SequenceEqual("."u8) && !name.SequenceEqual(".."u8)) + { + nameString = Encoding.UTF8.GetString(name); + isValid = !nameString.Equals(GVFSConstants.DotGit.Root, StringComparison.OrdinalIgnoreCase) && + !(this.useWindowsNameRules && IsWindowsDotGitName(nameString)); + } + else + { + isValid = false; + } + + if (!isValid) + { + string invalidName = nameString ?? Encoding.UTF8.GetString(name); + this.ThrowExpansionException( + this.currentFrame, + folder => $"The folder '{folder}' in the sparse index has a tree entry with the name '{GitIndexParser.EscapeForDisplay(invalidName)}'. Git cannot add this name to an index."); + } + } + + /// + /// Throws if a file type and mode cannot be in a full index. These are the checks that + /// GitIndexParser.ParseIndex does for an entry of a full index. + /// + private void ValidateFileTypeAndMode(TreeFrame frame, FileTypeAndMode typeAndMode, string gitPath) + { + bool isValid; + switch (typeAndMode.Type) + { + case FileType.Regular: + isValid = typeAndMode.Mode == FileMode755 || typeAndMode.Mode == FileMode644 || typeAndMode.Mode == FileMode664; + break; + + case FileType.SymLink: + case FileType.GitLink: + isValid = typeAndMode.Mode == 0; + break; + + default: + isValid = false; + break; + } + + if (!isValid) + { + this.ThrowExpansionException( + frame, + folder => $"The file '{GitIndexParser.EscapeForDisplay(gitPath)}' in the folder '{folder}' of the sparse index has the invalid type {typeAndMode.Type} and mode {typeAndMode.GetModeAsOctalString()}."); + } + } + + /// + /// Logs and throws . + /// + /// Builds the message from the escaped folder path of + private void ThrowExpansionException(TreeFrame frame, Func buildMessage) + { + string message = buildMessage(GitIndexParser.EscapeForDisplay(this.GetFolderPathForDisplay(frame))) + + " VFS for Git cannot project the files in this folder. " + MountWithoutSparseIndexSupport; + + EventMetadata metadata = CreateEventMetadata(); + metadata.Add(TracingConstants.MessageKey.ErrorMessage, message); + this.tracer.RelatedError(metadata, $"{nameof(SparseDirectoryExpander)}: Invalid tree in a sparse directory"); + + throw new SparseIndexExpansionException(message); + } + + /// + /// Returns the folder of . Adds the folder, and the folders + /// above it, to the projection if they are not there. + /// + private FolderData GetOrAddFolder(TreeFrame frame) + { + if (frame.Folder != null) + { + return frame.Folder; + } + + // Find the frames above this one that have no folder yet, without recursion + this.framesWithoutFolder.Clear(); + TreeFrame current = frame; + while (current != null && current.Folder == null) + { + this.framesWithoutFolder.Add(current); + current = current.Parent; + } + + FolderData folder = current?.Folder; + for (int i = this.framesWithoutFolder.Count - 1; i >= 0; i--) + { + TreeFrame frameToAdd = this.framesWithoutFolder[i]; + folder = frameToAdd.Parent == null + ? this.GetOrAddSparseDirectoryFolder() + : folder.ChildEntries.GetOrAddFolder(frameToAdd.Name, frameToAdd.Inclusion.Included); + frameToAdd.Folder = folder; + } + + this.framesWithoutFolder.Clear(); + return frame.Folder; + } + + /// + /// Adds the folders of the sparse-directory entry path to the projection, as + /// AddFileToTree adds the folders of a file path. + /// + private FolderData GetOrAddSparseDirectoryFolder() + { + GitIndexEntry entry = this.sparseDirectoryEntry; + FolderData folder = this.rootFolderData; + for (int pathIndex = 0; pathIndex < entry.BuildingProjection_NumParts; ++pathIndex) + { + folder = folder.ChildEntries.GetOrAddFolder(entry.BuildingProjection_PathParts, pathIndex, folder.IsIncluded, this.rootSparseFolder); + } + + return folder; + } + + private string GetFolderPathForDisplay(TreeFrame frame) + { + if (frame.GitPath != null) + { + return frame.GitPath; + } + + List names = new List(); + for (TreeFrame current = frame; current.Parent != null; current = current.Parent) + { + names.Add(current.Name.GetString()); + } + + names.Add(this.sparseDirectoryEntry.BuildingProjection_GetGitRelativePath()); + names.Reverse(); + return string.Join(GVFSConstants.GitPathSeparatorString, names); + } + + /// + /// Computes the inclusion of the collapsed folder in the gvfs sparse folders, as + /// does. + /// + private FrameInclusion GetSparseDirectoryInclusion(GitIndexEntry entry) + { + if (this.rootSparseFolder.Children.Count == 0) + { + return FrameInclusion.AllIncluded; + } + + SparseFolderData node = this.rootSparseFolder; + for (int i = 0; i < entry.BuildingProjection_NumParts; i++) + { + if (node.IsRecursive) + { + return FrameInclusion.AllIncluded; + } + + if (!node.Children.TryGetValue(entry.BuildingProjection_PathParts[i].GetString(), out node)) + { + return FrameInclusion.Excluded; + } + } + + return new FrameInclusion(included: true, recursive: node.IsRecursive, node: node); + } + + /// + /// Computes the inclusion of a child folder from the inclusion of its parent folder. The + /// result is the same as the walk from the root in + /// . + /// + private FrameInclusion GetChildInclusion(FrameInclusion parent, LazyUTF8String childName) + { + if (this.rootSparseFolder.Children.Count == 0 || (parent.Included && parent.Recursive)) + { + return FrameInclusion.AllIncluded; + } + + if (!parent.Included) + { + return FrameInclusion.Excluded; + } + + if (parent.Node.Children.TryGetValue(childName.GetString(), out SparseFolderData childNode)) + { + return new FrameInclusion(included: true, recursive: childNode.IsRecursive, node: childNode); + } + + return FrameInclusion.Excluded; + } + + private readonly struct ChildEntry + { + public ChildEntry(LazyUTF8String name, int nameLength, uint fileMode) + { + this.Name = name; + this.NameLength = nameLength; + this.FileMode = fileMode; + } + + public LazyUTF8String Name { get; } + + // The length of the name in UTF-8 bytes + public int NameLength { get; } + public uint FileMode { get; } + } + + private class TreeFrame + { + public TreeFrame(TreeFrame parent, LazyUTF8String name, byte[] treeId, int pathLength, FrameInclusion inclusion, string gitPath, bool checkModifiedPaths) + { + this.Parent = parent; + this.Name = name; + this.TreeId = treeId; + this.PathLength = pathLength; + this.Inclusion = inclusion; + this.GitPath = gitPath; + this.CheckModifiedPaths = checkModifiedPaths; + } + + public TreeFrame Parent { get; } + public LazyUTF8String Name { get; } + public byte[] TreeId { get; } + + // The length of the git path of the folder in UTF-8 bytes + public int PathLength { get; } + public FrameInclusion Inclusion { get; } + + // The git path of the folder. Null unless the expander needs paths for this subtree. + public string GitPath { get; } + + // True if a modified path is under this folder + public bool CheckModifiedPaths { get; } + + // Null until the expander adds a file under this folder + public FolderData Folder { get; set; } + } + } + + /// + /// Finds whether a file is in the tree of a sparse-directory entry. The placeholder scan + /// uses it to decide if a placeholder under a collapsed folder is in the index. + /// + /// + /// Name matches use the path comparer, as the placeholder scan does for a full index. The + /// lookup caches each tree that it reads. Use one instance for one scan, on one thread. + /// + internal class SparseDirectoryTreeLookup + { + private readonly IProjectionTreeReader treeReader; + private readonly StringComparer pathComparer = GVFSPlatform.Instance.Constants.PathComparer; + private readonly Dictionary> trees = new Dictionary>(StringComparer.OrdinalIgnoreCase); + + public SparseDirectoryTreeLookup(IProjectionTreeReader treeReader) + { + this.treeReader = treeReader; + } + + /// The tree of the sparse-directory entry + /// The path of the file under the collapsed folder, one name for each part + public SparseDirectoryFileLookupResult FindFile(byte[] treeId, string[] relativePathParts) + { + return this.FindFile(treeId, relativePathParts, 0); + } + + private SparseDirectoryFileLookupResult FindFile(byte[] treeId, string[] parts, int partIndex) + { + List children = this.ReadTree(treeId); + if (children == null) + { + return SparseDirectoryFileLookupResult.TreeUnreadable; + } + + bool isLastPart = partIndex == parts.Length - 1; + SparseDirectoryFileLookupResult result = SparseDirectoryFileLookupResult.NotFound; + foreach (TreeChild child in children) + { + if (child.IsTree == isLastPart || !this.pathComparer.Equals(child.Name, parts[partIndex])) + { + continue; + } + + if (isLastPart) + { + return SparseDirectoryFileLookupResult.Found; + } + + // Folder names that differ only in case are one folder in the projection, so + // look in each matching tree. + SparseDirectoryFileLookupResult childResult = this.FindFile(child.Id, parts, partIndex + 1); + if (childResult == SparseDirectoryFileLookupResult.Found) + { + return childResult; + } + + if (childResult == SparseDirectoryFileLookupResult.TreeUnreadable) + { + result = childResult; + } + } + + return result; + } + + private List ReadTree(byte[] treeId) + { + string treeSha = SHA1Util.HexStringFromBytes(treeId); + if (this.trees.TryGetValue(treeSha, out List cached)) + { + return cached; + } + + List children = new List(); + TreeEntryVisitor visitor = (name, objectId, fileMode) => + children.Add(new TreeChild(Encoding.UTF8.GetString(name), objectId.ToArray(), (fileMode & 0xF000) == 0x4000)); + + TreeEnumerationResult result = this.treeReader.TryReadTree(treeId, visitor); + if (result == TreeEnumerationResult.MissingTree && this.treeReader.TryDownloadTree(treeSha)) + { + children.Clear(); + result = this.treeReader.TryReadTree(treeId, visitor); + } + + if (result != TreeEnumerationResult.Success) + { + return null; + } + + this.trees.Add(treeSha, children); + return children; + } + + private readonly struct TreeChild + { + public TreeChild(string name, byte[] id, bool isTree) + { + this.Name = name; + this.Id = id; + this.IsTree = isTree; + } + + public string Name { get; } + public byte[] Id { get; } + public bool IsTree { get; } + } + } + + /// + /// The inclusion of a folder in the gvfs sparse folders (), + /// as the expander walks down a tree. + /// + internal readonly struct FrameInclusion + { + public static readonly FrameInclusion AllIncluded = new FrameInclusion(included: true, recursive: true, node: null); + public static readonly FrameInclusion Excluded = new FrameInclusion(included: false, recursive: false, node: null); + + public FrameInclusion(bool included, bool recursive, SparseFolderData node) + { + this.Included = included; + this.Recursive = recursive; + this.Node = node; + } + + /// True if the folder is included (). + public bool Included { get; } + + /// True if every folder under this folder is included. + public bool Recursive { get; } + + /// The sparse folder node that matches this folder. Null if Recursive or not Included. + public SparseFolderData Node { get; } + } + + /// + /// A snapshot of the modified paths, for the expansion of a sparse directory. + /// + /// + /// The virtual file system hook reports the modified paths to git. For a full index, git + /// clears the skip-worktree bit of each entry whose path is a modified file path, and of + /// each entry under a modified folder path ("folder/"). Matches ignore case on a + /// case-insensitive file system. The projection does not contain an entry without the + /// skip-worktree bit. The filter gives the same result for the files under a sparse directory. + /// + internal class ModifiedPathsFilter + { + private static readonly ModifiedPathsFilter Empty = new ModifiedPathsFilter(); + + private readonly HashSet files; + private readonly HashSet folders; + + // Every entry, sorted with the path comparer. The entries under a folder are contiguous. + private readonly List sortedEntries; + private readonly StringComparison pathComparison; + + private ModifiedPathsFilter() + { + this.IsEmpty = true; + } + + private ModifiedPathsFilter(IEnumerable modifiedPaths) + { + StringComparer comparer = GVFSPlatform.Instance.Constants.PathComparer; + this.pathComparison = GVFSPlatform.Instance.Constants.PathComparison; + this.files = new HashSet(comparer); + this.folders = new HashSet(comparer); + this.sortedEntries = new List(); + + foreach (string path in modifiedPaths) + { + if (string.IsNullOrEmpty(path)) + { + continue; + } + + this.sortedEntries.Add(path); + if (path[path.Length - 1] == GVFSConstants.GitPathSeparator) + { + this.folders.Add(path.Substring(0, path.Length - 1)); + } + else + { + this.files.Add(path); + } + } + + this.sortedEntries.Sort(comparer); + this.IsEmpty = this.sortedEntries.Count == 0; + } + + public bool IsEmpty { get; } + + /// Modified paths in git format. A folder path ends in '/'. Can be null. + public static ModifiedPathsFilter Create(IEnumerable modifiedPaths) + { + return modifiedPaths == null ? Empty : new ModifiedPathsFilter(modifiedPaths); + } + + /// True if is a modified file path. + public bool ContainsFile(string gitPath) + { + return !this.IsEmpty && this.files.Contains(gitPath); + } + + /// True if , without a trailing '/', is a modified folder path. + public bool ContainsFolder(string gitPath) + { + return !this.IsEmpty && this.folders.Contains(gitPath); + } + + /// + /// True if , or a folder above it, is a modified folder path. + /// + public bool ContainsFolderOrParentFolder(string gitPath) + { + if (this.IsEmpty || this.folders.Count == 0) + { + return false; + } + + for (int separatorIndex = gitPath.IndexOf(GVFSConstants.GitPathSeparator); + separatorIndex > 0; + separatorIndex = gitPath.IndexOf(GVFSConstants.GitPathSeparator, separatorIndex + 1)) + { + if (this.folders.Contains(gitPath.Substring(0, separatorIndex))) + { + return true; + } + } + + return this.folders.Contains(gitPath); + } + + /// + /// True if a modified path is under the folder . + /// + public bool HasEntriesUnder(string folderGitPath) + { + if (this.IsEmpty) + { + return false; + } + + string prefix = folderGitPath + GVFSConstants.GitPathSeparatorString; + int index = this.sortedEntries.BinarySearch(prefix, GVFSPlatform.Instance.Constants.PathComparer); + if (index < 0) + { + index = ~index; + } + + return index < this.sortedEntries.Count && this.sortedEntries[index].StartsWith(prefix, this.pathComparison); + } + } + } +} diff --git a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs index 66239dedd4..f469a24b92 100644 --- a/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs +++ b/GVFS/GVFS.Virtualization/Projection/GitIndexProjection.cs @@ -64,6 +64,19 @@ public partial class GitIndexProjection : IDisposable, IProfilerOnlyIndexProject private ReaderWriterLockSlim projectionReadWriteLock; private ManualResetEventSlim projectionParseComplete; + // Not null when gvfs.auto-sparse-index is true: the projection expands the sparse-directory + // entries of a sparse index. Null when it is false: the projection rejects a sparse index. + private SparseDirectoryExpander sparseDirectoryExpander; + + // True when the last projection build expanded at least one sparse-directory entry + private volatile bool projectionHasExpandedSparseDirectories; + + // Cancels tree downloads of the projection build when the mount stops + private CancellationTokenSource shutdownTokenSource = new CancellationTokenSource(); + + // True when a caller without a repository (gvfs repair) validates a sparse index + private bool acceptSparseDirectoriesWithoutExpansion; + private volatile bool projectionInvalid; private long projectionGeneration; @@ -117,6 +130,16 @@ public GitIndexProjection( this.rootSparseFolder = new SparseFolderData(); this.ClearProjectionCaches(); + if (this.context.Repository != null && + this.context.Repository.GetConfigBoolOrDefault(GVFSConstants.GitConfig.AutoSparseIndex, GVFSConstants.GitConfig.AutoSparseIndexDefault)) + { + this.sparseDirectoryExpander = new SparseDirectoryExpander( + this.context.Tracer, + new ProjectionTreeReader(this.context.Repository, this.gitObjects, this.shutdownTokenSource.Token), + this.rootSparseFolder, + this.nonDefaultFileTypesAndModes); + } + LocalGVFSConfig config = new LocalGVFSConfig(); if (config.TryGetConfig(GVFSConstants.LocalGVFSConfig.USNJournalUpdates, out string value, out string error)) { @@ -155,11 +178,14 @@ public enum PathSparseState Excluded, } - public static void ReadIndex(ITracer tracer, string indexPath) + public static void ReadIndex(ITracer tracer, string indexPath, bool acceptSparseDirectories = false) { using (FileStream indexStream = new FileStream(indexPath, FileMode.Open, FileAccess.ReadWrite, FileShare.Read, IndexFileStreamBufferSize)) { - GitIndexParser.ValidateIndex(tracer, indexStream); + GitIndexParser.ValidateIndex( + tracer, + indexStream, + acceptSparseDirectories ? GitIndexParser.SparseDirectoryHandling.Accept : GitIndexParser.SparseDirectoryHandling.Reject); } } @@ -193,6 +219,25 @@ public void BuildProjectionFromPath(ITracer tracer, string indexPath) } } + /// + /// Parses the index into a projection, as + /// does. If is true and sparse-index expansion is + /// off for this projection, the method validates each sparse-directory entry, but it does + /// not add the files under it. Use the result only to check that the index can be parsed. + /// + public void BuildProjectionFromPath(ITracer tracer, string indexPath, bool acceptSparseDirectories) + { + this.acceptSparseDirectoriesWithoutExpansion = acceptSparseDirectories; + try + { + this.BuildProjectionFromPath(tracer, indexPath); + } + finally + { + this.acceptSparseDirectoriesWithoutExpansion = false; + } + } + public virtual void Initialize(BackgroundFileSystemTaskRunner backgroundFileSystemTaskRunner) { if (!File.Exists(this.indexPath)) @@ -243,6 +288,7 @@ public virtual void Initialize(BackgroundFileSystemTaskRunner backgroundFileSyst public virtual void Shutdown() { this.isStopping = true; + this.shutdownTokenSource?.Cancel(); this.wakeUpIndexParsingThread.Set(); this.indexParsingThread.Wait(); } @@ -359,6 +405,30 @@ public virtual int GetProjectedFolderCount() } } + /// + /// Get the number of files in the projection, if the projection expanded the + /// sparse-directory entries of a sparse index. A sparse index has one entry for each + /// collapsed folder, so its entry count is not the number of files. + /// + /// The number of files, or -1 if the projection came from a full index + public virtual int GetProjectedFileCountIfSparseIndex() + { + if (!this.projectionHasExpandedSparseDirectories) + { + return -1; + } + + this.projectionReadWriteLock.EnterReadLock(); + try + { + return this.projectionHasExpandedSparseDirectories ? this.rootFolderData.GetRecursiveFileCount() : -1; + } + finally + { + this.projectionReadWriteLock.ExitReadLock(); + } + } + /// /// Count unique directories by parsing the index file directly. /// This is a fallback for when the in-memory projection is not available @@ -787,6 +857,12 @@ protected virtual void Dispose(bool disposing) // resources, so it is not disposed here. this.indexParsingThread = null; } + + if (this.shutdownTokenSource != null) + { + this.shutdownTokenSource.Dispose(); + this.shutdownTokenSource = null; + } } } @@ -874,7 +950,12 @@ private void AddItemFromIndexEntry(GitIndexEntry indexEntry) private FileSystemTaskResult AddModifiedPath(string path) { - bool wasAdded = this.modifiedPaths.TryAdd(path, isFolder: false, isRetryable: out bool isRetryable); + return this.AddModifiedPath(path, isFolder: false); + } + + private FileSystemTaskResult AddModifiedPath(string path, bool isFolder) + { + bool wasAdded = this.modifiedPaths.TryAdd(path, isFolder, isRetryable: out bool isRetryable); if (!wasAdded) { return isRetryable ? FileSystemTaskResult.RetryableError : FileSystemTaskResult.FatalError; @@ -883,6 +964,56 @@ private FileSystemTaskResult AddModifiedPath(string path) return FileSystemTaskResult.Success; } + /// + /// What the index parser does with a sparse-directory entry, for this projection. + /// + private GitIndexParser.SparseDirectoryHandling ProjectionSparseDirectoryHandling + { + get + { + return this.sparseDirectoryExpander != null || this.acceptSparseDirectoriesWithoutExpansion + ? GitIndexParser.SparseDirectoryHandling.Accept + : GitIndexParser.SparseDirectoryHandling.Reject; + } + } + + /// + /// Enables the expansion of sparse-directory entries, with the given tree reader. For unit tests only. + /// + internal void EnableSparseIndexExpansionForTests(IProjectionTreeReader treeReader) + { + if (this.sparseDirectoryExpander == null) + { + this.sparseDirectoryExpander = new SparseDirectoryExpander(this.context.Tracer, treeReader, this.rootSparseFolder, this.nonDefaultFileTypesAndModes); + } + else + { + this.sparseDirectoryExpander.SetTreeReaderForTests(treeReader); + } + } + + /// + /// Adds the files under a sparse-directory entry to the projection. + /// + private void AddSparseDirectoryEntry(GitIndexEntry indexEntry) + { + // The parse of the collapsed folder path does not use the same-parent state, and the + // next entry must not use the folder of this entry as its parent. + indexEntry.ClearLastParent(); + if (this.sparseDirectoryExpander != null) + { + indexEntry.BuildingProjection_ParseSparseDirectoryPath(); + this.sparseDirectoryExpander.Expand(this.rootFolderData, indexEntry); + } + + indexEntry.ClearLastParent(); + } + + private IEnumerable GetModifiedPathsForExpansion() + { + return this.modifiedPaths?.GetAllModifiedPaths(); + } + private void ClearProjectionCaches() { SortedFolderEntries.FreePool(); @@ -1285,6 +1416,13 @@ private void ParseIndexThreadMain() } } } + catch (SparseIndexExpansionException e) when (this.isStopping) + { + // A tree download that the shutdown canceled fails the build. BuildProjection + // already marked the projection invalid, so the next mount builds it again. + EventMetadata metadata = CreateEventMetadata(e); + this.context.Tracer.RelatedWarning(metadata, "ParseIndexThreadMain: Projection build stopped by shutdown"); + } catch (Exception e) { this.LogErrorAndExit("ParseIndexThreadMain caught unhandled exception, exiting process", e); @@ -1996,6 +2134,7 @@ private void BuildProjection() catch (Exception e) { EventMetadata metadata = CreateEventMetadata(e); + this.sparseDirectoryExpander?.AddMetadata(metadata); this.context.Tracer.RelatedWarning(metadata, $"{nameof(this.BuildProjection)}: Exception thrown by {nameof(GitIndexParser.RebuildProjection)}"); this.SetProjectionInvalid(true); @@ -2011,6 +2150,7 @@ private void BuildProjection() poolMetadata.Add($"{nameof(SortedFolderEntries)}_{nameof(SortedFolderEntries.FilePoolSize)}", SortedFolderEntries.FilePoolSize()); poolMetadata.Add($"{nameof(LazyUTF8String)}_{nameof(LazyUTF8String.StringPoolSize)}", LazyUTF8String.StringPoolSize()); poolMetadata.Add($"{nameof(LazyUTF8String)}_{nameof(LazyUTF8String.BytePoolSize)}", LazyUTF8String.BytePoolSize()); + this.sparseDirectoryExpander?.AddMetadata(poolMetadata); TimeSpan duration = tracer.Stop(poolMetadata); this.context.Repository.GVFSLock.Stats.RecordParseGitIndex((long)duration.TotalMilliseconds); } diff --git a/GVFS/GVFS.Virtualization/Projection/Readme.md b/GVFS/GVFS.Virtualization/Projection/Readme.md index eab35bbf8d..12ca2784c0 100644 --- a/GVFS/GVFS.Virtualization/Projection/Readme.md +++ b/GVFS/GVFS.Virtualization/Projection/Readme.md @@ -146,6 +146,19 @@ Class used to store the data from the index about a single entry. There is only Class that is responsible for parsing the git index based of version 4. Please see [`index-format.txt`](https://github.com/microsoft/git/blob/f5992bb185757a1654ce31424611b4d05bda3400/Documentation/technical/index-format.txt) for detailed information of this format. This is used to both validate the index and build the projection. It currently ignores all index extensions and is only for getting the paths and building the tree using the `FolderData` and `FileData` classes. The index is read in chunks of 512K which gave the best performance. +### `SparseDirectoryExpander` + +A sparse index (git `index.sparse`) stores a folder outside the sparse-checkout cone as one sparse-directory entry. The entry has mode `040000`, a path that ends in `/`, and the id of the tree of the folder. By default (`gvfs.auto-sparse-index` is false), `GitIndexParser` rejects a sparse index. When `gvfs.auto-sparse-index` is true, `SparseDirectoryExpander` reads the tree behind each sparse-directory entry through libgit2, and adds every file under it to the projection. The projection is then the same as the projection of the full index: + +- Folders and files are added in index order, so folder names that differ only in case merge as they do for a full index. +- A folder is added only when a file is added under it. A full index has no entry for an empty tree. +- A file is not added if the file, or a folder above it, is in the modified paths. For a full index, git clears the skip-worktree bit of those entries, and the projection does not contain them. +- If a tree is not in the local object store, the expander downloads it once. If the tree is still missing, is not a tree, or cannot be read, or if an entry cannot be in a full index, the projection build fails with `SparseIndexExpansionException`. The mount never serves a projection with missing files. + +The background placeholder scan treats a placeholder under a sparse-directory entry as an index entry only if the file is in the tree of that entry. + +The expansion reads every tree under every sparse-directory entry on each projection build. + ## Other classes ### `ProjectedFileInfo` diff --git a/GVFS/GVFS.Virtualization/Projection/SparseIndexExpansionException.cs b/GVFS/GVFS.Virtualization/Projection/SparseIndexExpansionException.cs new file mode 100644 index 0000000000..b5b91c6531 --- /dev/null +++ b/GVFS/GVFS.Virtualization/Projection/SparseIndexExpansionException.cs @@ -0,0 +1,20 @@ +using System; + +namespace GVFS.Virtualization.Projection +{ + /// + /// The projection cannot expand a sparse-directory entry of a sparse index + /// (gvfs.auto-sparse-index is true). The message tells the user what to do next. + /// + /// + /// Do not derive from IOException. The index parsing thread retries an IOException, and + /// a retry under the projection write lock does not fix a tree that cannot be read. + /// + public class SparseIndexExpansionException : Exception + { + public SparseIndexExpansionException(string message) + : base(message) + { + } + } +} diff --git a/GVFS/GVFS.Virtualization/Projection/SparseIndexNotSupportedException.cs b/GVFS/GVFS.Virtualization/Projection/SparseIndexNotSupportedException.cs index 575a25c8f3..9f0193cb98 100644 --- a/GVFS/GVFS.Virtualization/Projection/SparseIndexNotSupportedException.cs +++ b/GVFS/GVFS.Virtualization/Projection/SparseIndexNotSupportedException.cs @@ -3,7 +3,8 @@ namespace GVFS.Virtualization.Projection { /// - /// The git index is a sparse index (git index.sparse), and the projection cannot use it. + /// The git index is a sparse index (git index.sparse), and sparse-index support + /// (gvfs.auto-sparse-index) is off, so the projection cannot use the index. /// The message tells the user how to expand the index. /// /// diff --git a/GVFS/GVFS/RepairJobs/RepairJob.cs b/GVFS/GVFS/RepairJobs/RepairJob.cs index 1d1ff4da39..b712a1f641 100644 --- a/GVFS/GVFS/RepairJobs/RepairJob.cs +++ b/GVFS/GVFS/RepairJobs/RepairJob.cs @@ -1,5 +1,6 @@ using GVFS.Common; using GVFS.Common.FileSystem; +using GVFS.Common.Git; using GVFS.Common.Tracing; using GVFS.Virtualization.Projection; using System; @@ -112,6 +113,12 @@ protected bool TryDeleteFolder(string filePath) protected IssueType TryParseIndex(string path, List messages) { GVFSContext context = new GVFSContext(this.Tracer, null, null, this.Enlistment); + bool sparseIndexEnabled = LibGit2Repo.GetConfigBoolOrDefault( + this.Tracer, + this.Enlistment.WorkingDirectoryBackingRoot, + GVFSConstants.GitConfig.AutoSparseIndex, + GVFSConstants.GitConfig.AutoSparseIndexDefault, + this.Enlistment.CreateGitProcess(this.Tracer).TryGetBoolFromConfig); using (GitIndexProjection index = new GitIndexProjection( context, @@ -125,7 +132,9 @@ protected IssueType TryParseIndex(string path, List messages) { try { - index.BuildProjectionFromPath(this.Tracer, path); + // When sparse-index support is on, a sparse-directory entry is valid. Repair + // checks the entry, but it does not read the trees under it. + index.BuildProjectionFromPath(this.Tracer, path, acceptSparseDirectories: sparseIndexEnabled); } catch (SparseIndexNotSupportedException ex) {