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
13 changes: 13 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 Expand Up @@ -170,6 +177,12 @@ public static class DotGVFS
public const string LogName = "logs";
public const string MountLock = "mount.lock";

/// <summary>
/// The mount creates this file when a working-tree change needs a sparse-index cone
/// change that the index does not have yet. The pre-command hook checks it.
/// </summary>
public const string ConeChangePending = "ConeChangePending";

public static class Databases
{
public const string Name = "databases";
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
3 changes: 3 additions & 0 deletions GVFS/GVFS.Common/Git/GitConfigSetting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ public class GitConfigSetting
{
public const string CoreVirtualizeObjectsName = "core.virtualizeobjects";
public const string CoreVirtualFileSystemName = "core.virtualfilesystem";
public const string CoreIgnoreCaseName = "core.ignorecase";
public const string CoreSparseCheckoutName = "core.sparsecheckout";
public const string IndexSparseName = "index.sparse";
public const string CredentialUseHttpPath = "credential.\"https://dev.azure.com\".useHttpPath";

public const string HttpSslCert = "http.sslcert";
Expand Down
161 changes: 161 additions & 0 deletions GVFS/GVFS.Common/Git/GitProcess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,167 @@ public Result Reset(string target, string paths)
return this.InvokeGitInWorkingDirectoryRoot($"reset {target} {paths}", useReadObjectHook: false);
}

/// <summary>
/// Make the sparse-directory entries of the index match the cone file with
/// <c>git sparse-checkout reapply</c>. Git expands each sparse-directory entry that the
/// cone now includes, and collapses each directory that the cone no longer includes.
/// </summary>
/// <remarks>
/// For a mounted enlistment:
/// <list type="bullet">
/// <item>The virtual file system stays on. Git then keeps the skip-worktree bits that
/// the mount reports, and it does not write working-tree files.</item>
/// <item>The hooks path stays as it is, because Git asks the virtual file system hook
/// which paths are present.</item>
/// <item>The read-object hook stays on, because Git can read tree objects that are not
/// local yet when it expands a directory.</item>
/// <item><c>COMMAND_HOOK_LOCK</c> makes Git skip the pre-command and post-command hooks,
/// so this process does not ask for the GVFS lock or for a cone change.</item>
/// <item><c>index.deleteSparseDirectories=false</c> stops Git from deleting the
/// working-tree directories that leave the cone.</item>
/// </list>
/// Git does not do the same with <c>update-index --force-write-index</c>: it does not
/// expand a sparse-directory entry that the cone now includes.
/// </remarks>
public Result ReapplySparseCheckout()
{
return this.InvokeGitImpl(
"-c index.deleteSparseDirectories=false sparse-checkout reapply",
workingDirectory: this.workingDirectoryRoot,
dotGitDirectory: null,
useReadObjectHook: true,
writeStdIn: null,
parseStdOutLine: null,
timeoutMs: -1,
usePreCommandHook: false);
}

/// <summary>
/// List the sparse-directory entries of the index with <c>git ls-files --sparse</c>.
/// </summary>
/// <remarks>
/// <c>ls-files --sparse</c> reads a sparse index without expanding it. The virtual file
/// system stays on, so Git keeps the skip-worktree bits that the mount reports.
/// <c>COMMAND_HOOK_LOCK</c> makes Git skip the pre-command and post-command hooks.
/// </remarks>
public Result ListSparseDirectories(Action<string> onSparseDirectory)
{
ArgumentNullException.ThrowIfNull(onSparseDirectory);

return this.InvokeGitImpl(
"ls-files --sparse -z",
workingDirectory: this.workingDirectoryRoot,
dotGitDirectory: null,
useReadObjectHook: false,
writeStdIn: null,
parseStdOutLine: null,
timeoutMs: -1,
usePreCommandHook: false,
parseStdOutToken: path =>
{
if (path.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal))
{
onSparseDirectory(path);
}
});
}

/// <summary>
/// List the paths that differ between HEAD and the index or the working tree, with
/// <c>git status --porcelain=v2</c>: changed and unmerged tracked paths, and untracked
/// files. An untracked folder ends with '/'. Git does not list ignored files.
/// </summary>
/// <remarks>
/// <c>git status</c> reads a sparse index without expanding it, and it compares the
/// content of a file whose stat data changed, so a file that has the content of HEAD
/// again is not listed. <c>--no-optional-locks</c> stops Git from writing the refreshed
/// index, so this does not need the GVFS lock. <c>--no-deserialize</c> stops Git from
/// reading the GVFS status cache. The virtual file system stays on, so Git checks only
/// the paths that the mount reports, and it looks for untracked files only there.
/// <c>COMMAND_HOOK_LOCK</c> makes Git skip the pre-command and post-command hooks.
/// </remarks>
public Result ListPathsThatDifferFromHead(Action<string> onPath, int timeoutMs)
{
ArgumentNullException.ThrowIfNull(onPath);

return this.InvokeGitImpl(
"--no-optional-locks status --porcelain=v2 -z --untracked-files=normal --no-renames --ignore-submodules=all --no-deserialize",
workingDirectory: this.workingDirectoryRoot,
dotGitDirectory: null,
useReadObjectHook: true,
writeStdIn: null,
parseStdOutLine: null,
timeoutMs: timeoutMs,
usePreCommandHook: false,
parseStdOutToken: record =>
{
string path = GetPorcelainV2Path(record);
if (path != null)
{
onPath(path);
}
});
}

/// <summary>Run <c>git version --build-options</c>.</summary>
public Result VersionBuildOptions()
{
return this.InvokeGitOutsideEnlistment("version --build-options");
}

/// <summary>
/// Return true when the output of <c>git version --build-options</c> has a line that is
/// exactly <paramref name="option"/>, apart from white space at the ends.
/// </summary>
internal static bool HasBuildOption(string buildOptionsOutput, string option)
{
if (buildOptionsOutput == null)
{
return false;
}

foreach (string line in buildOptionsOutput.Split('\n'))
{
if (string.Equals(line.Trim(), option, StringComparison.Ordinal))
{
return true;
}
}

return false;
}

/// <summary>
/// Return the path of a <c>git status --porcelain=v2 -z</c> record for a changed,
/// unmerged, or untracked entry, or null for any other record. The path of an untracked
/// folder ends with '/'.
/// </summary>
internal static string GetPorcelainV2Path(string record)
{
// "1 XY sub mH mI mW hH hI path", "u XY sub m1 m2 m3 mW h1 h2 h3 path", and
// "? path". The path is the rest of the record, so it can contain spaces.
int pathField;
if (record.StartsWith("1 ", StringComparison.Ordinal))
{
pathField = 8;
}
else if (record.StartsWith("u ", StringComparison.Ordinal))
{
pathField = 10;
}
else if (record.StartsWith("? ", StringComparison.Ordinal))
{
pathField = 1;
}
else
{
return null;
}

string[] fields = record.Split(' ', pathField + 1);
return fields.Length == pathField + 1 && fields[pathField].Length > 0 ? fields[pathField] : null;
}

public Result Status(bool allowObjectDownloads, bool useStatusCache, bool showUntracked = false)
{
string command = "status";
Expand Down
33 changes: 33 additions & 0 deletions GVFS/GVFS.Common/Git/GitRepo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,39 @@ 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 the in-process libgit2 repo (no git.exe spawn).
/// </summary>
/// <returns>
/// The config value, or <paramref name="defaultValue"/> if the setting is unset or no
/// libgit2 repo is available.
/// </returns>
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
Loading
Loading