Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions GVFS/GVFS.Common/GVFSConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions GVFS/GVFS.Common/Git/GVFSGitObjects.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public enum RequestSource
GVFSVerb,
NamedPipeMessage,
SymLinkCreation,
ProjectionBuild,
}

/// <summary>
Expand Down Expand Up @@ -261,6 +262,12 @@ public DownloadAndSaveObjectResult TryDownloadAndSaveObject(string objectId, Req
return this.TryDownloadAndSaveObject(objectId, CancellationToken.None, requestSource, retryOnFailure: true).Result;
}

/// <exception cref="OperationCanceledException"><paramref name="cancellationToken"/> was canceled</exception>
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);
Expand Down
36 changes: 36 additions & 0 deletions GVFS/GVFS.Common/Git/GitRepo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,42 @@ public virtual bool TryGetConfigValue(string name, out string value)
return this.libgit2RepoInvoker.TryInvoke(repo => repo.GetConfigString(name), out value);
}

/// <summary>
/// Reads a boolean git config value through <see cref="LibGit2RepoInvoker.GetConfigBoolOrDefault"/>,
/// which uses git.exe instead of libgit2 when the environment changes git config.
/// Virtual so that unit tests can supply config values.
/// </summary>
/// <returns>
/// The config value, or <paramref name="defaultValue"/> if the setting is unset or no
/// libgit2 repo is available.
/// </returns>
/// <exception cref="System.IO.InvalidDataException">git.exe cannot read the setting.</exception>
public virtual bool GetConfigBoolOrDefault(string name, bool defaultValue)
{
if (this.libgit2RepoInvoker == null)
{
return defaultValue;
}

return this.libgit2RepoInvoker.GetConfigBoolOrDefault(name, defaultValue);
}

/// <summary>
/// Reads the entries of a tree object from the local object store. Does not download objects.
/// </summary>
/// <param name="treeId">The 20-byte object id of the tree</param>
/// <param name="visitor">Receives each entry, in tree order. The spans are valid only during the call.</param>
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)
Expand Down
87 changes: 87 additions & 0 deletions GVFS/GVFS.Common/Git/LibGit2Repo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ namespace GVFS.Common.Git
/// </remarks>
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.
//
Expand Down Expand Up @@ -338,6 +340,80 @@ public virtual string[] GetMissingSubTrees(string treeSha)
return missingSubtreesList.ToArray();
}

/// <summary>
/// Reads the entries of a tree object from the local object store, and calls
/// <paramref name="visitor"/> once for each entry, in tree order. Does not download objects.
/// </summary>
/// <param name="treeId">The 20-byte object id of the tree</param>
/// <param name="visitor">Receives each entry. The spans are valid only during the call.</param>
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<byte>(name, nameLength),
new ReadOnlySpan<byte>((byte*)entryId, GitOidLength),
Native.Tree.GetEntryFileMode(entryHandle));
}
}
finally
{
Native.Object.Free(treeHandle);
}

return TreeEnumerationResult.Success;
}

/// <summary>
/// Get a config value from the repo's git config.
/// </summary>
Expand Down Expand Up @@ -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);

Expand Down Expand Up @@ -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")]
Expand Down
49 changes: 49 additions & 0 deletions GVFS/GVFS.Common/Git/TreeEnumeration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
using System;

namespace GVFS.Common.Git
{
/// <summary>
/// The result of an attempt to read the entries of a tree object from the local object store.
/// </summary>
public enum TreeEnumerationResult
{
/// <summary>
/// The object is a tree. The visitor received every entry, in tree order.
/// </summary>
Success,

/// <summary>
/// The object is not in the local object store. The visitor received no entries.
/// A download can make the object available.
/// </summary>
MissingTree,

/// <summary>
/// The object is in the local object store, but it is not a tree. The visitor received no entries.
/// </summary>
NotTree,

/// <summary>
/// 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.
/// </summary>
CorruptTree,

/// <summary>
/// The repository is not available, for example because it is shutting down.
/// The visitor received no entries.
/// </summary>
RepositoryUnavailable,
}

/// <summary>
/// Receives one entry of a tree object.
/// </summary>
/// <param name="name">The UTF-8 name of the entry. It is valid only during the call.</param>
/// <param name="objectId">The 20-byte object id of the entry. It is valid only during the call.</param>
/// <param name="fileMode">
/// The git file mode of the entry, for example 0100644 (file), 0100755 (executable),
/// 0120000 (symbolic link), 0160000 (gitlink), or 040000 (tree).
/// </param>
public delegate void TreeEntryVisitor(ReadOnlySpan<byte> name, ReadOnlySpan<byte> objectId, uint fileMode);
}
13 changes: 12 additions & 1 deletion GVFS/GVFS.Common/GitStatusCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ public class GitStatusCache : IDisposable
private readonly Lock hydrationStatisticsLock = new Lock();

private Func<int> projectedFolderCountProvider;
private Func<int> projectedFileCountProvider;
private Func<IEnumerable<string>> modifiedPathsProvider;

private volatile CacheState cacheState = CacheState.Dirty;
Expand Down Expand Up @@ -99,6 +100,15 @@ public void SetProjectedFolderCountProvider(Func<int> provider)
this.projectedFolderCountProvider = provider;
}

/// <summary>
/// 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).
/// </summary>
public void SetProjectedFileCountProvider(Func<int> provider)
{
this.projectedFileCountProvider = provider;
}

public void SetModifiedPathsProvider(Func<IEnumerable<string>> provider)
{
ArgumentNullException.ThrowIfNull(provider);
Expand Down Expand Up @@ -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)
Expand Down
12 changes: 11 additions & 1 deletion GVFS/GVFS.Common/HealthCalculator/EnlistmentHydrationSummary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ internal static EnlistmentHydrationSummary CreateSummary(
Func<int> projectedFolderCountProvider,
EnlistmentPathData pathData,
CancellationToken cancellationToken = default,
HydrationSummaryDiagnostics diagnostics = null)
HydrationSummaryDiagnostics diagnostics = null,
Func<int> projectedFileCountProvider = null)
{
diagnostics = diagnostics ?? new HydrationSummaryDiagnostics();
EnlistmentHydrationSummary summary = new EnlistmentHydrationSummary { Diagnostics = diagnostics };
Expand All @@ -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();
Expand Down
Loading
Loading