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
9 changes: 9 additions & 0 deletions GVFS/GVFS.Common/FileSystem/PhysicalFileSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,15 @@ public virtual void FlushFileBuffers(string path)
GVFSPlatform.Instance.FileSystem.FlushFileBuffers(path);
}

/// <summary>
/// Return true when <paramref name="path"/> names the file that <paramref name="stream"/>
/// has open, and no delete of that file is pending. Return false when this is not known.
/// </summary>
public virtual bool IsOpenFileAtPath(Stream stream, string path)
{
return stream is FileStream fileStream && NativeMethods.IsOpenFileAtPath(fileStream.SafeFileHandle, path);
}

public virtual void CreateDirectory(string path)
{
Directory.CreateDirectory(path);
Expand Down
198 changes: 198 additions & 0 deletions GVFS/GVFS.Common/Git/GitProcess.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
Expand Down Expand Up @@ -962,6 +963,203 @@ internal static bool HasBuildOption(string buildOptionsOutput, string option)
}

/// <summary>
/// Read the blob of each path in the index (stage 0) with <c>git ls-files --sparse -s</c>
/// and in HEAD with <c>git ls-tree -l</c>. Add each path that has the same regular-file
/// blob in both to <paramref name="matchingBlobs"/>, and each path that the index does not
/// have to <paramref name="notInIndex"/>.
/// </summary>
/// <remarks>
/// Neither command writes the index. <c>--sparse</c> stops <c>ls-files</c> from expanding
/// a sparse index. <c>--literal-pathspecs</c> makes Git match each path exactly. The
/// commands need no skip-worktree bits, so the virtual file system is off, and Git does
/// not run its hook. <c>sparse.expectFilesOutsideOfPatterns</c> stops Git from looking
/// for projected files outside the cone. The paths
/// go on the command line, in several commands when they are too long for one, so Git
/// does not read standard input and the output streams while Git runs. The read-object
/// hook stays on, because the HEAD tree can be not local yet. <c>COMMAND_HOOK_LOCK</c>
/// makes Git skip the pre-command and post-command hooks.
/// </remarks>
/// <param name="timeoutMs">The time that all the commands together can take.</param>
public Result GetBlobsThatMatchHead(IReadOnlyList<string> gitPaths, StringComparer pathComparer, IDictionary<string, HeadBlob> matchingBlobs, ICollection<string> notInIndex, int timeoutMs)
{
ArgumentNullException.ThrowIfNull(gitPaths);
ArgumentNullException.ThrowIfNull(pathComparer);
ArgumentNullException.ThrowIfNull(matchingBlobs);
ArgumentNullException.ThrowIfNull(notInIndex);

Dictionary<string, string> indexBlobs = new Dictionary<string, string>(pathComparer);
Dictionary<string, HeadBlob> headBlobs = new Dictionary<string, HeadBlob>(pathComparer);
Result result = new Result(string.Empty, string.Empty, Result.SuccessCode);
Stopwatch stopwatch = Stopwatch.StartNew();
Result timedOut = new Result(string.Empty, "The blob lookup took longer than " + timeoutMs + " ms", Result.GenericFailureCode);
foreach (string pathspecs in GetPathspecArguments(gitPaths))
{
int remainingMs = timeoutMs - (int)stopwatch.ElapsedMilliseconds;
if (remainingMs <= 0)
{
return timedOut;
}

result = this.InvokeGitImpl(
"-c core.virtualfilesystem= -c sparse.expectFilesOutsideOfPatterns=true --literal-pathspecs ls-files --sparse -s -z -- " + pathspecs,
workingDirectory: this.workingDirectoryRoot,
dotGitDirectory: null,
useReadObjectHook: false,
writeStdIn: null,
parseStdOutLine: null,
timeoutMs: remainingMs,
usePreCommandHook: false,
parseStdOutToken: record =>
{
if (TryParseLsFilesStageRecord(record, out string path, out string sha))
{
indexBlobs[path] = sha;
}
});
if (result.ExitCodeIsFailure)
{
return result;
}

remainingMs = timeoutMs - (int)stopwatch.ElapsedMilliseconds;
if (remainingMs <= 0)
{
return timedOut;
}

result = this.InvokeGitImpl(
"-c core.virtualfilesystem= -c sparse.expectFilesOutsideOfPatterns=true --literal-pathspecs ls-tree -l -z HEAD -- " + pathspecs,
workingDirectory: this.workingDirectoryRoot,
dotGitDirectory: null,
useReadObjectHook: true,
writeStdIn: null,
parseStdOutLine: null,
timeoutMs: remainingMs,
usePreCommandHook: false,
parseStdOutToken: record =>
{
if (TryParseLsTreeLongRecord(record, out string path, out HeadBlob blob))
{
headBlobs[path] = blob;
}
});
if (result.ExitCodeIsFailure)
{
return result;
}
}

foreach (string path in gitPaths)
{
if (!indexBlobs.TryGetValue(path, out string indexSha))
{
notInIndex.Add(path);
}
else if (headBlobs.TryGetValue(path, out HeadBlob headBlob) &&
string.Equals(indexSha, headBlob.Sha, StringComparison.Ordinal))
{
matchingBlobs[path] = headBlob;
}
}

return result;
}

/// <summary>
/// Quote the paths for a command line, and split them into groups that fit in one command.
/// </summary>
internal static IEnumerable<string> GetPathspecArguments(IReadOnlyList<string> gitPaths, int maxLength = 24000)
{
StringBuilder arguments = new StringBuilder();
foreach (string path in gitPaths)
{
string quoted = QuoteGitPath(path);
if (arguments.Length > 0 && arguments.Length + quoted.Length + 1 > maxLength)
{
yield return arguments.ToString();
arguments.Clear();
}

if (arguments.Length > 0)
{
arguments.Append(' ');
}

arguments.Append(quoted);
}

if (arguments.Length > 0)
{
yield return arguments.ToString();
}
}

/// <summary>
/// Parse a <c>git ls-files -s -z</c> record of a regular file at stage 0:
/// "&lt;mode&gt; &lt;oid&gt; 0\t&lt;path&gt;". Return false for any other record, for
/// example a sparse-directory entry, a symbolic link, or a conflict stage.
/// </summary>
internal static bool TryParseLsFilesStageRecord(string record, out string path, out string sha)
{
path = null;
sha = null;
int tab = record?.IndexOf('\t') ?? -1;
if (tab <= 0 || tab == record.Length - 1)
{
return false;
}

string[] fields = record.Substring(0, tab).Split(' ');
if (fields.Length != 3 || !IsRegularFileMode(fields[0]) || !IsSha(fields[1]) || fields[2] != "0")
{
return false;
}

path = record.Substring(tab + 1);
sha = fields[1].ToLowerInvariant();
return true;
}

/// <summary>
/// Parse a <c>git ls-tree -l -z</c> record of a regular file:
/// "&lt;mode&gt; blob &lt;oid&gt; &lt;size&gt;\t&lt;path&gt;" (Git pads the size with spaces).
/// Return false for any other record.
/// </summary>
internal static bool TryParseLsTreeLongRecord(string record, out string path, out HeadBlob blob)
{
path = null;
blob = default;
int tab = record?.IndexOf('\t') ?? -1;
if (tab <= 0 || tab == record.Length - 1)
{
return false;
}

string[] fields = record.Substring(0, tab).Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length != 4 ||
!IsRegularFileMode(fields[0]) ||
fields[1] != "blob" ||
!IsSha(fields[2]) ||
!long.TryParse(fields[3], NumberStyles.None, CultureInfo.InvariantCulture, out long size))
{
return false;
}

path = record.Substring(tab + 1);
blob = new HeadBlob(fields[2].ToLowerInvariant(), size);
return true;
}

private static bool IsRegularFileMode(string mode)
{
return mode == "100644" || mode == "100755";
}

private static bool IsSha(string value)
{
return value.Length == GVFSConstants.ShaStringLength && SHA1Util.IsValidShaFormat(value);
}

/// Return the path of a <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 '/'.
Expand Down
7 changes: 7 additions & 0 deletions GVFS/GVFS.Common/Git/HeadBlob.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace GVFS.Common.Git
{
/// <summary>A blob that the index and HEAD both have for a path.</summary>
/// <param name="Sha">The object id of the blob.</param>
/// <param name="Size">The size of the blob in bytes.</param>
public readonly record struct HeadBlob(string Sha, long Size);
}
79 changes: 79 additions & 0 deletions GVFS/GVFS.Common/NativeMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ public static partial class NativeMethods
private const int ERROR_FILE_NOT_FOUND = 0x2;
private const int ERROR_PATH_NOT_FOUND = 0x3;

// FILE_INFO_BY_HANDLE_CLASS values.
private const int FileStandardInfoClass = 1;
private const int FileIdInfoClass = 18;

[Flags]
public enum MoveFileFlags : uint
{
Expand Down Expand Up @@ -202,6 +206,55 @@ public static DateTime GetLastRebootTime()
return DateTime.Now - uptime;
}

/// <summary>
/// Return true when <paramref name="path"/> names the file that <paramref name="openHandle"/>
/// refers to, and no delete of that file is pending. Return false when this is not known.
/// </summary>
public static bool IsOpenFileAtPath(SafeFileHandle openHandle, string path)
{
if (!GetFileInformationByHandleEx(openHandle, FileStandardInfoClass, out FileStandardInfo standardInfo, (uint)Marshal.SizeOf<FileStandardInfo>()) ||
standardInfo.DeletePending != 0 ||
!GetFileInformationByHandleEx(openHandle, FileIdInfoClass, out FileIdInfo openId, (uint)Marshal.SizeOf<FileIdInfo>()))
{
return false;
}

// The prefix allows a path longer than MAX_PATH. FILE_FLAG_OPEN_REPARSE_POINT: a link
// at the path is not the file that it points to.
using (SafeFileHandle pathHandle = CreateFile(
ToExtendedLengthPath(path),
FileAccess.FILE_READ_ATTRIBUTES,
FileShare.ReadWrite | FileShare.Delete,
IntPtr.Zero,
FileMode.Open,
FileAttributes.FILE_FLAG_OPEN_REPARSE_POINT,
IntPtr.Zero))
{
if (pathHandle.IsInvalid ||
!GetFileInformationByHandleEx(pathHandle, FileIdInfoClass, out FileIdInfo pathId, (uint)Marshal.SizeOf<FileIdInfo>()))
{
return false;
}

return openId.VolumeSerialNumber == pathId.VolumeSerialNumber &&
openId.FileIdLow == pathId.FileIdLow &&
openId.FileIdHigh == pathId.FileIdHigh;
}
}

private static string ToExtendedLengthPath(string path)
{
string fullPath = Path.GetFullPath(path);
if (fullPath.StartsWith(@"\\?\", StringComparison.Ordinal))
{
return fullPath;
}

return fullPath.StartsWith(@"\\", StringComparison.Ordinal)
? @"\\?\UNC\" + fullPath.Substring(2)
: @"\\?\" + fullPath;
}

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool MoveFileEx(
string existingFileName,
Expand All @@ -211,6 +264,14 @@ private static extern bool MoveFileEx(
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool FlushFileBuffers(SafeFileHandle hFile);

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetFileInformationByHandleEx(SafeFileHandle hFile, int fileInformationClass, out FileStandardInfo fileInformation, uint bufferSize);

[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetFileInformationByHandleEx(SafeFileHandle hFile, int fileInformationClass, out FileIdInfo fileInformation, uint bufferSize);

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool GetVolumeInformation(
string rootPathName,
Expand Down Expand Up @@ -336,5 +397,23 @@ private struct OSVersionInfo
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string CSDVersion;
}

[StructLayout(LayoutKind.Sequential)]
private struct FileStandardInfo
{
public long AllocationSize;
public long EndOfFile;
public uint NumberOfLinks;
public byte DeletePending;
public byte Directory;
}

[StructLayout(LayoutKind.Sequential)]
private struct FileIdInfo
{
public ulong VolumeSerialNumber;
public ulong FileIdLow;
public ulong FileIdHigh;
}
}
}
Loading
Loading