diff --git a/GVFS/GVFS.Common/GitPathspecParser.cs b/GVFS/GVFS.Common/GitPathspecParser.cs
new file mode 100644
index 000000000..d0fc3aded
--- /dev/null
+++ b/GVFS/GVFS.Common/GitPathspecParser.cs
@@ -0,0 +1,601 @@
+using System;
+using System.Collections.Generic;
+
+namespace GVFS.Common
+{
+ ///
+ /// General-purpose parser for a Git command line as seen by the GVFS
+ /// pre/post-command hooks. Its job is to extract the set of working-tree
+ /// paths (pathspecs) that a command names, so the mount process can widen
+ /// the sparse-index cone to cover them before Git runs.
+ ///
+ ///
+ ///
+ /// This is distinct from , which classifies
+ /// a whole command string into coarse verbs for the virtualization layer.
+ /// This parser instead extracts pathspecs from the argv the hooks receive.
+ ///
+ ///
+ /// The hook args array has the shape produced by the GVFS git-hooks loader
+ /// plus Git itself:
+ /// [hookType, gitCommand, arg0, arg1, ..., --git-pid=<pid>[, --exit_code=<n>]].
+ ///
+ ///
+ /// Git strips its global options (-C, -c, --git-dir,
+ /// --work-tree, ...) in handle_options() before it dispatches
+ /// the builtin, so run_pre_command_hook() receives an argv that
+ /// starts at the command name. In normal operation the hook therefore never
+ /// sees global options. This parser still recognizes a leading run of global
+ /// options so that it is a correct general Git command-line parser (and so
+ /// callers that construct a full command line are handled), but that path is
+ /// defensive: the common case consumes zero global options.
+ ///
+ ///
+ /// Extraction never has to be exact. A missed pathspec only means that Git
+ /// expands the sparse index in memory to resolve the path, which is slower
+ /// but correct. An over-broad pathspec only makes the cone wider than
+ /// necessary. Both error directions are benign, so ambiguous positional
+ /// arguments are classified conservatively rather than perfectly.
+ ///
+ ///
+ public static class GitPathspecParser
+ {
+ internal const string GitPidArgPrefix = "--git-pid=";
+ private const string ExitCodeArgPrefix = "--exit_code=";
+ private const string PathspecFromFileArg = "--pathspec-from-file";
+ private const string PathspecFromFileEqualsArg = "--pathspec-from-file=";
+ private const string PathspecFileNulArg = "--pathspec-file-nul";
+ private const string DashDash = "--";
+ private const string EndOfOptions = "--end-of-options";
+
+ // Global (pre-command) long options that consume a following token as
+ // their value. Matches git.c handle_options(). The "=value" form of any
+ // of these is self-contained and needs no special handling.
+ private static readonly HashSet GlobalLongOptionsWithValue = new HashSet(StringComparer.Ordinal)
+ {
+ "--git-dir",
+ "--work-tree",
+ "--namespace",
+ "--super-prefix",
+ "--config-env",
+ "--attr-source",
+ "-c",
+ };
+
+ private static readonly Dictionary CommandSpecs = BuildCommandSpecs();
+
+ private enum PositionalKind
+ {
+ /// Every positional argument is a pathspec (add, rm, mv, restore, commit).
+ Pathspec,
+
+ /// The first positionals are refs; the rest are pathspecs (checkout, reset).
+ LeadingRefsThenPathspec,
+
+ /// No positional before "--" is a pathspec; only "-- <paths>" count (diff, log, show, grep, blame, and unknown commands).
+ RefsOnly,
+
+ /// The command takes no pathspecs at all (switch).
+ None,
+
+ /// The first positional is a stash subcommand; pathspecs follow only for push/save.
+ StashSubcommand,
+ }
+
+ ///
+ /// Parses a hook args array and returns the pathspecs the command names.
+ ///
+ ///
+ /// The full hook argument array, where hookArgs[0] is the hook
+ /// type and hookArgs[1] is normally the Git command.
+ ///
+ public static ParsedGitCommand ParseHookArgs(string[] hookArgs)
+ {
+ if (hookArgs == null || hookArgs.Length < 2)
+ {
+ return ParsedGitCommand.Empty;
+ }
+
+ // hookArgs[0] is the hook type (pre-command / post-command).
+ return ParseTokens(hookArgs, startIndex: 1);
+ }
+
+ ///
+ /// Parses a token list starting at , which
+ /// must point at the leading global options or the command name.
+ ///
+ private static ParsedGitCommand ParseTokens(IReadOnlyList tokens, int startIndex)
+ {
+ string changeDirectory = null;
+ string gitDir = null;
+ string workTree = null;
+
+ int index = startIndex;
+
+ // Phase 1: consume a leading run of Git global options. In the normal
+ // hook case there are none and this loop exits immediately with the
+ // command at the first token.
+ while (index < tokens.Count)
+ {
+ string token = tokens[index];
+
+ if (IsInjectedArg(token))
+ {
+ index++;
+ continue;
+ }
+
+ if (!token.StartsWith("-", StringComparison.Ordinal) || token == DashDash)
+ {
+ // First non-option token is the command name.
+ break;
+ }
+
+ index++;
+
+ if (TrySplitEquals(token, out string name, out string value))
+ {
+ RecordGlobal(name, value, ref changeDirectory, ref gitDir, ref workTree);
+ continue;
+ }
+
+ if (token == "-C")
+ {
+ if (index < tokens.Count)
+ {
+ changeDirectory = tokens[index++];
+ }
+
+ continue;
+ }
+
+ if (GlobalLongOptionsWithValue.Contains(token))
+ {
+ if (index < tokens.Count)
+ {
+ string globalValue = tokens[index++];
+ RecordGlobal(token, globalValue, ref changeDirectory, ref gitDir, ref workTree);
+ }
+
+ continue;
+ }
+
+ // Boolean global option (or an unrecognized one) — nothing to consume.
+ }
+
+ if (index >= tokens.Count)
+ {
+ return new ParsedGitCommand(null, null, null, false, false, changeDirectory, gitDir, workTree);
+ }
+
+ string command = NormalizeCommand(tokens[index]);
+ index++;
+
+ GitCommandSpec spec = GetSpec(command);
+ return ParseCommandArgs(tokens, index, command, spec, changeDirectory, gitDir, workTree);
+ }
+
+ private static ParsedGitCommand ParseCommandArgs(
+ IReadOnlyList tokens,
+ int startIndex,
+ string command,
+ GitCommandSpec spec,
+ string changeDirectory,
+ string gitDir,
+ string workTree)
+ {
+ List pathspecs = new List();
+ string pathspecFromFile = null;
+ bool pathspecFileNul = false;
+
+ bool pastDashDash = false;
+ bool pastEndOfOptions = false;
+ bool captureNextAsPathspecFile = false;
+ bool skipNextAsValue = false;
+ int positionalIndex = 0;
+ bool stashTakesPaths = false;
+
+ // Some flags remove the command's leading ref operand, so every
+ // positional becomes a pathspec. The canonical case is conflict
+ // resolution: "git checkout --ours " / "--theirs " and
+ // "git checkout -p " name a working-tree path with no ref, yet
+ // the default checkout grammar would misread that first positional as
+ // a branch. Detect these up front so classification uses the right
+ // leading-ref count regardless of token order.
+ int leadingRefCount = spec.LeadingRefCount;
+ if (leadingRefCount > 0 && HasRefSuppressingFlag(tokens, startIndex, spec))
+ {
+ leadingRefCount = 0;
+ }
+
+ for (int i = startIndex; i < tokens.Count; i++)
+ {
+ string token = tokens[i];
+
+ if (captureNextAsPathspecFile)
+ {
+ pathspecFromFile = token;
+ captureNextAsPathspecFile = false;
+ continue;
+ }
+
+ if (skipNextAsValue)
+ {
+ skipNextAsValue = false;
+ continue;
+ }
+
+ // Git appends --git-pid / --exit_code after all user arguments,
+ // so filter them even past "--".
+ if (IsInjectedArg(token))
+ {
+ continue;
+ }
+
+ if (!pastDashDash)
+ {
+ if (token == DashDash)
+ {
+ pastDashDash = true;
+ continue;
+ }
+
+ if (pastEndOfOptions)
+ {
+ // After --end-of-options, a token that starts with "-" is a
+ // positional argument (for example a ref named "-topic"),
+ // but "--" still separates the refs from the pathspecs.
+ ClassifyPositional(spec, leadingRefCount, token, positionalIndex, pathspecs, ref stashTakesPaths);
+ positionalIndex++;
+ continue;
+ }
+
+ if (token == EndOfOptions)
+ {
+ pastEndOfOptions = true;
+ continue;
+ }
+
+ if (token.StartsWith(PathspecFromFileEqualsArg, StringComparison.Ordinal))
+ {
+ pathspecFromFile = token.Substring(PathspecFromFileEqualsArg.Length);
+ continue;
+ }
+
+ if (token == PathspecFromFileArg)
+ {
+ captureNextAsPathspecFile = true;
+ continue;
+ }
+
+ if (token == PathspecFileNulArg)
+ {
+ pathspecFileNul = true;
+ continue;
+ }
+
+ if (token.StartsWith("--", StringComparison.Ordinal))
+ {
+ // Long option. The "=value" form is self-contained; the
+ // bare form consumes a following token only when this
+ // command declares the option as value-taking.
+ if (token.IndexOf('=') < 0 && spec.LongOptionsWithValue.Contains(token))
+ {
+ skipNextAsValue = true;
+ }
+
+ continue;
+ }
+
+ if (token.Length > 1 && token[0] == '-')
+ {
+ // Short option cluster, possibly combined (e.g. "-am").
+ // A value-taking letter that is the last character
+ // consumes the following token; otherwise the remainder
+ // of the cluster is its baked-in value.
+ if (ShortClusterConsumesNextArg(token, spec.ShortOptionsWithValue))
+ {
+ skipNextAsValue = true;
+ }
+
+ continue;
+ }
+
+ ClassifyPositional(spec, leadingRefCount, token, positionalIndex, pathspecs, ref stashTakesPaths);
+ positionalIndex++;
+ }
+ else
+ {
+ // Everything after "--" is a literal pathspec, for commands
+ // that take pathspecs at all.
+ if (PathspecsEnabledPastSeparator(spec, stashTakesPaths))
+ {
+ pathspecs.Add(token);
+ }
+ }
+ }
+
+ bool failed = pathspecFromFile == "-";
+
+ return new ParsedGitCommand(
+ command,
+ pathspecs,
+ pathspecFromFile,
+ pathspecFileNul,
+ failed,
+ changeDirectory,
+ gitDir,
+ workTree);
+ }
+
+ private static void ClassifyPositional(
+ GitCommandSpec spec,
+ int leadingRefCount,
+ string token,
+ int positionalIndex,
+ List pathspecs,
+ ref bool stashTakesPaths)
+ {
+ switch (spec.PositionalKind)
+ {
+ case PositionalKind.Pathspec:
+ pathspecs.Add(token);
+ break;
+
+ case PositionalKind.LeadingRefsThenPathspec:
+ if (positionalIndex >= leadingRefCount)
+ {
+ pathspecs.Add(token);
+ }
+
+ break;
+
+ case PositionalKind.StashSubcommand:
+ if (positionalIndex == 0)
+ {
+ stashTakesPaths =
+ token.Equals("push", StringComparison.Ordinal) ||
+ token.Equals("save", StringComparison.Ordinal);
+ }
+ else if (stashTakesPaths)
+ {
+ pathspecs.Add(token);
+ }
+
+ break;
+
+ case PositionalKind.RefsOnly:
+ case PositionalKind.None:
+ default:
+ break;
+ }
+ }
+
+ private static bool PathspecsEnabledPastSeparator(GitCommandSpec spec, bool stashTakesPaths)
+ {
+ switch (spec.PositionalKind)
+ {
+ case PositionalKind.None:
+ return false;
+ case PositionalKind.StashSubcommand:
+ return stashTakesPaths;
+ default:
+ return true;
+ }
+ }
+
+ private static bool ShortClusterConsumesNextArg(string token, HashSet shortOptionsWithValue)
+ {
+ // token[0] == '-'. Scan the cluster; the first value-taking letter
+ // determines the outcome.
+ for (int j = 1; j < token.Length; j++)
+ {
+ if (shortOptionsWithValue.Contains(token[j]))
+ {
+ // Last character: value is the following token.
+ // Otherwise: the rest of the cluster is a baked-in value.
+ return j == token.Length - 1;
+ }
+ }
+
+ return false;
+ }
+
+ ///
+ /// Returns true when any of the command's ref-suppressing flags appears
+ /// before a "--" separator. Such a flag means the command has no ref
+ /// operand, so every positional is a pathspec.
+ ///
+ private static bool HasRefSuppressingFlag(IReadOnlyList tokens, int startIndex, GitCommandSpec spec)
+ {
+ if (spec.RefSuppressingFlags.Count == 0)
+ {
+ return false;
+ }
+
+ for (int i = startIndex; i < tokens.Count; i++)
+ {
+ string token = tokens[i];
+
+ if (token == DashDash || token == EndOfOptions)
+ {
+ // Past "--" or "--end-of-options" a matching token is a
+ // positional argument, not a flag.
+ break;
+ }
+
+ if (IsInjectedArg(token))
+ {
+ continue;
+ }
+
+ if (spec.RefSuppressingFlags.Contains(token))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static bool IsInjectedArg(string token)
+ {
+ return token.StartsWith(GitPidArgPrefix, StringComparison.Ordinal)
+ || token.StartsWith(ExitCodeArgPrefix, StringComparison.Ordinal);
+ }
+
+ private static bool TrySplitEquals(string token, out string name, out string value)
+ {
+ int equalsIndex = token.IndexOf('=');
+ if (equalsIndex < 0)
+ {
+ name = null;
+ value = null;
+ return false;
+ }
+
+ name = token.Substring(0, equalsIndex);
+ value = token.Substring(equalsIndex + 1);
+ return true;
+ }
+
+ private static void RecordGlobal(
+ string name,
+ string value,
+ ref string changeDirectory,
+ ref string gitDir,
+ ref string workTree)
+ {
+ switch (name)
+ {
+ case "-C":
+ changeDirectory = value;
+ break;
+ case "--git-dir":
+ gitDir = value;
+ break;
+ case "--work-tree":
+ workTree = value;
+ break;
+ }
+ }
+
+ private static string NormalizeCommand(string command)
+ {
+ string normalized = command.ToLowerInvariant();
+ if (normalized.StartsWith("git-", StringComparison.Ordinal))
+ {
+ normalized = normalized.Substring(4);
+ }
+
+ return normalized;
+ }
+
+ private static GitCommandSpec GetSpec(string command)
+ {
+ if (CommandSpecs.TryGetValue(command, out GitCommandSpec spec))
+ {
+ return spec;
+ }
+
+ // Unknown command: trust only an explicit "--" pathspec separator.
+ return GitCommandSpec.RefsOnlyDefault;
+ }
+
+ private static Dictionary BuildCommandSpecs()
+ {
+ Dictionary specs = new Dictionary(StringComparer.Ordinal);
+
+ GitCommandSpec pathspecPositional = new GitCommandSpec(PositionalKind.Pathspec);
+ specs["add"] = pathspecPositional;
+ specs["stage"] = pathspecPositional;
+ specs["rm"] = new GitCommandSpec(PositionalKind.Pathspec);
+ specs["mv"] = new GitCommandSpec(PositionalKind.Pathspec);
+
+ specs["restore"] = new GitCommandSpec(
+ PositionalKind.Pathspec,
+ longOptionsWithValue: new[] { "--source", "--conflict" },
+ shortOptionsWithValue: new[] { 's' });
+
+ specs["commit"] = new GitCommandSpec(
+ PositionalKind.Pathspec,
+ longOptionsWithValue: new[]
+ {
+ "--message", "--author", "--date", "--reuse-message", "--reedit-message",
+ "--fixup", "--squash", "--file", "--template", "--cleanup", "--trailer",
+ },
+ shortOptionsWithValue: new[] { 'm', 'C', 'c', 'F', 't' });
+
+ specs["checkout"] = new GitCommandSpec(
+ PositionalKind.LeadingRefsThenPathspec,
+ leadingRefCount: 1,
+ longOptionsWithValue: new[] { "--conflict", "--orphan" },
+ shortOptionsWithValue: new[] { 'b', 'B' },
+ refSuppressingFlags: new[] { "--ours", "--theirs", "--patch", "-p" });
+
+ specs["switch"] = new GitCommandSpec(
+ PositionalKind.None,
+ longOptionsWithValue: new[] { "--orphan" },
+ shortOptionsWithValue: new[] { 'c', 'C' });
+
+ specs["reset"] = new GitCommandSpec(
+ PositionalKind.LeadingRefsThenPathspec,
+ leadingRefCount: 1);
+
+ specs["stash"] = new GitCommandSpec(
+ PositionalKind.StashSubcommand,
+ longOptionsWithValue: new[] { "--message" },
+ shortOptionsWithValue: new[] { 'm' });
+
+ // Commands whose paths are only unambiguous after "--".
+ specs["diff"] = GitCommandSpec.RefsOnlyDefault;
+ specs["log"] = GitCommandSpec.RefsOnlyDefault;
+ specs["show"] = GitCommandSpec.RefsOnlyDefault;
+ specs["grep"] = GitCommandSpec.RefsOnlyDefault;
+ specs["blame"] = GitCommandSpec.RefsOnlyDefault;
+
+ return specs;
+ }
+
+ ///
+ /// Immutable per-command grammar description used by the parser.
+ ///
+ private sealed class GitCommandSpec
+ {
+ private static readonly HashSet EmptyLongOptions = new HashSet(StringComparer.Ordinal);
+ private static readonly HashSet EmptyShortOptions = new HashSet();
+
+ public static readonly GitCommandSpec RefsOnlyDefault = new GitCommandSpec(PositionalKind.RefsOnly);
+
+ public GitCommandSpec(
+ PositionalKind positionalKind,
+ int leadingRefCount = 0,
+ IEnumerable longOptionsWithValue = null,
+ IEnumerable shortOptionsWithValue = null,
+ IEnumerable refSuppressingFlags = null)
+ {
+ this.PositionalKind = positionalKind;
+ this.LeadingRefCount = leadingRefCount;
+ this.LongOptionsWithValue = longOptionsWithValue == null
+ ? EmptyLongOptions
+ : new HashSet(longOptionsWithValue, StringComparer.Ordinal);
+ this.ShortOptionsWithValue = shortOptionsWithValue == null
+ ? EmptyShortOptions
+ : new HashSet(shortOptionsWithValue);
+ this.RefSuppressingFlags = refSuppressingFlags == null
+ ? EmptyLongOptions
+ : new HashSet(refSuppressingFlags, StringComparer.Ordinal);
+ }
+
+ public PositionalKind PositionalKind { get; }
+
+ public int LeadingRefCount { get; }
+
+ public HashSet LongOptionsWithValue { get; }
+
+ public HashSet ShortOptionsWithValue { get; }
+
+ public HashSet RefSuppressingFlags { get; }
+ }
+ }
+}
diff --git a/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs
new file mode 100644
index 000000000..412c9fec0
--- /dev/null
+++ b/GVFS/GVFS.Common/NamedPipes/ConeManagementNamedPipeMessages.cs
@@ -0,0 +1,228 @@
+using GVFS.Common.Sparse;
+using System.Collections.Generic;
+
+namespace GVFS.Common.NamedPipes
+{
+ public static partial class NamedPipeMessages
+ {
+ ///
+ /// Messages for automatic sparse-index cone management.
+ ///
+ ///
+ /// The pre-command hook sends a before Git runs, so that the
+ /// mount can widen the sparse-index cone to cover the paths that the Git command names.
+ /// The post-command hook sends a with the same
+ /// CommandId after Git runs, so that the mount can remove the cone entries that
+ /// it added for that command.
+ ///
+ /// The hook treats every reply other than as "not applied"
+ /// and lets Git run. This includes from a mount that does
+ /// not handle these messages, , no reply within the
+ /// wait budget, and no mount. Git then expands the sparse index in memory.
+ ///
+ ///
+ /// A widen request carries only repo-relative git-form paths that the hook resolved
+ /// (see ). It carries no absolute path
+ /// and no file for the mount to read. Any local user can write to the mount pipe, so
+ /// rejects a body with any other path.
+ ///
+ ///
+ /// The mount owns the lifetime of the entries that it adds. A narrow can be missing
+ /// (the Git process was killed) or late (it timed out). Two Git commands can widen the
+ /// same directory at the same time, because commands that do not take the GVFS lock
+ /// (for example git diff -- <path>) also send widen requests. The command id
+ /// is the Git process id, so the mount can count the commands that need an entry and
+ /// remove the entries of a process that no longer runs.
+ ///
+ ///
+ /// A body is a list of fields separated by NUL. The header and the body split on the
+ /// first '|' only, so a field can contain '|'.
+ ///
+ ///
+ public static class ConeManagement
+ {
+ public const string WidenRequest = "ConeWiden";
+ public const string NarrowRequest = "ConeNarrow";
+
+ /// The mount applied the request.
+ public const string SuccessResult = "S";
+
+ /// The mount tried to apply the request and failed.
+ public const string FailureResult = "F";
+
+ /// The mount received the request, but automatic sparse index is not enabled.
+ public const string NotEnabledResult = "NE";
+
+ ///
+ /// The time that the pre-command hook allows to connect and send a widen request. If
+ /// the hook cannot send the request in this time, it lets Git run, and it does not
+ /// send the request.
+ ///
+ public const int WidenWaitBudgetMs = 1000;
+
+ ///
+ /// The maximum time that the pre-command hook waits for the reply after it sent a
+ /// widen request. To apply a widen, the mount runs Git, which holds the index lock.
+ /// If the hook let Git run first, Git could fail because the index lock exists. Thus
+ /// the hook waits for the reply. The ceiling is far above the measured time of a
+ /// widen on a large repository (about 1.3 seconds at most, including the wait for
+ /// earlier requests), and it stops a mount that does not reply from blocking Git
+ /// without limit.
+ ///
+ public const int WidenReplyCeilingMs = 10000;
+
+ ///
+ /// The maximum time that the post-command hook waits for a narrow reply. Git has
+ /// already run, so this wait only delays the return to the user.
+ ///
+ public const int NarrowWaitBudgetMs = 100;
+
+ ///
+ /// The maximum time that the hook waits to connect to the mount pipe. A live mount
+ /// accepts the connection quickly. Without a mount, the connect fails at this limit.
+ ///
+ public const int ConnectTimeoutMs = 50;
+
+ private const char FieldSeparator = '\0';
+
+ ///
+ /// Return true when a command id is empty or has 1 to 10 ASCII digits (a Windows
+ /// process id fits in 10 digits).
+ ///
+ public static bool IsValidCommandId(string commandId)
+ {
+ if (commandId == null || commandId.Length > 10)
+ {
+ return false;
+ }
+
+ foreach (char character in commandId)
+ {
+ if (character < '0' || character > '9')
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ ///
+ /// Parameters for a widen request: the Git command id and the repo-relative
+ /// git-form paths to cover. A path with a trailing slash is a folder, and the mount
+ /// covers its whole subtree. Any other path is a file, and the mount covers the
+ /// files in its parent directory.
+ ///
+ public class WidenParameters
+ {
+ public WidenParameters(string commandId, IReadOnlyList paths)
+ {
+ this.CommandId = commandId ?? string.Empty;
+ this.Paths = paths ?? new List();
+ }
+
+ ///
+ /// Identifies the Git command: the Git process id, as decimal digits, or empty.
+ /// The pre-command and post-command hooks of one Git command send the same value.
+ ///
+ public string CommandId { get; }
+
+ /// The repo-relative git-form paths to cover.
+ public IReadOnlyList Paths { get; }
+
+ ///
+ /// Return true when the command id is valid and there is at least one path,
+ /// and every path is valid.
+ ///
+ public bool IsValid()
+ {
+ if (!IsValidCommandId(this.CommandId) || this.Paths.Count == 0)
+ {
+ return false;
+ }
+
+ foreach (string path in this.Paths)
+ {
+ if (!ConePathspecResolver.IsValidGitPath(path))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public string ToBody()
+ {
+ List fields = new List(1 + this.Paths.Count) { this.CommandId };
+ fields.AddRange(this.Paths);
+ return string.Join(FieldSeparator.ToString(), fields);
+ }
+
+ ///
+ /// Parse a widen body. Return false when the body is not valid (see
+ /// ).
+ ///
+ public static bool TryParse(string body, out WidenParameters parameters)
+ {
+ parameters = null;
+ if (body == null)
+ {
+ return false;
+ }
+
+ string[] fields = body.Split(FieldSeparator);
+ List paths = new List(fields.Length - 1);
+ for (int i = 1; i < fields.Length; i++)
+ {
+ paths.Add(fields[i]);
+ }
+
+ WidenParameters candidate = new WidenParameters(fields[0], paths);
+ if (!candidate.IsValid())
+ {
+ return false;
+ }
+
+ parameters = candidate;
+ return true;
+ }
+ }
+
+ ///
+ /// Parameters for a narrow request: the command id of the Git command whose widen
+ /// the mount removes.
+ ///
+ public class NarrowParameters
+ {
+ public NarrowParameters(string commandId)
+ {
+ this.CommandId = commandId ?? string.Empty;
+ }
+
+ /// The Git process id, as decimal digits, or empty.
+ public string CommandId { get; }
+
+ public string ToBody()
+ {
+ return this.CommandId;
+ }
+
+ ///
+ /// Parse a narrow body. Return false when the command id is not valid.
+ ///
+ public static bool TryParse(string body, out NarrowParameters parameters)
+ {
+ parameters = null;
+ if (!IsValidCommandId(body))
+ {
+ return false;
+ }
+
+ parameters = new NarrowParameters(body);
+ return true;
+ }
+ }
+ }
+ }
+}
diff --git a/GVFS/GVFS.Common/ParsedGitCommand.cs b/GVFS/GVFS.Common/ParsedGitCommand.cs
new file mode 100644
index 000000000..98b54688e
--- /dev/null
+++ b/GVFS/GVFS.Common/ParsedGitCommand.cs
@@ -0,0 +1,78 @@
+using System.Collections.Generic;
+
+namespace GVFS.Common
+{
+ ///
+ /// The result of parsing a Git command line for the working-tree paths it
+ /// names. Produced by .
+ ///
+ public class ParsedGitCommand
+ {
+ private static readonly IReadOnlyList NoPathspecs = new List();
+
+ public ParsedGitCommand(
+ string command,
+ IReadOnlyList pathspecs,
+ string pathspecFromFile,
+ bool pathspecFileNul,
+ bool failed,
+ string changeDirectory,
+ string gitDir,
+ string workTree)
+ {
+ this.Command = command;
+ this.Pathspecs = pathspecs ?? NoPathspecs;
+ this.PathspecFromFile = pathspecFromFile;
+ this.PathspecFileNul = pathspecFileNul;
+ this.Failed = failed;
+ this.ChangeDirectory = changeDirectory;
+ this.GitDir = gitDir;
+ this.WorkTree = workTree;
+ }
+
+ /// An empty result, returned when there is nothing to parse.
+ public static ParsedGitCommand Empty { get; } =
+ new ParsedGitCommand(null, NoPathspecs, null, false, false, null, null, null);
+
+ /// The Git command (verb), lowercased and with any "git-" prefix removed. Null when absent.
+ public string Command { get; }
+
+ /// The literal pathspecs the command names, in command-line order.
+ public IReadOnlyList Pathspecs { get; }
+
+ /// The argument of --pathspec-from-file, if present; "-" means stdin. Null when absent.
+ public string PathspecFromFile { get; }
+
+ /// True when --pathspec-file-nul was present.
+ public bool PathspecFileNul { get; }
+
+ ///
+ /// True when the command's pathspecs cannot be resolved from the command
+ /// line alone, e.g. --pathspec-from-file=- reads them from stdin. Callers
+ /// must not treat an empty pathspec set as authoritative when this is set.
+ ///
+ public bool Failed { get; }
+
+ /// The -C value (global change-directory), if present. Null when absent.
+ public string ChangeDirectory { get; }
+
+ /// The --git-dir value, if present. Null when absent.
+ public string GitDir { get; }
+
+ /// The --work-tree value, if present. Null when absent.
+ public string WorkTree { get; }
+
+ ///
+ /// True when the command names at least one path (inline, or via
+ /// --pathspec-from-file), and the pathspecs were resolvable.
+ ///
+ public bool NamesPaths
+ {
+ get
+ {
+ return !this.Failed &&
+ (this.Pathspecs.Count > 0 || !string.IsNullOrEmpty(this.PathspecFromFile));
+ }
+ }
+ }
+}
diff --git a/GVFS/GVFS.Common/Sparse/ConeCoverage.cs b/GVFS/GVFS.Common/Sparse/ConeCoverage.cs
new file mode 100644
index 000000000..50448114f
--- /dev/null
+++ b/GVFS/GVFS.Common/Sparse/ConeCoverage.cs
@@ -0,0 +1,294 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace GVFS.Common.Sparse
+{
+ ///
+ /// Reads a cone-mode info/sparse-checkout file into a ,
+ /// and finds the resolved paths that the cone does not cover.
+ ///
+ ///
+ /// A widen request for paths that the cone covers cannot change the cone. The pre-command
+ /// hook uses this type to find those requests and not send them, so that a command that
+ /// names only in-cone paths does not wait for the mount.
+ ///
+ /// The parse is strict and follows git's cone-mode reader (add_pattern_to_hashsets
+ /// in dir.c). Like git, it skips empty lines and comment lines. The file must start
+ /// with the /* and !/*/ header lines.
+ /// Each later line must be a positive directory pattern or a parent-only marker that
+ /// follows the positive pattern for the same directory, and no directory can repeat.
+ /// For any other file, fails, and the caller must not
+ /// trust the file.
+ ///
+ ///
+ public sealed class ConeCoverage
+ {
+ private const string HeaderInclude = "/*";
+ private const string HeaderExclude = "!/*/";
+ private const string ParentOnlySuffix = "/*/";
+
+ private static readonly UTF8Encoding Utf8WithoutBom = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
+
+ private readonly ConePathMatcher matcher;
+ private readonly HashSet recursiveDirectories;
+
+ public ConeCoverage(ConePatternSet cone)
+ {
+ ArgumentNullException.ThrowIfNull(cone);
+
+ this.matcher = new ConePathMatcher(cone);
+ this.recursiveDirectories = new HashSet(cone.RecursiveDirectories, GitPathComparer.GetComparer(cone.IgnoreCase));
+ }
+
+ ///
+ /// Decode sparse-checkout file bytes as git reads them: skip a UTF-8 byte order mark and
+ /// read the rest as UTF-8. Git does not recognize other byte order marks, so a UTF-16
+ /// file does not decode to cone patterns. A byte sequence that is not UTF-8 becomes
+ /// U+FFFD, and does not trust a directory with U+FFFD.
+ ///
+ public static string DecodeConeFile(byte[] bytes)
+ {
+ ArgumentNullException.ThrowIfNull(bytes);
+
+ int start = bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF ? 3 : 0;
+ return Utf8WithoutBom.GetString(bytes, start, bytes.Length - start);
+ }
+
+ ///
+ /// Return true when the content starts with the cone-mode header lines /* and
+ /// !/*/. Git cannot use a sparse index without cone mode, so content without
+ /// the header cannot need a widen.
+ ///
+ public static bool HasConeHeader(string content)
+ {
+ if (content == null)
+ {
+ return false;
+ }
+
+ int position = 0;
+ return TryReadLine(content, ref position, out string first) && first == HeaderInclude &&
+ TryReadLine(content, ref position, out string second) && second == HeaderExclude;
+ }
+
+ ///
+ /// Parse cone-mode sparse-checkout file content. Return false when the content is not
+ /// a cone file that git and GVFS read with the same meaning.
+ ///
+ /// The file content.
+ /// The repository's core.ignoreCase value.
+ /// The cone, when the method returns true. Otherwise null.
+ public static bool TryParseConeFile(string content, bool ignoreCase, out ConePatternSet cone)
+ {
+ cone = null;
+ if (!HasConeHeader(content))
+ {
+ return false;
+ }
+
+ GitPathComparer comparer = GitPathComparer.GetComparer(ignoreCase);
+ List positiveDirectories = new List();
+ HashSet positives = new HashSet(comparer);
+ HashSet parentOnly = new HashSet(comparer);
+
+ int position = 0;
+ TryReadLine(content, ref position, out _);
+ TryReadLine(content, ref position, out _);
+ while (TryReadLine(content, ref position, out string line))
+ {
+ if (line[0] == '!')
+ {
+ // Git requires the positive pattern before its parent-only marker.
+ if (!TryParseParentOnly(line, out string directory) ||
+ !positives.Contains(directory) ||
+ !parentOnly.Add(directory))
+ {
+ return false;
+ }
+ }
+ else
+ {
+ if (!TryParsePositive(line, out string directory) || !positives.Add(directory))
+ {
+ return false;
+ }
+
+ positiveDirectories.Add(directory);
+ }
+ }
+
+ List parentOnlyDirectories = new List();
+ List recursiveDirectories = new List();
+ foreach (string directory in positiveDirectories)
+ {
+ if (parentOnly.Contains(directory))
+ {
+ parentOnlyDirectories.Add(directory);
+ }
+ else
+ {
+ recursiveDirectories.Add(directory);
+ }
+ }
+
+ try
+ {
+ cone = new ConePatternSet(parentOnlyDirectories, recursiveDirectories, ignoreCase);
+ }
+ catch (ArgumentException)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ ///
+ /// Return true when a resolved git-form path is in the cone. A file path is covered
+ /// when git includes it (see ). A folder path, which
+ /// ends with a slash, is covered only when its whole subtree is in the cone: the folder
+ /// or one of its ancestors is a recursive directory.
+ ///
+ public bool IsCovered(string resolvedGitPath)
+ {
+ ArgumentNullException.ThrowIfNull(resolvedGitPath);
+
+ string path = ConePath.Normalize(resolvedGitPath, out bool isFolder);
+ if (!isFolder)
+ {
+ return this.matcher.IsInCone(path);
+ }
+
+ for (string directory = path; directory.Length != 0; directory = ConePath.GetParent(directory))
+ {
+ if (this.recursiveDirectories.Contains(directory))
+ {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ ///
+ /// Return the resolved git-form paths that the cone does not cover, in their input order.
+ ///
+ public IReadOnlyList GetUncoveredPaths(IEnumerable resolvedGitPaths)
+ {
+ ArgumentNullException.ThrowIfNull(resolvedGitPaths);
+
+ List uncovered = new List();
+ foreach (string path in resolvedGitPaths)
+ {
+ if (!this.IsCovered(path))
+ {
+ uncovered.Add(path);
+ }
+ }
+
+ return uncovered;
+ }
+
+ private static bool TryParsePositive(string line, out string directory)
+ {
+ directory = null;
+
+ // A positive directory pattern is "//".
+ if (line.Length < 3 ||
+ line[0] != GVFSConstants.GitPathSeparator ||
+ line[line.Length - 1] != GVFSConstants.GitPathSeparator)
+ {
+ return false;
+ }
+
+ return TryUnescapeDirectory(line.Substring(1, line.Length - 2), out directory);
+ }
+
+ private static bool TryParseParentOnly(string line, out string directory)
+ {
+ directory = null;
+
+ // A parent-only marker is "!//*/".
+ if (line.Length < 2 + 1 + ParentOnlySuffix.Length ||
+ line[1] != GVFSConstants.GitPathSeparator ||
+ !line.EndsWith(ParentOnlySuffix, StringComparison.Ordinal))
+ {
+ return false;
+ }
+
+ return TryUnescapeDirectory(line.Substring(2, line.Length - 2 - ParentOnlySuffix.Length), out directory);
+ }
+
+ ///
+ /// Reverse . Fail on an unescaped wildcard
+ /// character or on a backslash that does not escape one, because git does not read
+ /// either as a literal cone directory.
+ ///
+ private static bool TryUnescapeDirectory(string escaped, out string directory)
+ {
+ directory = null;
+
+ StringBuilder builder = new StringBuilder(escaped.Length);
+ for (int i = 0; i < escaped.Length; i++)
+ {
+ char character = escaped[i];
+ if (character == '\\')
+ {
+ if (i + 1 >= escaped.Length || !IsGlobSpecial(escaped[i + 1]))
+ {
+ return false;
+ }
+
+ i++;
+ builder.Append(escaped[i]);
+ }
+ else if (IsGlobSpecial(character))
+ {
+ return false;
+ }
+ else
+ {
+ builder.Append(character);
+ }
+ }
+
+ directory = builder.ToString();
+
+ // DecodeConeFile replaces bytes that are not UTF-8 with U+FFFD, and git compares
+ // the original bytes. Such a directory cannot be compared, so do not trust the file.
+ return directory.IndexOf('\uFFFD') < 0 && ConePatternSet.IsValidDirectory(directory);
+ }
+
+ ///
+ /// Read the next line that is not empty and not a comment, without its line ending, and
+ /// move past it. Git's reader skips the same lines.
+ ///
+ private static bool TryReadLine(string content, ref int position, out string line)
+ {
+ while (position < content.Length)
+ {
+ int end = content.IndexOf('\n', position);
+ if (end < 0)
+ {
+ end = content.Length;
+ }
+
+ line = content.Substring(position, end - position).TrimEnd('\r');
+ position = end + 1;
+ if (line.Length != 0 && line[0] != '#')
+ {
+ return true;
+ }
+ }
+
+ line = null;
+ return false;
+ }
+
+ private static bool IsGlobSpecial(char character)
+ {
+ return character == '*' || character == '?' || character == '[' || character == '\\';
+ }
+ }
+}
diff --git a/GVFS/GVFS.Common/Sparse/ConePathspecResolver.cs b/GVFS/GVFS.Common/Sparse/ConePathspecResolver.cs
new file mode 100644
index 000000000..4fc52ba76
--- /dev/null
+++ b/GVFS/GVFS.Common/Sparse/ConePathspecResolver.cs
@@ -0,0 +1,355 @@
+using System;
+using System.Collections.Generic;
+
+namespace GVFS.Common.Sparse
+{
+ ///
+ /// Resolves the literal pathspecs that a Git command names into repo-relative git-form
+ /// paths, which and accept.
+ ///
+ ///
+ /// This type does no I/O.
+ ///
+ /// Only a trailing slash gives a pathspec the shape of a folder. A folder resolves to a
+ /// recursive entry, and any other pathspec resolves to a file, which puts only its parent
+ /// directory in the cone. Thus an ambiguous dir/subdir is under-widened, not
+ /// over-widened. An over-wide recursive entry makes the index larger. An under-wide
+ /// entry only makes Git expand the index in memory.
+ ///
+ ///
+ /// The resolver skips a pathspec that it cannot map to one cone entry, so the result can
+ /// only under-widen. It skips a magic pathspec (a leading :), a path outside the
+ /// worktree, the worktree root, a pathspec with a wildcard character in a directory
+ /// segment, and a path that rejects. A wildcard only in the
+ /// last segment of a file pathspec is kept: the file's parent directory is still the
+ /// right cone entry for it.
+ ///
+ ///
+ public static class ConePathspecResolver
+ {
+ private static readonly char[] WildcardCharacters = new[] { '*', '?', '[' };
+ private static readonly string[] ReservedDeviceNames = new[] { "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$" };
+
+ ///
+ /// Return the directory that relative pathspecs resolve against.
+ ///
+ ///
+ /// Before Git runs the pre-command hook for a command that uses a repository, Git
+ /// changes to the top of the worktree and puts the user's subdirectory in the
+ /// GIT_PREFIX environment variable. Thus when the hook runs at the worktree
+ /// root and is a relative path inside the worktree, the
+ /// base directory is the root plus the prefix. In all other cases, the hook's current
+ /// directory is the base directory.
+ ///
+ /// The current directory of the hook process (absolute).
+ /// The root of the worktree (absolute).
+ /// The value of GIT_PREFIX, or null when it is not set.
+ public static string GetPathspecBaseDirectory(string hookCurrentDirectory, string workingDirectoryRoot, string gitPrefix)
+ {
+ ArgumentNullException.ThrowIfNull(hookCurrentDirectory);
+ ArgumentNullException.ThrowIfNull(workingDirectoryRoot);
+
+ if (string.IsNullOrEmpty(gitPrefix))
+ {
+ return hookCurrentDirectory;
+ }
+
+ string current = TrimTrailingSeparators(ToForwardSlashes(hookCurrentDirectory));
+ string root = TrimTrailingSeparators(ToForwardSlashes(workingDirectoryRoot));
+ if (!current.Equals(root, StringComparison.OrdinalIgnoreCase))
+ {
+ // Git did not change to the worktree root, so the prefix does not apply.
+ return hookCurrentDirectory;
+ }
+
+ // Git writes the prefix as a relative path with a trailing slash. Ignore any other
+ // value, so that the base directory cannot leave the worktree.
+ string prefix = TrimTrailingSeparators(ToForwardSlashes(gitPrefix));
+ if (prefix.Length == 0 || !IsValidGitPath(prefix))
+ {
+ return hookCurrentDirectory;
+ }
+
+ return root + GVFSConstants.GitPathSeparatorString + prefix;
+ }
+
+ ///
+ /// Resolve pathspecs to distinct repo-relative git-form paths. A file entry has no
+ /// trailing slash. A folder entry keeps its trailing slash. Every result passes
+ /// .
+ ///
+ ///
+ /// The directory that relative pathspecs resolve against (absolute). See
+ /// .
+ ///
+ /// The root of the worktree (absolute).
+ /// The literal pathspecs, as the user typed them.
+ public static IReadOnlyList ResolveToGitPaths(
+ string pathspecBaseDirectory,
+ string workingDirectoryRoot,
+ IEnumerable pathspecs)
+ {
+ ArgumentNullException.ThrowIfNull(workingDirectoryRoot);
+
+ List resolved = new List();
+ if (pathspecs == null)
+ {
+ return resolved;
+ }
+
+ string rootAbsolute = TrimTrailingSeparators(ToForwardSlashes(workingDirectoryRoot));
+ string baseAbsolute = TrimTrailingSeparators(ToForwardSlashes(pathspecBaseDirectory ?? string.Empty));
+
+ HashSet seen = new HashSet(StringComparer.Ordinal);
+ foreach (string rawPathspec in pathspecs)
+ {
+ if (TryResolveOne(rawPathspec, rootAbsolute, baseAbsolute, out string gitPath) &&
+ seen.Add(gitPath))
+ {
+ resolved.Add(gitPath);
+ }
+ }
+
+ return resolved;
+ }
+
+ ///
+ /// Return true when a path is a repo-relative git-form path that a cone can contain and
+ /// that stays inside the worktree on Windows.
+ ///
+ ///
+ /// The path uses forward slashes, has no leading slash, and has an optional trailing
+ /// slash for a folder. Its directory part (the folder, or the parent of a file) must
+ /// pass and must not contain a wildcard.
+ /// No segment can be empty, ., .., or .git, end with a dot or a
+ /// space, or be a Windows device name such as CON or COM1. Git for Windows
+ /// does not check out such paths. The path must not contain a backslash, a colon, a
+ /// control character, or an unpaired surrogate.
+ ///
+ public static bool IsValidGitPath(string path)
+ {
+ if (string.IsNullOrEmpty(path) || path[0] == GVFSConstants.GitPathSeparator)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < path.Length; i++)
+ {
+ char character = path[i];
+ if (character < ' ' || character == '\\' || character == ':')
+ {
+ return false;
+ }
+
+ if (char.IsHighSurrogate(character) && i + 1 < path.Length && char.IsLowSurrogate(path[i + 1]))
+ {
+ i++;
+ }
+ else if (char.IsSurrogate(character))
+ {
+ return false;
+ }
+ }
+
+ bool isFolder = path[path.Length - 1] == GVFSConstants.GitPathSeparator;
+ string trimmed = isFolder ? path.Substring(0, path.Length - 1) : path;
+ foreach (string segment in trimmed.Split(GVFSConstants.GitPathSeparator))
+ {
+ if (!IsValidSegment(segment))
+ {
+ return false;
+ }
+ }
+
+ int lastSeparator = trimmed.LastIndexOf(GVFSConstants.GitPathSeparator);
+ string directory = isFolder ? trimmed : (lastSeparator < 0 ? string.Empty : trimmed.Substring(0, lastSeparator));
+ return directory.Length == 0 ||
+ (directory.IndexOfAny(WildcardCharacters) < 0 && ConePatternSet.IsValidDirectory(directory));
+ }
+
+ private static bool IsValidSegment(string segment)
+ {
+ if (segment.Length == 0 ||
+ segment == "." ||
+ segment == ".." ||
+ segment.Equals(GVFSConstants.DotGit.Root, StringComparison.OrdinalIgnoreCase) ||
+ segment[segment.Length - 1] == '.' ||
+ segment[segment.Length - 1] == ' ')
+ {
+ return false;
+ }
+
+ // Windows opens a device for a reserved name, with or without an extension.
+ int dot = segment.IndexOf('.');
+ string name = (dot < 0 ? segment : segment.Substring(0, dot)).TrimEnd(' ');
+ foreach (string reserved in ReservedDeviceNames)
+ {
+ if (name.Equals(reserved, StringComparison.OrdinalIgnoreCase))
+ {
+ return false;
+ }
+ }
+
+ if (name.Length == 4 &&
+ (name.StartsWith("COM", StringComparison.OrdinalIgnoreCase) || name.StartsWith("LPT", StringComparison.OrdinalIgnoreCase)) &&
+ name[3] >= '1' && name[3] <= '9')
+ {
+ return false;
+ }
+
+ return true;
+ }
+ private static bool TryResolveOne(string rawPathspec, string rootAbsolute, string baseAbsolute, out string gitPath)
+ {
+ gitPath = null;
+
+ // A leading ':' starts a magic pathspec (:/, :(glob), :!, ...). Git expands the
+ // index for every magic pathspec, so no cone entry can help.
+ if (string.IsNullOrEmpty(rawPathspec) || rawPathspec[0] == ':')
+ {
+ return false;
+ }
+
+ string normalized = ToForwardSlashes(rawPathspec);
+ bool isFolder = normalized.EndsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal);
+
+ string absolute;
+ if (IsAbsolute(normalized))
+ {
+ absolute = normalized;
+ }
+ else
+ {
+ absolute = baseAbsolute.Length == 0
+ ? normalized
+ : baseAbsolute + GVFSConstants.GitPathSeparatorString + normalized;
+ }
+
+ if (!TryCanonicalize(absolute, out string canonical) ||
+ !TryMakeRepoRelative(canonical, rootAbsolute, out string relative))
+ {
+ return false;
+ }
+
+ // An empty result is the worktree root. The cone always includes the files at the
+ // root, and a recursive root entry is not a cone entry.
+ if (relative.Length == 0 || HasWildcardInDirectorySegment(relative, isFolder))
+ {
+ return false;
+ }
+
+ string candidate = isFolder ? relative + GVFSConstants.GitPathSeparatorString : relative;
+ if (!IsValidGitPath(candidate))
+ {
+ return false;
+ }
+
+ gitPath = candidate;
+ return true;
+ }
+
+ private static bool HasWildcardInDirectorySegment(string relative, bool isFolder)
+ {
+ int directoryLength = isFolder ? relative.Length : relative.LastIndexOf(GVFSConstants.GitPathSeparator);
+ return directoryLength > 0 && relative.IndexOfAny(WildcardCharacters, 0, directoryLength) >= 0;
+ }
+
+ private static bool TryCanonicalize(string path, out string canonical)
+ {
+ canonical = null;
+
+ string[] parts = path.Split(GVFSConstants.GitPathSeparator);
+ List segments = new List(parts.Length);
+ foreach (string part in parts)
+ {
+ if (part.Length == 0 || part == ".")
+ {
+ continue;
+ }
+
+ if (part == "..")
+ {
+ // A ".." that goes above the start of a relative path, or above a drive,
+ // cannot map to a path in the worktree.
+ if (segments.Count == 0 || IsDriveSegment(segments[segments.Count - 1]))
+ {
+ return false;
+ }
+
+ segments.RemoveAt(segments.Count - 1);
+ continue;
+ }
+
+ segments.Add(part);
+ }
+
+ canonical = string.Join(GVFSConstants.GitPathSeparatorString, segments);
+ return true;
+ }
+
+ private static bool TryMakeRepoRelative(string canonicalAbsolute, string rootAbsolute, out string relative)
+ {
+ relative = null;
+
+ if (rootAbsolute.Length == 0)
+ {
+ relative = canonicalAbsolute;
+ return true;
+ }
+
+ // Windows paths are not case-sensitive, so compare the root without case. Keep the
+ // caller's case in the result, because the cone compares it with index entries.
+ if (canonicalAbsolute.Length == rootAbsolute.Length)
+ {
+ if (canonicalAbsolute.Equals(rootAbsolute, StringComparison.OrdinalIgnoreCase))
+ {
+ relative = string.Empty;
+ return true;
+ }
+
+ return false;
+ }
+
+ if (canonicalAbsolute.Length > rootAbsolute.Length &&
+ canonicalAbsolute[rootAbsolute.Length] == GVFSConstants.GitPathSeparator &&
+ canonicalAbsolute.StartsWith(rootAbsolute, StringComparison.OrdinalIgnoreCase))
+ {
+ relative = canonicalAbsolute.Substring(rootAbsolute.Length + 1);
+ return true;
+ }
+
+ return false;
+ }
+
+ private static bool IsAbsolute(string forwardSlashedPath)
+ {
+ // A drive-rooted path (C:/...) or a path with a leading separator (UNC or rooted).
+ // A drive-relative "C:relative" path keeps its colon and IsValidGitPath rejects it.
+ if (forwardSlashedPath.StartsWith(GVFSConstants.GitPathSeparatorString, StringComparison.Ordinal))
+ {
+ return true;
+ }
+
+ return forwardSlashedPath.Length >= 3 &&
+ IsDriveSegment(forwardSlashedPath.Substring(0, 2)) &&
+ forwardSlashedPath[2] == GVFSConstants.GitPathSeparator;
+ }
+
+ private static bool IsDriveSegment(string segment)
+ {
+ return segment.Length == 2 &&
+ char.IsLetter(segment[0]) &&
+ segment[1] == ':';
+ }
+
+ private static string ToForwardSlashes(string path)
+ {
+ return path.Replace('\\', GVFSConstants.GitPathSeparator);
+ }
+
+ private static string TrimTrailingSeparators(string path)
+ {
+ return path.TrimEnd(GVFSConstants.GitPathSeparator);
+ }
+ }
+}
diff --git a/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs
new file mode 100644
index 000000000..e970f42c9
--- /dev/null
+++ b/GVFS/GVFS.FunctionalTests/Tests/EnlistmentPerFixture/ConeManagementHookTests.cs
@@ -0,0 +1,85 @@
+using GVFS.FunctionalTests.Tools;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System.Collections.Generic;
+using System.IO;
+using System.Text;
+
+namespace GVFS.FunctionalTests.Tests.EnlistmentPerFixture
+{
+ ///
+ /// Functional tests for the cone requests that the hooks send when
+ /// gvfs.auto-sparse-index is true. The mount does not handle these requests and
+ /// answers UnknownRequest, so the tests check that Git still runs.
+ ///
+ [TestFixture]
+ public class ConeManagementHookTests : TestsWithEnlistmentPerFixture
+ {
+ private const string AutoSparseIndexConfig = "gvfs.auto-sparse-index";
+
+ // The parent-only directory GVFS puts the files directly in GVFS/ in the cone, but
+ // not the files in GVFS/GVFS.Hooks/. GVFS does not set core.sparseCheckout, so Git
+ // itself ignores this file.
+ private const string ConeWithParentOnlyGVFS = "/*\n!/*/\n/GVFS/\n!/GVFS/*/\n";
+
+ private const string InConeFile = "GVFS/cone-request-in-cone.txt";
+ private const string OutOfConeFile = "GVFS/GVFS.Hooks/cone-request-out-of-cone.txt";
+
+ private static readonly Dictionary TraceEnvironment = new Dictionary
+ {
+ { "GIT_TRACE", "1" },
+ };
+
+ [TestCase]
+ public void GitRunsWhenTheMountDoesNotHandleConeRequests()
+ {
+ string sparseCheckoutPath = Path.Combine(this.Enlistment.RepoRoot, ".git", "info", "sparse-checkout");
+ string originalSparseCheckout = File.Exists(sparseCheckoutPath) ? File.ReadAllText(sparseCheckoutPath) : null;
+
+ try
+ {
+ File.WriteAllText(sparseCheckoutPath, ConeWithParentOnlyGVFS, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
+ GitProcess.Invoke(this.Enlistment.RepoRoot, "config --local " + AutoSparseIndexConfig + " true");
+ File.WriteAllText(this.Enlistment.GetVirtualPathTo(InConeFile), "in cone");
+ File.WriteAllText(this.Enlistment.GetVirtualPathTo(OutOfConeFile), "out of cone");
+
+ // The test runs each command in a subdirectory, so the hook must resolve the
+ // relative path through GIT_PREFIX to find the right cone answer.
+ ProcessResult inCone = GitProcess.InvokeProcess(
+ Path.Combine(this.Enlistment.RepoRoot, "GVFS"),
+ "add " + Path.GetFileName(InConeFile),
+ TraceEnvironment);
+ inCone.ExitCode.ShouldEqual(0, inCone.Errors);
+ inCone.Errors.ShouldContain("gvfs cone-management: widen skipped: SkippedInCone");
+
+ ProcessResult outOfCone = GitProcess.InvokeProcess(
+ Path.Combine(this.Enlistment.RepoRoot, "GVFS", "GVFS.Hooks"),
+ "add " + Path.GetFileName(OutOfConeFile),
+ TraceEnvironment);
+ outOfCone.ExitCode.ShouldEqual(0, outOfCone.Errors);
+ outOfCone.Errors.ShouldContain(
+ "gvfs cone-management: widen not applied: Rejected",
+ "gvfs cone-management: narrow not applied: Rejected");
+
+ GitProcess.Invoke(this.Enlistment.RepoRoot, "diff --cached --name-only")
+ .ShouldContain(InConeFile, OutOfConeFile);
+ }
+ finally
+ {
+ GitProcess.Invoke(this.Enlistment.RepoRoot, "config --local --unset " + AutoSparseIndexConfig);
+ GitProcess.Invoke(this.Enlistment.RepoRoot, "reset -q -- " + InConeFile + " " + OutOfConeFile);
+ File.Delete(this.Enlistment.GetVirtualPathTo(InConeFile));
+ File.Delete(this.Enlistment.GetVirtualPathTo(OutOfConeFile));
+
+ if (originalSparseCheckout == null)
+ {
+ File.Delete(sparseCheckoutPath);
+ }
+ else
+ {
+ File.WriteAllText(sparseCheckoutPath, originalSparseCheckout);
+ }
+ }
+ }
+ }
+}
diff --git a/GVFS/GVFS.Hooks/ConeManagementHook.cs b/GVFS/GVFS.Hooks/ConeManagementHook.cs
new file mode 100644
index 000000000..f8194b787
--- /dev/null
+++ b/GVFS/GVFS.Hooks/ConeManagementHook.cs
@@ -0,0 +1,387 @@
+using GVFS.Common;
+using GVFS.Common.NamedPipes;
+using GVFS.Common.Sparse;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Threading.Tasks;
+
+namespace GVFS.Hooks
+{
+ ///
+ /// Sends automatic sparse-index cone requests from the pre-command and post-command hooks.
+ ///
+ ///
+ /// When gvfs.auto-sparse-index is true and a Git command names paths outside the
+ /// sparse-index cone, the pre-command hook asks the mount to widen the cone before Git
+ /// runs. Otherwise Git expands the whole sparse index in memory to find those paths.
+ /// The post-command hook asks the mount to narrow the cone again.
+ ///
+ /// Cone management must never fail a Git command. Every failure, including no mount, a
+ /// mount that does not know the request, a slow mount, and an exception, lets Git run.
+ /// Git is then slower, but correct. The hook waits at most
+ /// to connect and send
+ /// a widen. After it sent a widen, it waits for the reply, at most
+ /// : the mount applies
+ /// the widen with a Git process that holds the index lock, and the user's Git must not
+ /// start before that process ends.
+ ///
+ ///
+ /// The hook knows only the paths on the command line. It does not read a
+ /// --pathspec-from-file file. A rebase or merge can stop on a conflict in a file
+ /// outside the cone, and those paths come from the commits. For these commands Git
+ /// expands the index, and the hook widens the cone when the user later names the path
+ /// (for example with git add).
+ ///
+ ///
+ /// All dependencies are delegates, so that unit tests can run every path without a mount,
+ /// a repository, or a working tree.
+ ///
+ ///
+ internal sealed class ConeManagementHook
+ {
+ private const string StashCommand = "stash";
+
+ private readonly ReadSparseIndexConfig readConfig;
+ private readonly Func readConeFile;
+ private readonly Func createPipeClient;
+ private readonly string hookCurrentDirectory;
+ private readonly Func getWorkingDirectoryRoot;
+ private readonly string gitPrefix;
+ private readonly Action trace;
+
+ /// Reads the feature flag and core.ignoreCase.
+ ///
+ /// Returns the decoded content of the worktree's info/sparse-checkout file (see
+ /// ), or null when the hook cannot read it.
+ ///
+ /// Creates an unconnected client for the mount pipe.
+ /// The current directory of the hook process.
+ ///
+ /// Returns the root of the worktree that Git runs in, in the same form as
+ /// .
+ ///
+ /// The value of GIT_PREFIX, or null.
+ /// Writes a diagnostic message.
+ public ConeManagementHook(
+ ReadSparseIndexConfig readConfig,
+ Func readConeFile,
+ Func createPipeClient,
+ string hookCurrentDirectory,
+ Func getWorkingDirectoryRoot,
+ string gitPrefix,
+ Action trace)
+ {
+ this.readConfig = readConfig ?? throw new ArgumentNullException(nameof(readConfig));
+ this.readConeFile = readConeFile ?? throw new ArgumentNullException(nameof(readConeFile));
+ this.createPipeClient = createPipeClient ?? throw new ArgumentNullException(nameof(createPipeClient));
+ this.hookCurrentDirectory = hookCurrentDirectory ?? throw new ArgumentNullException(nameof(hookCurrentDirectory));
+ this.getWorkingDirectoryRoot = getWorkingDirectoryRoot ?? throw new ArgumentNullException(nameof(getWorkingDirectoryRoot));
+ this.gitPrefix = gitPrefix;
+ this.trace = trace ?? (message => { });
+ }
+
+ ///
+ /// Reads the gvfs.auto-sparse-index flag. When it is true, also reads
+ /// core.ignoreCase.
+ ///
+ /// The value of the feature flag.
+ internal delegate bool ReadSparseIndexConfig(out bool ignoreCase);
+
+ ///
+ /// If the command names paths outside the cone, ask the mount to widen the cone. Never
+ /// throws.
+ ///
+ /// The hook arguments.
+ ///
+ /// The maximum time to connect and send the request. If this time ends first, the hook
+ /// does not send the request.
+ ///
+ ///
+ /// The maximum time to wait for the reply after the hook sent the request. The mount
+ /// runs Git to apply the widen, and that Git holds the index lock. Thus the hook waits
+ /// for the reply, so that the user's Git does not find the index lock.
+ ///
+ public ConeRequestOutcome TrySendWiden(
+ string[] args,
+ int waitBudgetMs = NamedPipeMessages.ConeManagement.WidenWaitBudgetMs,
+ int replyCeilingMs = NamedPipeMessages.ConeManagement.WidenReplyCeilingMs)
+ {
+ ConeRequestOutcome outcome;
+ try
+ {
+ outcome = this.Widen(args, waitBudgetMs, replyCeilingMs);
+ }
+ catch (Exception e)
+ {
+ this.trace($"widen failed: {e.Message}");
+ return ConeRequestOutcome.Failed;
+ }
+
+ this.TraceOutcome("widen", outcome);
+ return outcome;
+ }
+
+ ///
+ /// If the command names paths, ask the mount to remove the cone entries that it added
+ /// for this command, and wait for the reply, at most
+ /// in total. Never throws.
+ ///
+ ///
+ /// The post-command hook does not repeat the in-cone check of the pre-command hook:
+ /// the cone can change while Git runs, so the result could differ. A narrow for a
+ /// command that did not widen does nothing. A narrow only writes the cone file and does
+ /// not run Git, so the short budget does not let the user's Git find the index lock.
+ ///
+ public ConeRequestOutcome TrySendNarrow(string[] args, int waitBudgetMs = NamedPipeMessages.ConeManagement.NarrowWaitBudgetMs)
+ {
+ ConeRequestOutcome outcome;
+ try
+ {
+ outcome = this.Narrow(args, waitBudgetMs);
+ }
+ catch (Exception e)
+ {
+ this.trace($"narrow failed: {e.Message}");
+ return ConeRequestOutcome.Failed;
+ }
+
+ this.TraceOutcome("narrow", outcome);
+ return outcome;
+ }
+
+ ///
+ /// Return the id that pairs the widen and narrow requests of one Git command: the Git
+ /// process id from the last --git-pid= argument, which Git appends after the
+ /// user's arguments. Return an empty string when it is absent or not a number.
+ ///
+ internal static string GetCommandId(string[] args)
+ {
+ if (args != null)
+ {
+ for (int i = args.Length - 1; i >= 0; i--)
+ {
+ string arg = args[i];
+ if (arg != null && arg.StartsWith(GitPathspecParser.GitPidArgPrefix, StringComparison.Ordinal))
+ {
+ string value = arg.Substring(GitPathspecParser.GitPidArgPrefix.Length);
+ return value.Length != 0 && NamedPipeMessages.ConeManagement.IsValidCommandId(value)
+ ? value
+ : string.Empty;
+ }
+ }
+ }
+
+ return string.Empty;
+ }
+
+ private static bool IsStash(ParsedGitCommand parsed)
+ {
+ return string.Equals(parsed.Command, StashCommand, StringComparison.Ordinal);
+ }
+
+ private ConeRequestOutcome Widen(string[] args, int waitBudgetMs, int replyCeilingMs)
+ {
+ ParsedGitCommand parsed = GitPathspecParser.ParseHookArgs(args);
+ if (!parsed.NamesPaths)
+ {
+ return ConeRequestOutcome.NoPathsNamed;
+ }
+
+ // Check the cone file before the config. Git can use a sparse index only in cone
+ // mode, and a file read costs much less than the repository open that a config
+ // read needs. GVFS does not write a cone-mode file unless the feature is on.
+ string coneFileContent = this.readConeFile();
+ if (!ConeCoverage.HasConeHeader(coneFileContent))
+ {
+ return ConeRequestOutcome.NoConeFile;
+ }
+
+ if (!this.readConfig(out bool ignoreCase))
+ {
+ return ConeRequestOutcome.FeatureDisabled;
+ }
+
+ // Measured on a large repository: git stash push with a pathspec still expanded the
+ // whole index after a widen, and the widen made the command slower.
+ if (IsStash(parsed))
+ {
+ return ConeRequestOutcome.SkippedStash;
+ }
+
+ // Git applies -C, --git-dir, and --work-tree before it runs the hook, so the hook
+ // does not see them. If they are present anyway, the paths belong to another
+ // directory or repository.
+ if (!string.IsNullOrEmpty(parsed.ChangeDirectory) ||
+ !string.IsNullOrEmpty(parsed.GitDir) ||
+ !string.IsNullOrEmpty(parsed.WorkTree))
+ {
+ return ConeRequestOutcome.NoResolvablePaths;
+ }
+
+ string workingDirectoryRoot = this.getWorkingDirectoryRoot();
+ string pathspecBaseDirectory = ConePathspecResolver.GetPathspecBaseDirectory(
+ this.hookCurrentDirectory,
+ workingDirectoryRoot,
+ this.gitPrefix);
+
+ IReadOnlyList paths = ConePathspecResolver.ResolveToGitPaths(
+ pathspecBaseDirectory,
+ workingDirectoryRoot,
+ parsed.Pathspecs);
+
+ if (paths.Count == 0)
+ {
+ return ConeRequestOutcome.NoResolvablePaths;
+ }
+
+ // When the hook cannot trust the cone file, it sends every path and the mount
+ // decides.
+ if (ConeCoverage.TryParseConeFile(coneFileContent, ignoreCase, out ConePatternSet cone))
+ {
+ paths = new ConeCoverage(cone).GetUncoveredPaths(paths);
+ if (paths.Count == 0)
+ {
+ return ConeRequestOutcome.SkippedInCone;
+ }
+ }
+
+ NamedPipeMessages.ConeManagement.WidenParameters parameters =
+ new NamedPipeMessages.ConeManagement.WidenParameters(GetCommandId(args), paths);
+
+ return this.SendBounded(
+ NamedPipeMessages.ConeManagement.WidenRequest,
+ parameters.ToBody(),
+ waitBudgetMs,
+ replyCeilingMs);
+ }
+
+ private ConeRequestOutcome Narrow(string[] args, int waitBudgetMs)
+ {
+ ParsedGitCommand parsed = GitPathspecParser.ParseHookArgs(args);
+ if (!parsed.NamesPaths)
+ {
+ return ConeRequestOutcome.NoPathsNamed;
+ }
+
+ if (!ConeCoverage.HasConeHeader(this.readConeFile()))
+ {
+ return ConeRequestOutcome.NoConeFile;
+ }
+
+ if (!this.readConfig(out _))
+ {
+ return ConeRequestOutcome.FeatureDisabled;
+ }
+
+ if (IsStash(parsed))
+ {
+ return ConeRequestOutcome.SkippedStash;
+ }
+
+ NamedPipeMessages.ConeManagement.NarrowParameters parameters =
+ new NamedPipeMessages.ConeManagement.NarrowParameters(GetCommandId(args));
+
+ return this.SendBounded(
+ NamedPipeMessages.ConeManagement.NarrowRequest,
+ parameters.ToBody(),
+ waitBudgetMs,
+ replyCeilingMs: null);
+ }
+
+ private void TraceOutcome(string request, ConeRequestOutcome outcome)
+ {
+ switch (outcome)
+ {
+ case ConeRequestOutcome.NoPathsNamed:
+ case ConeRequestOutcome.NoConeFile:
+ case ConeRequestOutcome.FeatureDisabled:
+ case ConeRequestOutcome.Applied:
+ break;
+
+ case ConeRequestOutcome.SkippedStash:
+ case ConeRequestOutcome.SkippedInCone:
+ case ConeRequestOutcome.NoResolvablePaths:
+ this.trace($"{request} skipped: {outcome}");
+ break;
+
+ default:
+ this.trace($"{request} not applied: {outcome}");
+ break;
+ }
+ }
+
+ ///
+ /// Connect, send the request, and read the reply on a worker task.
+ ///
+ /// The request header.
+ /// The request body.
+ ///
+ /// The maximum time to connect and send. If is null,
+ /// it also bounds the reply: the full request then takes at most this time.
+ ///
+ ///
+ /// If not null, the maximum time to wait for the reply after the request was sent.
+ ///
+ private ConeRequestOutcome SendBounded(string header, string body, int waitBudgetMs, int? replyCeilingMs)
+ {
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ object sendGate = new object();
+ bool sendAbandoned = false;
+ bool requestSent = false;
+ TaskCompletionSource sending = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ Task task = Task.Run(() =>
+ {
+ using (NamedPipeClient pipeClient = this.createPipeClient())
+ {
+ if (!pipeClient.Connect(NamedPipeMessages.ConeManagement.ConnectTimeoutMs, out _))
+ {
+ return ConeRequestOutcome.MountUnavailable;
+ }
+
+ // After the budget ends, the hook lets Git run. A request sent after that
+ // could make the mount run Git while the user's Git runs.
+ lock (sendGate)
+ {
+ if (sendAbandoned)
+ {
+ return ConeRequestOutcome.TimedOut;
+ }
+
+ requestSent = true;
+ }
+
+ sending.TrySetResult(true);
+ pipeClient.SendRequest(new NamedPipeMessages.Message(header, body));
+ NamedPipeMessages.Message response = pipeClient.ReadResponse();
+ return response.Header == NamedPipeMessages.ConeManagement.SuccessResult
+ ? ConeRequestOutcome.Applied
+ : ConeRequestOutcome.Rejected;
+ }
+ });
+
+ // If the hook cannot send in time, or the mount does not reply in time, abandon the
+ // task. The hook process exits soon after this method returns, which ends the task.
+ if (Task.WaitAny(new Task[] { task, sending.Task }, waitBudgetMs) < 0)
+ {
+ lock (sendGate)
+ {
+ if (!requestSent)
+ {
+ sendAbandoned = true;
+ return ConeRequestOutcome.TimedOut;
+ }
+ }
+ }
+
+ int replyWaitMs = replyCeilingMs ?? Math.Max(0, waitBudgetMs - (int)stopwatch.ElapsedMilliseconds);
+ if (!task.Wait(replyWaitMs))
+ {
+ return replyCeilingMs.HasValue ? ConeRequestOutcome.ReplyTimedOut : ConeRequestOutcome.TimedOut;
+ }
+
+ return task.Result;
+ }
+ }
+}
diff --git a/GVFS/GVFS.Hooks/ConeRequestOutcome.cs b/GVFS/GVFS.Hooks/ConeRequestOutcome.cs
new file mode 100644
index 000000000..fd927f827
--- /dev/null
+++ b/GVFS/GVFS.Hooks/ConeRequestOutcome.cs
@@ -0,0 +1,50 @@
+namespace GVFS.Hooks
+{
+ ///
+ /// The result of one cone-management request attempt from a hook.
+ ///
+ internal enum ConeRequestOutcome
+ {
+ /// The command names no paths, so the hook did nothing.
+ NoPathsNamed,
+
+ /// The worktree has no cone-mode sparse-checkout file, so the index cannot be sparse and the hook did nothing.
+ NoConeFile,
+
+ /// The gvfs.auto-sparse-index feature flag is off, so the hook did nothing.
+ FeatureDisabled,
+
+ /// The command is git stash, which expands the index for any pathspec.
+ SkippedStash,
+
+ /// The cone covers every named path, so a widen cannot change it.
+ SkippedInCone,
+
+ /// No named path maps to a cone entry inside the worktree, so the hook did not send a widen.
+ NoResolvablePaths,
+
+ /// The mount replied that it applied the request.
+ Applied,
+
+ /// The hook could not connect to the mount.
+ MountUnavailable,
+
+ /// The mount replied with a result other than success (for example an unknown request).
+ Rejected,
+
+ ///
+ /// The hook could not connect and send within the wait budget, so it did not send the
+ /// request. For a narrow, the mount also did not reply within that budget.
+ ///
+ TimedOut,
+
+ ///
+ /// The hook sent a widen, but the mount did not reply within the reply ceiling. Git can
+ /// then find the index lock that the mount's Git process holds.
+ ///
+ ReplyTimedOut,
+
+ /// The request failed with an exception.
+ Failed,
+ }
+}
diff --git a/GVFS/GVFS.Hooks/Program.ConeManagement.cs b/GVFS/GVFS.Hooks/Program.ConeManagement.cs
new file mode 100644
index 000000000..27cd0c579
--- /dev/null
+++ b/GVFS/GVFS.Hooks/Program.ConeManagement.cs
@@ -0,0 +1,170 @@
+using GVFS.Common;
+using GVFS.Common.Git;
+using GVFS.Common.NamedPipes;
+using GVFS.Common.Sparse;
+using GVFS.Common.Tracing;
+using GVFS.Hooks.HooksPlatform;
+using System;
+using System.IO;
+
+namespace GVFS.Hooks
+{
+ ///
+ /// Automatic sparse-index cone management. See .
+ ///
+ public partial class Program
+ {
+ private const string CoreIgnoreCaseConfig = "core.ignorecase";
+ private const string GitPrefixEnvironmentVariable = "GIT_PREFIX";
+
+ // A cone file larger than this is not read. The hook then does not widen, and Git
+ // expands the index for the command.
+ private const long MaxConeFileBytes = 16 * 1024 * 1024;
+
+ private static void TrySendConeWiden(string[] args)
+ {
+ try
+ {
+ CreateConeManagementHook().TrySendWiden(args);
+ }
+ catch (Exception e)
+ {
+ TraceConeDiagnostic($"widen failed: {e.Message}");
+ }
+ }
+
+ private static void TrySendConeNarrow(string[] args)
+ {
+ try
+ {
+ CreateConeManagementHook().TrySendNarrow(args);
+ }
+ catch (Exception e)
+ {
+ TraceConeDiagnostic($"narrow failed: {e.Message}");
+ }
+ }
+
+ private static ConeManagementHook CreateConeManagementHook()
+ {
+ return new ConeManagementHook(
+ ReadAutoSparseIndexConfig,
+ ReadConeFile,
+ () => new NamedPipeClient(enlistmentPipename),
+ normalizedCurrentDirectory,
+ GetConeWorkingDirectoryRoot,
+ Environment.GetEnvironmentVariable(GitPrefixEnvironmentVariable),
+ TraceConeDiagnostic);
+ }
+
+ private static bool ReadAutoSparseIndexConfig(out bool ignoreCase)
+ {
+ ignoreCase = false;
+ try
+ {
+ using (LibGit2Repo repo = new LibGit2Repo(NullTracer.Instance, normalizedCurrentDirectory, GitConfigReadRetry.Delay, ConfigReadMaxAttempts))
+ {
+ // GetConfigBool throws for an unreadable or non-boolean value, so that the
+ // catch below can trace it.
+ if (!(repo.GetConfigBool(GVFSConstants.GitConfig.AutoSparseIndex) ?? GVFSConstants.GitConfig.AutoSparseIndexDefault))
+ {
+ return false;
+ }
+
+ ignoreCase = repo.GetConfigBool(CoreIgnoreCaseConfig) ?? false;
+ return true;
+ }
+ }
+ catch (Exception e)
+ {
+ TraceConeDiagnostic($"cannot read {GVFSConstants.GitConfig.AutoSparseIndex}: {e.Message}");
+ return GVFSConstants.GitConfig.AutoSparseIndexDefault;
+ }
+ }
+
+ ///
+ /// Return the worktree root in the same form as ,
+ /// so that the pathspec resolver can compare the two.
+ ///
+ private static string GetConeWorkingDirectoryRoot()
+ {
+ string root = currentWorktreeInfo != null
+ ? currentWorktreeInfo.WorktreePath
+ : Path.Combine(enlistmentRoot, GVFSConstants.WorkingDirectoryRootName);
+
+ return GVFSHooksPlatform.TryGetNormalizedPath(root, out string normalizedRoot, out _) ? normalizedRoot : root;
+ }
+
+ private static string ReadConeFile()
+ {
+ string sparseCheckoutPath = SparseCheckoutPathResolver.GetSparseCheckoutFilePath(
+ isWorktree: currentWorktreeInfo != null,
+ dotGitRoot: Path.Combine(enlistmentRoot, GVFSConstants.WorkingDirectoryRootName, GVFSConstants.DotGit.Root),
+ worktreeGitDir: currentWorktreeInfo?.WorktreeGitDir);
+
+ try
+ {
+ // Open the file once, and read at most one byte more than the limit, so that a
+ // file that changes after the attribute check cannot make the read unbounded.
+ FileInfo file = new FileInfo(sparseCheckoutPath);
+ if (!file.Exists)
+ {
+ return null;
+ }
+
+ if ((file.Attributes & (FileAttributes.ReparsePoint | FileAttributes.Device)) != 0)
+ {
+ TraceConeDiagnostic($"cone file not read: {sparseCheckoutPath} is not a regular file");
+ return null;
+ }
+
+ using (FileStream stream = new FileStream(sparseCheckoutPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
+ using (MemoryStream content = new MemoryStream())
+ {
+ byte[] buffer = new byte[64 * 1024];
+ int read;
+ while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ content.Write(buffer, 0, read);
+ if (content.Length > MaxConeFileBytes)
+ {
+ TraceConeDiagnostic($"cone file not read: {sparseCheckoutPath} is larger than {MaxConeFileBytes} bytes");
+ return null;
+ }
+ }
+
+ return ConeCoverage.DecodeConeFile(content.ToArray());
+ }
+ }
+ catch (Exception e) when (e is IOException || e is UnauthorizedAccessException)
+ {
+ TraceConeDiagnostic($"cone file not read: {e.Message}");
+ return null;
+ }
+ }
+
+ ///
+ /// Write a cone-management diagnostic to stderr, but only when GIT_TRACE sends Git's own
+ /// trace output to stderr (1, 2, or true). Then a skipped request is distinct from a
+ /// failed one, and the hook writes nothing in normal use.
+ ///
+ private static void TraceConeDiagnostic(string message)
+ {
+ string gitTrace = Environment.GetEnvironmentVariable("GIT_TRACE");
+ if (!string.Equals(gitTrace, "1", StringComparison.Ordinal) &&
+ !string.Equals(gitTrace, "2", StringComparison.Ordinal) &&
+ !string.Equals(gitTrace, "true", StringComparison.OrdinalIgnoreCase))
+ {
+ return;
+ }
+
+ try
+ {
+ Console.Error.WriteLine($"gvfs cone-management: {message}");
+ }
+ catch (IOException)
+ {
+ }
+ }
+ }
+}
diff --git a/GVFS/GVFS.Hooks/Program.cs b/GVFS/GVFS.Hooks/Program.cs
index 339e73e69..c4cee26be 100644
--- a/GVFS/GVFS.Hooks/Program.cs
+++ b/GVFS/GVFS.Hooks/Program.cs
@@ -25,6 +25,7 @@ public partial class Program
private static string enlistmentRoot;
private static string enlistmentPipename;
private static string normalizedCurrentDirectory;
+ private static GVFSEnlistment.WorktreeInfo currentWorktreeInfo;
private static Random random = new Random();
private delegate void LockRequestDelegate(bool unattended, string[] args, int pid, NamedPipeClient pipeClient);
@@ -70,7 +71,8 @@ public static void Main(string[] args)
// If running inside a worktree, append a worktree-specific
// suffix to the pipe name so hooks communicate with the
// correct GVFS mount instance.
- string worktreeSuffix = GVFSEnlistment.GetWorktreePipeSuffix(normalizedCurrentDirectory);
+ currentWorktreeInfo = GVFSEnlistment.TryGetWorktreeInfo(normalizedCurrentDirectory);
+ string worktreeSuffix = currentWorktreeInfo?.PipeSuffix;
if (worktreeSuffix != null)
{
enlistmentPipename += worktreeSuffix;
@@ -134,6 +136,8 @@ private static void RunPreCommands(string[] args)
RunWorktreePreCommand(args);
break;
}
+
+ TrySendConeWiden(args);
}
private static bool ArgsBlockHydrationStatus(string[] args)
@@ -154,6 +158,8 @@ private static void RunPostCommands(string[] args)
RunWorktreePostCommand(args);
break;
}
+
+ TrySendConeNarrow(args);
}
private static string ResolvePath(string path)
diff --git a/GVFS/GVFS.UnitTests/Common/ConeManagementMessagesTests.cs b/GVFS/GVFS.UnitTests/Common/ConeManagementMessagesTests.cs
new file mode 100644
index 000000000..c935ccd5e
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Common/ConeManagementMessagesTests.cs
@@ -0,0 +1,109 @@
+using GVFS.Common.NamedPipes;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System.Collections.Generic;
+
+namespace GVFS.UnitTests.Common
+{
+ [TestFixture]
+ public class ConeManagementMessagesTests
+ {
+ [TestCase]
+ public void WidenRequestRoundTripsThroughMessageFrame()
+ {
+ NamedPipeMessages.ConeManagement.WidenParameters original =
+ new NamedPipeMessages.ConeManagement.WidenParameters(
+ "4242",
+ new List { "A/b.txt", "my dir/a|b.txt", "C/D/" });
+
+ NamedPipeMessages.Message message = NamedPipeMessages.Message.FromString(
+ new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.WidenRequest, original.ToBody()).ToString());
+
+ message.Header.ShouldEqual(NamedPipeMessages.ConeManagement.WidenRequest);
+ NamedPipeMessages.ConeManagement.WidenParameters.TryParse(
+ message.Body, out NamedPipeMessages.ConeManagement.WidenParameters parsed)
+ .ShouldBeTrue();
+ parsed.CommandId.ShouldEqual("4242");
+ parsed.Paths.ShouldMatchInOrder("A/b.txt", "my dir/a|b.txt", "C/D/");
+ }
+
+ [TestCase]
+ public void WidenAllowsAnEmptyCommandId()
+ {
+ string body = new NamedPipeMessages.ConeManagement.WidenParameters(null, new List { "A/b.txt" }).ToBody();
+
+ NamedPipeMessages.ConeManagement.WidenParameters.TryParse(body, out NamedPipeMessages.ConeManagement.WidenParameters parsed).ShouldBeTrue();
+ parsed.CommandId.ShouldEqual(string.Empty);
+ }
+
+ [TestCase(null)]
+ [TestCase("")]
+ [TestCase("4242")]
+ [TestCase("12a\0A/b.txt")]
+ [TestCase("4242\0/abs/path.txt")]
+ [TestCase("4242\0C:/Windows/x.txt")]
+ [TestCase("4242\0D:relative.txt")]
+ [TestCase("4242\0//server/share/x.txt")]
+ [TestCase("4242\0A\\b.txt")]
+ [TestCase("4242\0../outside.txt")]
+ [TestCase("4242\0A/../../outside.txt")]
+ [TestCase("4242\0A//b.txt")]
+ [TestCase("4242\0./A/b.txt")]
+ [TestCase("4242\0A/b.txt\0")]
+ [TestCase("4242\0A/line\nbreak.txt")]
+ [TestCase("4242\0A/frame\u0003end.txt")]
+ [TestCase("4242\0A/control\u0001.txt")]
+ [TestCase("4242\0A/*/x.txt")]
+ [TestCase("4242\0A/b?/")]
+ [TestCase("4242\0A/trailing./x.txt")]
+ [TestCase("4242\0A/trailing /x.txt")]
+ [TestCase("4242\0CON")]
+ [TestCase("4242\0A/nul.txt")]
+ [TestCase("4242\0A/COM1/")]
+ [TestCase("4242\0.git/config")]
+ [TestCase("12345678901\0A/b.txt")]
+ public void WidenParseRejectsBodiesThatAreNotRepoRelativePaths(string body)
+ {
+ NamedPipeMessages.ConeManagement.WidenParameters.TryParse(body, out NamedPipeMessages.ConeManagement.WidenParameters parsed)
+ .ShouldBeFalse();
+ parsed.ShouldBeNull();
+ }
+
+ [TestCase]
+ public void WidenParseRejectsAnUnpairedSurrogate()
+ {
+ NamedPipeMessages.ConeManagement.WidenParameters.TryParse("4242\0A/" + '\uD800' + ".txt", out NamedPipeMessages.ConeManagement.WidenParameters parsed)
+ .ShouldBeFalse();
+ parsed.ShouldBeNull();
+ }
+
+ [TestCase("A/*.cs")]
+ [TestCase("A/COM10.txt")]
+ [TestCase("A/console/")]
+ [TestCase("A/.gitignore")]
+ [TestCase("A/\uD83D\uDE00/b.txt")]
+ public void WidenParseAcceptsUnusualButValidPaths(string path)
+ {
+ NamedPipeMessages.ConeManagement.WidenParameters.TryParse("4242\0" + path, out NamedPipeMessages.ConeManagement.WidenParameters parsed)
+ .ShouldBeTrue();
+ parsed.Paths.ShouldMatchInOrder(path);
+ }
+
+ [TestCase("4242", true)]
+ [TestCase("", true)]
+ [TestCase(null, false)]
+ [TestCase("12a", false)]
+ [TestCase("-1", false)]
+ public void NarrowParseAcceptsOnlyDigits(string body, bool expected)
+ {
+ NamedPipeMessages.ConeManagement.NarrowParameters.TryParse(body, out NamedPipeMessages.ConeManagement.NarrowParameters parsed)
+ .ShouldEqual(expected);
+
+ if (expected)
+ {
+ parsed.CommandId.ShouldEqual(body);
+ parsed.ToBody().ShouldEqual(body);
+ }
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/Common/GitPathspecParserTests.cs b/GVFS/GVFS.UnitTests/Common/GitPathspecParserTests.cs
new file mode 100644
index 000000000..8b448b31c
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Common/GitPathspecParserTests.cs
@@ -0,0 +1,648 @@
+using GVFS.Common;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+
+namespace GVFS.UnitTests.Common
+{
+ [TestFixture]
+ public class GitPathspecParserTests
+ {
+ // ── Command extraction ──────────────────────────────────────────
+
+ [TestCase]
+ public void EmptyArgs_ReturnsEmpty()
+ {
+ GitPathspecParser.ParseHookArgs(new string[0]).Command.ShouldBeNull();
+ GitPathspecParser.ParseHookArgs(null).Command.ShouldBeNull();
+ GitPathspecParser.ParseHookArgs(new[] { "pre-command" }).Command.ShouldBeNull();
+ }
+
+ [TestCase]
+ public void Command_IsLowercasedAndGitPrefixStripped()
+ {
+ GitPathspecParser.ParseHookArgs(new[] { "pre-command", "ADD", "file.txt" })
+ .Command.ShouldEqual("add");
+ GitPathspecParser.ParseHookArgs(new[] { "pre-command", "git-add", "file.txt" })
+ .Command.ShouldEqual("add");
+ }
+
+ // ── add / stage / rm / mv: all positionals are pathspecs ────────
+
+ [TestCase]
+ public void Add_InlinePathspecs()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "a.txt", "b.txt" });
+ result.Pathspecs.ShouldMatchInOrder("a.txt", "b.txt");
+ result.NamesPaths.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void Add_NoPathspecs()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add" });
+ result.Pathspecs.ShouldBeEmpty();
+ result.NamesPaths.ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void Add_SkipsOptionFlags()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "--all", "--verbose", "src/" });
+ result.Pathspecs.ShouldMatchInOrder("src/");
+ }
+
+ [TestCase]
+ public void Add_CombinedShortFlags_AreNotPathspecs()
+ {
+ // -Av = --all --verbose; neither takes a value, so "file" is a pathspec.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "-Av", "file" });
+ result.Pathspecs.ShouldMatchInOrder("file");
+ }
+
+ // ── Paths with spaces (shell already stripped quotes) ───────────
+
+ [TestCase]
+ public void Add_PathWithSpaces()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "my documents/todo list.txt" });
+ result.Pathspecs.ShouldMatchInOrder("my documents/todo list.txt");
+ }
+
+ // ── "--" separator ──────────────────────────────────────────────
+
+ [TestCase]
+ public void Add_PathsAfterDashDash()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "--", "-weird-name.txt", "b.txt" });
+ result.Pathspecs.ShouldMatchInOrder("-weird-name.txt", "b.txt");
+ }
+
+ [TestCase]
+ public void DashDash_TokensAreLiteralNotOptions()
+ {
+ // After --, a token that looks like an option is still a pathspec.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "--", "--all" });
+ result.Pathspecs.ShouldMatchInOrder("--all");
+ }
+
+ // ── checkout: leading ref, then pathspecs ───────────────────────
+
+ [TestCase]
+ public void Checkout_BranchOnly_NoPathspecs()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "my-branch" });
+ result.Pathspecs.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void Checkout_HeadDashDashPaths()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "HEAD", "--", "foo.txt", "bar.txt" });
+ result.Pathspecs.ShouldMatchInOrder("foo.txt", "bar.txt");
+ }
+
+ [TestCase]
+ public void Checkout_RefThenPathspecsWithoutDashDash()
+ {
+ // git checkout branch file1 file2 — first positional is the ref.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "branch", "file1", "file2" });
+ result.Pathspecs.ShouldMatchInOrder("file1", "file2");
+ }
+
+ [TestCase]
+ public void Checkout_DashB_ConsumesBranchName_NotPathspec()
+ {
+ // -b creates a branch; the value is not a pathspec.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "-b", "topic" });
+ result.Pathspecs.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void Checkout_DashDashPathsAfterDashB()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "-b", "topic", "--", "file.txt" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ // ── reset: leading ref, then pathspecs ──────────────────────────
+
+ [TestCase]
+ public void Reset_MixedWithPaths()
+ {
+ // git reset HEAD file.txt — first positional is the ref.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "reset", "HEAD", "out1/f.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out1/f.txt");
+ }
+
+ [TestCase]
+ public void Reset_PathsAfterDashDash()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "reset", "--", "out1/f.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out1/f.txt");
+ }
+
+ // ── restore: existing behavior must be covered ──────────────────
+
+ [TestCase]
+ public void Restore_StagedAllFiles()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "restore", "--staged", "." });
+ result.Pathspecs.ShouldMatchInOrder(".");
+ }
+
+ [TestCase]
+ public void Restore_SkipsSourceSeparateValue()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "restore", "--staged", "--source", "HEAD~1", "file.txt" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void Restore_SkipsSourceEqualsValue()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "restore", "--staged", "--source=HEAD~1", "file.txt" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void Restore_SkipsShortSourceSeparateValue()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "restore", "--staged", "-s", "HEAD~1", "file.txt" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ // ── commit: -m must not swallow a pathspec ──────────────────────
+
+ [TestCase]
+ public void Commit_ShortMessageSeparateValue_ThenPathspec()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "commit", "-m", "my message", "file.txt" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void Commit_CombinedShortMessage_BakedValue()
+ {
+ // -am "msg": -a is boolean, -m is value-taking and last, so it
+ // consumes "wip"; "file.txt" remains a pathspec.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "commit", "-am", "wip", "file.txt" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void Commit_ShortMessageBakedIntoCluster()
+ {
+ // -mwip: -m is value-taking but not last, so "wip" is its baked
+ // value; "file.txt" is a pathspec.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "commit", "-mwip", "file.txt" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void Commit_LongMessageEqualsValue_ThenPathspec()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "commit", "--message=hello world", "file.txt" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ // ── switch: no pathspecs at all ─────────────────────────────────
+
+ [TestCase]
+ public void Switch_TakesNoPathspecs()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "switch", "-c", "topic" });
+ result.Pathspecs.ShouldBeEmpty();
+ result.NamesPaths.ShouldBeFalse();
+ }
+
+ // ── stash push/save vs other subcommands ────────────────────────
+
+ [TestCase]
+ public void Stash_PushWithPaths()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "stash", "push", "out1/f.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out1/f.txt");
+ }
+
+ [TestCase]
+ public void Stash_PushDashDashPaths()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "stash", "push", "--", "out1/f.txt", "out2/g.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out1/f.txt", "out2/g.txt");
+ }
+
+ [TestCase]
+ public void Stash_PushSkipsMessageValue()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "stash", "push", "-m", "my stash", "out1/f.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out1/f.txt");
+ }
+
+ [TestCase]
+ public void Stash_PopHasNoPathspecs()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "stash", "pop" });
+ result.Pathspecs.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void Stash_BareIsNotPush()
+ {
+ // Bare "git stash" is an implicit push but names no paths.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "stash" });
+ result.Pathspecs.ShouldBeEmpty();
+ }
+
+ // ── diff / log / show: only paths after "--" count ──────────────
+
+ [TestCase]
+ public void Diff_RefsBeforeDashDashAreNotPathspecs()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "diff", "main", "feature", "--", "src/file.cs" });
+ result.Pathspecs.ShouldMatchInOrder("src/file.cs");
+ }
+
+ [TestCase]
+ public void Log_NoDashDash_NoPathspecs()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "log", "--oneline", "main" });
+ result.Pathspecs.ShouldBeEmpty();
+ }
+
+ // ── Unknown command: only "--" paths count ──────────────────────
+
+ [TestCase]
+ public void UnknownCommand_OnlyDashDashPaths()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "frobnicate", "arg1", "--", "path.txt" });
+ result.Pathspecs.ShouldMatchInOrder("path.txt");
+ }
+
+ // ── Injected --git-pid / --exit_code are filtered ───────────────
+
+ [TestCase]
+ public void GitPid_IsFiltered()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "file.txt", "--git-pid=1234" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void ExitCode_IsFilteredEvenPastDashDash()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "post-command", "add", "--", "file.txt", "--git-pid=1234", "--exit_code=0" });
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ // ── --pathspec-from-file / --pathspec-file-nul ──────────────────
+
+ [TestCase]
+ public void PathspecFromFile_EqualsForm()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "--pathspec-from-file=list.txt" });
+ result.PathspecFromFile.ShouldEqual("list.txt");
+ result.PathspecFileNul.ShouldBeFalse();
+ result.Failed.ShouldBeFalse();
+ result.NamesPaths.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void PathspecFromFile_SeparateArg()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "--pathspec-from-file", "list.txt" });
+ result.PathspecFromFile.ShouldEqual("list.txt");
+ }
+
+ [TestCase]
+ public void PathspecFileNul_SetsFlag()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "--pathspec-from-file=list.txt", "--pathspec-file-nul" });
+ result.PathspecFromFile.ShouldEqual("list.txt");
+ result.PathspecFileNul.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void PathspecFromFile_Stdin_Fails()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "--pathspec-from-file=-" });
+ result.Failed.ShouldBeTrue();
+ result.NamesPaths.ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void PathspecFromFile_WithInlinePaths()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "--pathspec-from-file=list.txt", "extra.txt" });
+ result.PathspecFromFile.ShouldEqual("list.txt");
+ result.Pathspecs.ShouldMatchInOrder("extra.txt");
+ }
+
+ // ── Global options: -C, --git-dir, --work-tree ──────────────────
+
+ [TestCase]
+ public void Global_DashC_SeparateValue()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "-C", "sub/dir", "add", "file.txt" });
+ result.ChangeDirectory.ShouldEqual("sub/dir");
+ result.Command.ShouldEqual("add");
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void Global_GitDir_SeparateValue()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "--git-dir", "/repo/.git", "add", "file.txt" });
+ result.GitDir.ShouldEqual("/repo/.git");
+ result.Command.ShouldEqual("add");
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void Global_GitDir_EqualsValue()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "--git-dir=/repo/.git", "add", "file.txt" });
+ result.GitDir.ShouldEqual("/repo/.git");
+ result.Command.ShouldEqual("add");
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void Global_WorkTree_AndConfig()
+ {
+ // -c key=value is a value-taking global; --work-tree consumes a value.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "-c", "core.autocrlf=false", "--work-tree", "/wt", "add", "file.txt" });
+ result.WorkTree.ShouldEqual("/wt");
+ result.Command.ShouldEqual("add");
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ [TestCase]
+ public void Global_BooleanPaginate_DoesNotConsumeCommand()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "--no-pager", "add", "file.txt" });
+ result.Command.ShouldEqual("add");
+ result.Pathspecs.ShouldMatchInOrder("file.txt");
+ }
+
+ // ── Mixed: everything at once ───────────────────────────────────
+
+ [TestCase]
+ public void Mixed_GlobalsOptionsValueOptionsPathspecs()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[]
+ {
+ "pre-command", "-C", "repo", "commit",
+ "--message", "a commit", "-a", "src/a.cs", "src/b.cs", "--git-pid=99",
+ });
+ result.ChangeDirectory.ShouldEqual("repo");
+ result.Command.ShouldEqual("commit");
+ result.Pathspecs.ShouldMatchInOrder("src/a.cs", "src/b.cs");
+ }
+
+ // ── Out-of-cone conflict resolution ─────────────────────────────
+ //
+ // When a rebase/merge conflicts on a file outside the sparse cone, the
+ // user resolves it by naming that path: "git add ", "git rm
+ // ", "git checkout --ours/--theirs ", "git restore
+ // ". Each must yield the path so the pre-command hook can widen
+ // the cone and let plain (non "--sparse") Git succeed.
+
+ [TestCase]
+ public void Add_OutOfConeConflictPath_NamesPath()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "out0005/f0001.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt");
+ result.NamesPaths.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void Rm_OutOfConeConflictPath_NamesPath()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "rm", "out0005/f0001.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt");
+ result.NamesPaths.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void Restore_ConflictPathWithOurs_NamesPath()
+ {
+ // restore treats every positional as a pathspec, so --ours is just a
+ // boolean flag; the path is still extracted.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "restore", "--ours", "out0005/f0001.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt");
+ result.NamesPaths.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void Checkout_DashDashConflictPath_NamesPath()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "--", "out0005/f0001.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt");
+ result.NamesPaths.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void Reset_DashDashConflictPath_NamesPath()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "reset", "--", "out0005/f0001.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt");
+ result.NamesPaths.ShouldBeTrue();
+ }
+
+ // ── checkout --ours / --theirs / -p suppress the leading ref ────
+ //
+ // "git checkout --ours " has no ref operand, so the first
+ // positional is a pathspec, not a branch. Without this, the parser
+ // would misread the conflicted path as a ref and never widen for it.
+
+ [TestCase]
+ public void Checkout_Ours_FirstPositionalIsPathspec()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "--ours", "out0005/f0001.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt");
+ result.NamesPaths.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void Checkout_Theirs_FirstPositionalIsPathspec()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "--theirs", "a.txt", "b.txt" });
+ result.Pathspecs.ShouldMatchInOrder("a.txt", "b.txt");
+ }
+
+ [TestCase]
+ public void Checkout_ShortPatch_FirstPositionalIsPathspec()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "-p", "out0005/f0001.txt" });
+ result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt");
+ }
+
+ [TestCase]
+ public void Checkout_Ours_FlagAfterPathIsStillSuppressing()
+ {
+ // Flag order is not fixed: the ref-suppressing flag is detected
+ // across the whole command, so the path is a pathspec even when the
+ // flag follows it.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "out0005/f0001.txt", "--theirs" });
+ result.Pathspecs.ShouldMatchInOrder("out0005/f0001.txt");
+ }
+
+ [TestCase]
+ public void Checkout_Ours_NoPath_NoPathspecs()
+ {
+ // "git checkout --ours" with no path still names nothing.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "--ours" });
+ result.Pathspecs.ShouldBeEmpty();
+ result.NamesPaths.ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void Checkout_LiteralOursPathAfterDashDash_IsPathspec()
+ {
+ // After "--", "--ours" is a literal path, not a ref-suppressing flag;
+ // the branch before "--" is still a ref.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "topic", "--", "--ours" });
+ result.Pathspecs.ShouldMatchInOrder("--ours");
+ }
+
+ // ── --end-of-options ────────────────────────────────────────────
+
+ [TestCase]
+ public void EndOfOptions_DashTokenIsPositional()
+ {
+ // "-topic" is a ref after --end-of-options, so it does not count as a
+ // short option cluster, and the next positional is a pathspec.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "--end-of-options", "-topic", "a.txt" });
+ result.Pathspecs.ShouldMatchInOrder("a.txt");
+ }
+
+ [TestCase]
+ public void EndOfOptions_DashTokenIsPathspecForPathCommands()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "add", "--end-of-options", "-weird.txt", "--all" });
+ result.Pathspecs.ShouldMatchInOrder("-weird.txt", "--all");
+ }
+
+ [TestCase]
+ public void EndOfOptions_DashDashStillSeparatesPathspecs()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "diff", "--end-of-options", "-topic", "--", "a.txt" });
+ result.Pathspecs.ShouldMatchInOrder("a.txt");
+ }
+
+ [TestCase]
+ public void EndOfOptions_LaterRefSuppressingFlagIsARef()
+ {
+ // "--ours" after --end-of-options is a ref name, so the leading ref
+ // operand is not suppressed.
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "checkout", "--end-of-options", "--ours", "a.txt" });
+ result.Pathspecs.ShouldMatchInOrder("a.txt");
+ }
+
+ // ── Other verbs in the table ────────────────────────────────────
+
+ [TestCase("stage")]
+ [TestCase("rm")]
+ [TestCase("mv")]
+ public void PathspecVerbs_EveryPositionalIsAPathspec(string verb)
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", verb, "-q", "a.txt", "dir/", "--git-pid=1" });
+ result.Pathspecs.ShouldMatchInOrder("a.txt", "dir/");
+ }
+
+ [TestCase("grep")]
+ [TestCase("blame")]
+ [TestCase("show")]
+ public void RefsOnlyVerbs_OnlyPathsAfterDashDash(string verb)
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", verb, "HEAD", "--stat", "a.txt", "--", "b.txt" });
+ result.Pathspecs.ShouldMatchInOrder("b.txt");
+ }
+
+ [TestCase]
+ public void Commit_FixupValueIsNotAPathspec()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "commit", "--fixup", "HEAD~1", "a.txt" });
+ result.Pathspecs.ShouldMatchInOrder("a.txt");
+ }
+
+ [TestCase]
+ public void Restore_ConflictEqualsValue_ThenPathspec()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "restore", "--conflict=diff3", "a.txt" });
+ result.Pathspecs.ShouldMatchInOrder("a.txt");
+ }
+
+ [TestCase]
+ public void Switch_DashDashPathsAreIgnored()
+ {
+ ParsedGitCommand result = GitPathspecParser.ParseHookArgs(
+ new[] { "pre-command", "switch", "-c", "topic", "--", "a.txt" });
+ result.Pathspecs.ShouldBeEmpty();
+ result.NamesPaths.ShouldBeFalse();
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/ConeCoverageTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/ConeCoverageTests.cs
new file mode 100644
index 000000000..d8fe1ee52
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Common/Sparse/ConeCoverageTests.cs
@@ -0,0 +1,165 @@
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using GVFS.Common.Sparse;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+
+namespace GVFS.UnitTests.Common.Sparse
+{
+ [TestFixture]
+ public class ConeCoverageTests
+ {
+ private const string Header = "/*\n!/*/\n";
+
+ [TestCase]
+ public void ParseReadsBackWhatTheWriterWrites()
+ {
+ ConePatternSet written = new ConePatternSet(
+ new[] { "A", "A/B", "W" },
+ new[] { "A/B/C", "W/x*y", "Q[1]" },
+ ignoreCase: false);
+
+ ConeCoverage.TryParseConeFile(ConeFileWriter.Serialize(written), ignoreCase: false, out ConePatternSet read).ShouldBeTrue();
+
+ read.ParentOnlyDirectories.ShouldMatchInOrder("A", "A/B", "W");
+ read.RecursiveDirectories.ShouldMatchInOrder("A/B/C", "W/x*y", "Q[1]");
+ read.IgnoreCase.ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void ParseAcceptsCrLfLineEndings()
+ {
+ ConeCoverage.TryParseConeFile("/*\r\n!/*/\r\n/A/\r\n", ignoreCase: true, out ConePatternSet read).ShouldBeTrue();
+ read.RecursiveDirectories.ShouldMatchInOrder("A");
+ read.IgnoreCase.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void ParseAcceptsHeaderOnly()
+ {
+ ConeCoverage.TryParseConeFile(Header, ignoreCase: false, out ConePatternSet read).ShouldBeTrue();
+ read.ParentOnlyDirectories.ShouldBeEmpty();
+ read.RecursiveDirectories.ShouldBeEmpty();
+ }
+
+ [TestCase(null)]
+ [TestCase("")]
+ [TestCase("/A/\n")]
+ [TestCase("/*\n/A/\n")]
+ [TestCase("!/*/\n/*\n/A/\n")]
+ [TestCase("/A/\n/*\n!/*/\n")]
+ [TestCase(Header + "!/A/*/\n")]
+ [TestCase(Header + "!/A/*/\n/A/\n")]
+ [TestCase(Header + "/A/\n!/A/*/\n!/A/*/\n")]
+ [TestCase(Header + "/A/\n!/A/*/\n/A/\n")]
+ [TestCase(Header + "/A*/\n")]
+ [TestCase(Header + "/A\\b/\n")]
+ [TestCase(Header + "/A\uFFFD/\n")]
+ [TestCase(Header + "/A/\n/A/\n")]
+ [TestCase(Header + "/A/./B/\n")]
+ [TestCase(Header + "/A\n")]
+ [TestCase(Header + "!/A/\n")]
+ public void ParseRejectsFilesThatGitDoesNotReadAsTheSameCone(string content)
+ {
+ ConeCoverage.TryParseConeFile(content, ignoreCase: false, out ConePatternSet read).ShouldBeFalse();
+ read.ShouldBeNull();
+ }
+
+ [TestCase]
+ public void ParseAcceptsDirectoriesWithoutTheirAncestors()
+ {
+ // Git's reader does not add the ancestors of a cone directory, and neither does
+ // ConePathMatcher, so both read this file with the same meaning.
+ ConeCoverage.TryParseConeFile(Header + "/A/B/\n/C/\n!/C/*/\n/C/D/E/\n", ignoreCase: false, out ConePatternSet read).ShouldBeTrue();
+ read.ParentOnlyDirectories.ShouldMatchInOrder("C");
+ read.RecursiveDirectories.ShouldMatchInOrder("A/B", "C/D/E");
+
+ ConeCoverage coverage = new ConeCoverage(read);
+ coverage.IsCovered("A/B/file.txt").ShouldBeTrue();
+ coverage.IsCovered("A/file.txt").ShouldBeFalse();
+ }
+
+ [TestCase("/*\n!/*/\n", true)]
+ [TestCase("\n/*\r\n\r\n!/*/\r\n/A/\n", true)]
+ [TestCase("# written by a tool\n/*\n# root files\n!/*/\n", true)]
+ [TestCase("/.gitattributes\r\n", false)]
+ [TestCase("!/*/\n/*\n", false)]
+ [TestCase("/*\n/A/\n!/*/\n", false)]
+ [TestCase("", false)]
+ [TestCase(null, false)]
+ public void HasConeHeaderNeedsTheHeaderLinesFirst(string content, bool expected)
+ {
+ ConeCoverage.HasConeHeader(content).ShouldEqual(expected);
+ }
+
+ [TestCase]
+ public void ParseSkipsCommentLinesAsGitDoes()
+ {
+ ConeCoverage.TryParseConeFile("# note\n" + Header + "# A is recursive\n/A/\n", ignoreCase: false, out ConePatternSet read).ShouldBeTrue();
+ read.RecursiveDirectories.ShouldMatchInOrder("A");
+ }
+
+ [TestCase]
+ public void DecodeSkipsOnlyAUtf8ByteOrderMark()
+ {
+ byte[] utf8 = Encoding.UTF8.GetBytes(Header + "/Ä/\n");
+ byte[] utf8WithBom = new byte[] { 0xEF, 0xBB, 0xBF }.Concat(utf8).ToArray();
+ ConeCoverage.DecodeConeFile(utf8WithBom).ShouldEqual(Header + "/Ä/\n");
+ ConeCoverage.DecodeConeFile(utf8).ShouldEqual(Header + "/Ä/\n");
+
+ byte[] utf16WithBom = Encoding.Unicode.GetPreamble().Concat(Encoding.Unicode.GetBytes(Header + "/A/\n")).ToArray();
+ ConeCoverage.HasConeHeader(ConeCoverage.DecodeConeFile(utf16WithBom)).ShouldBeFalse();
+ }
+
+ [TestCase]
+ public void ParseAppliesTheCaseRule()
+ {
+ string content = Header + "/A/\n/a/\n";
+
+ ConeCoverage.TryParseConeFile(content, ignoreCase: false, out ConePatternSet caseSensitive).ShouldBeTrue();
+ caseSensitive.RecursiveDirectories.ShouldMatchInOrder("A", "a");
+
+ ConeCoverage.TryParseConeFile(content, ignoreCase: true, out ConePatternSet caseInsensitive).ShouldBeFalse();
+ caseInsensitive.ShouldBeNull();
+ }
+
+ [TestCase("root.txt", true)]
+ [TestCase("A/file.txt", true)]
+ [TestCase("A/Other/file.txt", false)]
+ [TestCase("A/B/file.txt", true)]
+ [TestCase("A/B/deep/er/file.txt", true)]
+ [TestCase("Z/file.txt", false)]
+ [TestCase("A/B/", true)]
+ [TestCase("A/B/deep/", true)]
+ [TestCase("A/", false)]
+ [TestCase("A/Other/", false)]
+ [TestCase("Z/", false)]
+ public void IsCoveredFollowsTheCone(string path, bool expected)
+ {
+ CreateCoverage(ignoreCase: false).IsCovered(path).ShouldEqual(expected);
+ }
+
+ [TestCase(true, true)]
+ [TestCase(false, false)]
+ public void IsCoveredUsesTheCaseRule(bool ignoreCase, bool expected)
+ {
+ ConeCoverage coverage = CreateCoverage(ignoreCase);
+ coverage.IsCovered("a/b/file.txt").ShouldEqual(expected);
+ coverage.IsCovered("a/b/sub/").ShouldEqual(expected);
+ }
+
+ [TestCase]
+ public void GetUncoveredPathsKeepsInputOrder()
+ {
+ CreateCoverage(ignoreCase: false)
+ .GetUncoveredPaths(new[] { "Z/z.txt", "A/a.txt", "Y/", "A/B/b.txt", "A/" })
+ .ShouldMatchInOrder("Z/z.txt", "Y/", "A/");
+ }
+
+ private static ConeCoverage CreateCoverage(bool ignoreCase)
+ {
+ return new ConeCoverage(new ConePatternSet(new[] { "A" }, new[] { "A/B" }, ignoreCase));
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/Common/Sparse/ConePathspecResolverTests.cs b/GVFS/GVFS.UnitTests/Common/Sparse/ConePathspecResolverTests.cs
new file mode 100644
index 000000000..c72b9789a
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Common/Sparse/ConePathspecResolverTests.cs
@@ -0,0 +1,174 @@
+using System.Collections.Generic;
+using GVFS.Common.Sparse;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+
+namespace GVFS.UnitTests.Common.Sparse
+{
+ [TestFixture]
+ public class ConePathspecResolverTests
+ {
+ private const string Root = "C:/repo/src";
+
+ [TestCase]
+ public void RelativeFileResolvesAgainstBaseDirectory()
+ {
+ Resolve("C:/repo/src/A", "b.txt").ShouldMatchInOrder("A/b.txt");
+ }
+
+ [TestCase]
+ public void RelativeNestedFileKeepsFullPath()
+ {
+ Resolve("C:/repo/src/A", "B/c.txt").ShouldMatchInOrder("A/B/c.txt");
+ }
+
+ [TestCase]
+ public void TrailingSlashMarksRecursiveFolder()
+ {
+ Resolve("C:/repo/src/A", "sub/").ShouldMatchInOrder("A/sub/");
+ }
+
+ [TestCase]
+ public void FileAtRepoRootResolvesToBareName()
+ {
+ Resolve(Root, "root.txt").ShouldMatchInOrder("root.txt");
+ }
+
+ [TestCase]
+ public void DotSegmentsAreCollapsed()
+ {
+ Resolve("C:/repo/src/A", "./B/./c.txt").ShouldMatchInOrder("A/B/c.txt");
+ }
+
+ [TestCase]
+ public void DotDotClimbsToSibling()
+ {
+ Resolve("C:/repo/src/A", "../D/d.txt").ShouldMatchInOrder("D/d.txt");
+ }
+
+ [TestCase]
+ public void DotDotThatEscapesRootIsSkipped()
+ {
+ // From C:/repo/src/A, ../.. is C:/repo, which is above the worktree root.
+ Resolve("C:/repo/src/A", "../../outside.txt").ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void BackslashesAreNormalized()
+ {
+ Resolve("C:\\repo\\src\\A", "B\\c.txt").ShouldMatchInOrder("A/B/c.txt");
+ }
+
+ [TestCase]
+ public void AbsolutePathUnderRootIsMadeRelative()
+ {
+ Resolve("C:/repo/src", "C:/repo/src/X/y.txt").ShouldMatchInOrder("X/y.txt");
+ }
+
+ [TestCase]
+ public void AbsolutePathOutsideRootIsSkipped()
+ {
+ Resolve("C:/repo/src", "C:/other/z.txt").ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void RootPrefixMatchIsCaseInsensitiveButSuffixCasingIsKept()
+ {
+ Resolve("C:/repo/src", "C:/REPO/SRC/Keep/Case.txt").ShouldMatchInOrder("Keep/Case.txt");
+ }
+
+ [TestCase]
+ public void PathspecEqualToRootIsSkipped()
+ {
+ Resolve("C:/repo/src", "C:/repo/src").ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void MagicPathspecIsSkipped()
+ {
+ Resolve("C:/repo/src", ":(glob)**/*.txt").ShouldBeEmpty();
+ Resolve("C:/repo/src", ":/top.txt").ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void DuplicateResultsAreDeduplicated()
+ {
+ Resolve("C:/repo/src/A", "b.txt", "./b.txt").ShouldMatchInOrder("A/b.txt");
+ }
+
+ [TestCase]
+ public void EmptyAndNullPathspecsAreSkipped()
+ {
+ Resolve("C:/repo/src", string.Empty, null, "keep.txt").ShouldMatchInOrder("keep.txt");
+ }
+
+ [TestCase]
+ public void NullPathspecEnumerableYieldsEmpty()
+ {
+ ConePathspecResolver.ResolveToGitPaths(Root, Root, null).ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void FileAndFolderShapesAreDistinctEntries()
+ {
+ Resolve("C:/repo/src", "A", "A/").ShouldMatchInOrder("A", "A/");
+ }
+
+ [TestCase]
+ public void WildcardInFileNameIsKept()
+ {
+ Resolve("C:/repo/src/A", "*.cs", "B/f?le.txt").ShouldMatchInOrder("A/*.cs", "A/B/f?le.txt");
+ }
+
+ [TestCase]
+ public void WildcardInDirectorySegmentIsSkipped()
+ {
+ Resolve("C:/repo/src", "*/a.txt", "A/[bc]/d.txt", "A/B*/", "**/x.cs", "keep/a.txt")
+ .ShouldMatchInOrder("keep/a.txt");
+ }
+
+ [TestCase("C:/repo/src", null, "C:/repo/src")]
+ [TestCase("C:/repo/src", "", "C:/repo/src")]
+ [TestCase("C:/repo/src", "A/B/", "C:/repo/src/A/B")]
+ [TestCase("C:\\REPO\\src\\", "A\\B\\", "C:/repo/src/A/B")]
+ [TestCase("C:/repo/src/A", "B/", "C:/repo/src/A")]
+ public void PathspecBaseDirectoryAppliesPrefixOnlyAtWorktreeRoot(string hookCurrentDirectory, string gitPrefix, string expected)
+ {
+ string actual = ConePathspecResolver.GetPathspecBaseDirectory(hookCurrentDirectory, Root, gitPrefix);
+ actual.Replace('\\', '/').TrimEnd('/').ShouldEqual(expected);
+ }
+
+ [TestCase]
+ public void PrefixedBaseDirectoryResolvesRelativePathspecs()
+ {
+ string baseDirectory = ConePathspecResolver.GetPathspecBaseDirectory(Root, Root, "A/B/");
+ ConePathspecResolver.ResolveToGitPaths(baseDirectory, Root, new[] { "c.txt", "../d/" })
+ .ShouldMatchInOrder("A/B/c.txt", "A/d/");
+ }
+
+ [TestCase("../outside/")]
+ [TestCase("A/../../outside/")]
+ [TestCase("C:/Windows/")]
+ [TestCase("D:relative/")]
+ [TestCase("/rooted/")]
+ [TestCase("A//B/")]
+ public void PrefixThatCanLeaveTheWorktreeIsIgnored(string gitPrefix)
+ {
+ ConePathspecResolver.GetPathspecBaseDirectory(Root, Root, gitPrefix).ShouldEqual(Root);
+ }
+
+ [TestCase("D:dir/file.txt")]
+ [TestCase("A/stream.txt:alternate")]
+ [TestCase("A/line\nbreak.txt")]
+ [TestCase("A/frame\u0003end.txt")]
+ public void PathThatIsNotAValidGitPathIsSkipped(string pathspec)
+ {
+ Resolve("C:/repo/src", pathspec, "keep.txt").ShouldMatchInOrder("keep.txt");
+ }
+
+ private static IReadOnlyList Resolve(string baseDirectory, params string[] pathspecs)
+ {
+ return ConePathspecResolver.ResolveToGitPaths(baseDirectory, Root, pathspecs);
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj
index 42ed65d1d..68275bd68 100644
--- a/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj
+++ b/GVFS/GVFS.UnitTests/GVFS.UnitTests.csproj
@@ -28,6 +28,12 @@
+
+ Hooks\ConeManagementHook.cs
+
+
+ Hooks\ConeRequestOutcome.cs
+
Hooks\GitCommandLock.cs
diff --git a/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs b/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs
new file mode 100644
index 000000000..0ab4c827d
--- /dev/null
+++ b/GVFS/GVFS.UnitTests/Hooks/ConeManagementHookTests.cs
@@ -0,0 +1,417 @@
+using GVFS.Common.NamedPipes;
+using GVFS.Hooks;
+using GVFS.UnitTests.Mock.Common;
+using GVFS.Tests.Should;
+using NUnit.Framework;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Threading;
+
+namespace GVFS.UnitTests.Hooks
+{
+ [TestFixture]
+ public class ConeManagementHookTests
+ {
+ private const string Root = "C:\\repo\\src";
+ private const string Header = "/*\n!/*/\n";
+ private const string ConeWithRecursiveA = Header + "/A/\n";
+ private const string ConeWithParentOnlyA = Header + "/A/\n!/A/*/\n";
+ private const string GitPid = "--git-pid=1234";
+
+ // Tests that expect a reply use a long budget, so that a slow test machine cannot turn
+ // the reply into a timeout.
+ private const int ReplyBudgetMs = 30000;
+
+ private bool featureEnabled;
+ private int configReadCount;
+ private string coneFileContent;
+ private List createdClients;
+ private Func clientFactory;
+
+ [SetUp]
+ public void SetUp()
+ {
+ this.featureEnabled = true;
+ this.configReadCount = 0;
+ this.coneFileContent = ConeWithRecursiveA;
+ this.createdClients = new List();
+ this.clientFactory = () => ReplyWith(NamedPipeMessages.ConeManagement.SuccessResult);
+ }
+
+ [TestCase]
+ public void WidenWithFeatureOffSendsNothing()
+ {
+ this.featureEnabled = false;
+
+ this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.FeatureDisabled);
+
+ this.configReadCount.ShouldEqual(1);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase(null)]
+ [TestCase("/.gitattributes\r\n")]
+ [TestCase("/A/\n")]
+ public void WithoutConeModeFileNeitherHookReadsConfigOrSends(string content)
+ {
+ this.coneFileContent = content;
+
+ this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.NoConeFile);
+ this.Narrow("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.NoConeFile);
+
+ this.configReadCount.ShouldEqual(0);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase("status")]
+ [TestCase("commit", "-m", "message")]
+ [TestCase("checkout", "topic")]
+ public void WidenForCommandWithoutPathsDoesNotReadConfig(params string[] command)
+ {
+ this.Widen(command).ShouldEqual(ConeRequestOutcome.NoPathsNamed);
+
+ this.configReadCount.ShouldEqual(0);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenTreatsAnAmbiguousRefOrPathAsARef()
+ {
+ // Without "--", git diff can read "Z/z.txt" as a revision, so the parser does not
+ // count it as a path, and the hook does not widen.
+ this.Widen("diff", "HEAD", "Z/z.txt").ShouldEqual(ConeRequestOutcome.NoPathsNamed);
+ }
+
+ [TestCase("add", "A/a.txt")]
+ [TestCase("add", "A/deep/er/")]
+ [TestCase("rm", "root.txt")]
+ [TestCase("restore", "--staged", "A/a.txt", "root.txt")]
+ [TestCase("checkout", "HEAD", "--", "A/a.txt")]
+ public void WidenForInConePathsSendsNoRequest(params string[] command)
+ {
+ this.Widen(command).ShouldEqual(ConeRequestOutcome.SkippedInCone);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenUsesTheRepositoryCaseRule()
+ {
+ this.CreateHook(ignoreCase: true).TrySendWiden(BuildArgs("add", "a/a.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.SkippedInCone);
+ this.CreateHook(ignoreCase: false).TrySendWiden(BuildArgs("add", "a/a.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.Applied);
+ }
+
+ [TestCase]
+ public void WidenSendsOnlyTheOutOfConePaths()
+ {
+ this.Widen("add", "A/a.txt", "Z/z.txt", ":(glob)**/*.cs", ".").ShouldEqual(ConeRequestOutcome.Applied);
+
+ NamedPipeMessages.ConeManagement.WidenParameters parameters = this.GetSingleWidenRequest();
+ parameters.CommandId.ShouldEqual("1234");
+ parameters.Paths.ShouldMatchInOrder("Z/z.txt");
+ }
+
+ [TestCase("A/")]
+ [TestCase("Z/")]
+ public void WidenForFolderNeedsTheWholeSubtreeInCone(string folder)
+ {
+ this.coneFileContent = ConeWithParentOnlyA;
+
+ this.Widen("add", folder).ShouldEqual(ConeRequestOutcome.Applied);
+ this.GetSingleWidenRequest().Paths.ShouldMatchInOrder(folder);
+ }
+
+ [TestCase]
+ public void WidenResolvesRelativePathsAgainstGitPrefix()
+ {
+ this.coneFileContent = ConeWithParentOnlyA;
+
+ this.CreateHook(gitPrefix: "B/").TrySendWiden(BuildArgs("add", "x.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.Applied);
+ this.GetSingleWidenRequest().Paths.ShouldMatchInOrder("B/x.txt");
+
+ this.createdClients.Clear();
+ this.CreateHook(gitPrefix: "A/").TrySendWiden(BuildArgs("add", "x.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.SkippedInCone);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase(Header + "/A*/\n", false)]
+ [TestCase(Header + "/A/\n/a/\n", true)]
+ public void WidenSendsEveryPathWhenTheConeFileCannotBeTrusted(string content, bool ignoreCase)
+ {
+ this.coneFileContent = content;
+
+ this.CreateHook(ignoreCase: ignoreCase).TrySendWiden(BuildArgs("add", "A/a.txt"), ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.Applied);
+ this.GetSingleWidenRequest().Paths.ShouldMatchInOrder("A/a.txt");
+ }
+
+ [TestCase("add", "C:\\other\\file.txt")]
+ [TestCase("add", "../outside.txt")]
+ [TestCase("add", "A/*/x.txt")]
+ [TestCase("add", "Z/frame\u0003end.txt")]
+ [TestCase("add", ":(glob)**/*.cs")]
+ [TestCase("add", ".")]
+ [TestCase("add", "--pathspec-from-file=list.txt")]
+ public void WidenSendsNothingForPathsWithoutAConeEntry(params string[] command)
+ {
+ this.Widen(command).ShouldEqual(ConeRequestOutcome.NoResolvablePaths);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase("-C", "sub")]
+ [TestCase("--git-dir=other")]
+ [TestCase("--work-tree", "other")]
+ public void WidenSendsNothingWhenAGlobalOptionChangesTheRepository(params string[] globalOptions)
+ {
+ List command = new List(globalOptions) { "add", "Z/z.txt" };
+
+ this.Widen(command.ToArray()).ShouldEqual(ConeRequestOutcome.NoResolvablePaths);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenForStashSendsNoRequest()
+ {
+ this.Widen("stash", "push", "--", "Z/z.txt").ShouldEqual(ConeRequestOutcome.SkippedStash);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase(NamedPipeMessages.UnknownRequest)]
+ [TestCase(NamedPipeMessages.MountNotReadyResult)]
+ [TestCase(NamedPipeMessages.ConeManagement.FailureResult)]
+ [TestCase(NamedPipeMessages.ConeManagement.NotEnabledResult)]
+ public void WidenWithNonSuccessReplyLetsGitRun(string responseHeader)
+ {
+ this.clientFactory = () => ReplyWith(responseHeader);
+
+ this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.Rejected);
+ this.createdClients[0].Requests.Count.ShouldEqual(1);
+ }
+
+ [TestCase]
+ public void WidenWithoutMountLetsGitRun()
+ {
+ this.clientFactory = NoMount;
+
+ this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.MountUnavailable);
+ this.createdClients[0].Requests.ShouldBeEmpty();
+ this.createdClients[0].ConnectTimeoutMs.ShouldEqual(NamedPipeMessages.ConeManagement.ConnectTimeoutMs);
+ this.createdClients[0].Disposed.ShouldBeTrue();
+ }
+
+ [TestCase]
+ public void WidenWaitsForTheReplyAfterTheWaitBudget()
+ {
+ ManualResetEventSlim releaseReply = new ManualResetEventSlim(initialState: false);
+ this.clientFactory = () => ReplyAfter(releaseReply);
+ using (Timer releaseLater = new Timer(_ => releaseReply.Set(), null, dueTime: 300, period: Timeout.Infinite))
+ {
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ this.CreateHook().TrySendWiden(BuildArgs("add", "Z/z.txt"), waitBudgetMs: 50, replyCeilingMs: ReplyBudgetMs)
+ .ShouldEqual(ConeRequestOutcome.Applied);
+ stopwatch.Stop();
+
+ (stopwatch.ElapsedMilliseconds >= 250).ShouldBeTrue("The hook must wait for the reply after it sent the widen.");
+ }
+ }
+
+ [TestCase]
+ public void WidenWithoutAReplyLetsGitRunAtTheReplyCeiling()
+ {
+ // The event is not disposed, because the abandoned request task still waits on it.
+ ManualResetEventSlim releaseReply = new ManualResetEventSlim(initialState: false);
+ this.clientFactory = () => ReplyAfter(releaseReply);
+
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ this.CreateHook().TrySendWiden(BuildArgs("add", "Z/z.txt"), waitBudgetMs: ReplyBudgetMs, replyCeilingMs: 50)
+ .ShouldEqual(ConeRequestOutcome.ReplyTimedOut);
+ stopwatch.Stop();
+ releaseReply.Set();
+
+ (stopwatch.ElapsedMilliseconds < 5000).ShouldBeTrue("The hook must not wait for the reply after the ceiling ends.");
+ }
+
+ [TestCase]
+ public void WidenThatCannotSendInTheWaitBudgetLetsGitRunAndNeverSends()
+ {
+ ManualResetEventSlim releaseConnect = new ManualResetEventSlim(initialState: false);
+ this.clientFactory = () => new MockNamedPipeClient
+ {
+ ConnectCallback = () => releaseConnect.Wait(),
+ Response = new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null),
+ };
+
+ Stopwatch stopwatch = Stopwatch.StartNew();
+ this.CreateHook().TrySendWiden(BuildArgs("add", "Z/z.txt"), waitBudgetMs: 50, replyCeilingMs: ReplyBudgetMs)
+ .ShouldEqual(ConeRequestOutcome.TimedOut);
+ stopwatch.Stop();
+ (stopwatch.ElapsedMilliseconds < 5000).ShouldBeTrue("The hook must not wait for the reply ceiling when it did not send.");
+
+ // The test lets the abandoned task connect, then checks that the task did not send.
+ releaseConnect.Set();
+ SpinWait.SpinUntil(() => this.createdClients.Count == 1 && this.createdClients[0].Disposed, 5000).ShouldBeTrue();
+ this.createdClients[0].Requests.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void WidenThatThrowsLetsGitRun()
+ {
+ this.clientFactory = () => new MockNamedPipeClient { SendError = new BrokenPipeException("send failed", null) };
+ this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.Failed);
+
+ this.clientFactory = () => throw new InvalidOperationException("no client");
+ this.Widen("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.Failed);
+
+ ConeManagementHook throwingConfig = new ConeManagementHook(
+ (out bool ignoreCase) => throw new InvalidOperationException("config"),
+ () => this.coneFileContent,
+ () => throw new InvalidOperationException("no client"),
+ Root,
+ () => Root,
+ null,
+ null);
+ throwingConfig.TrySendWiden(BuildArgs("add", "Z/z.txt")).ShouldEqual(ConeRequestOutcome.Failed);
+ throwingConfig.TrySendNarrow(BuildArgs("add", "Z/z.txt")).ShouldEqual(ConeRequestOutcome.Failed);
+ }
+
+ [TestCase]
+ public void NarrowWithFeatureOffSendsNothing()
+ {
+ this.featureEnabled = false;
+
+ this.Narrow("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.FeatureDisabled);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void NarrowSendsTheGitProcessIdFromThePostCommandArguments()
+ {
+ string[] postCommandArgs = new[] { "post-command", "add", "A/a.txt", "--git-pid=1234", "--exit_code=0" };
+
+ this.CreateHook().TrySendNarrow(postCommandArgs, ReplyBudgetMs).ShouldEqual(ConeRequestOutcome.Applied);
+
+ NamedPipeMessages.Message request = this.createdClients[0].Requests[0];
+ request.Header.ShouldEqual(NamedPipeMessages.ConeManagement.NarrowRequest);
+ NamedPipeMessages.ConeManagement.NarrowParameters.TryParse(request.Body, out NamedPipeMessages.ConeManagement.NarrowParameters parameters).ShouldBeTrue();
+ parameters.CommandId.ShouldEqual("1234");
+ }
+
+ [TestCase]
+ public void NarrowSkipsCommandsThatCannotWiden()
+ {
+ this.Narrow("status").ShouldEqual(ConeRequestOutcome.NoPathsNamed);
+ this.Narrow("stash", "push", "--", "Z/z.txt").ShouldEqual(ConeRequestOutcome.SkippedStash);
+ this.createdClients.ShouldBeEmpty();
+ }
+
+ [TestCase]
+ public void NarrowFailuresLetGitFinish()
+ {
+ this.clientFactory = NoMount;
+ this.Narrow("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.MountUnavailable);
+
+ this.clientFactory = () => ReplyWith(NamedPipeMessages.UnknownRequest);
+ this.Narrow("add", "Z/z.txt").ShouldEqual(ConeRequestOutcome.Rejected);
+
+ ManualResetEventSlim releaseReply = new ManualResetEventSlim(initialState: false);
+ this.clientFactory = () => ReplyAfter(releaseReply);
+ this.CreateHook().TrySendNarrow(BuildArgs("add", "Z/z.txt"), waitBudgetMs: 50).ShouldEqual(ConeRequestOutcome.TimedOut);
+ releaseReply.Set();
+ }
+
+ [TestCase]
+ public void FailedRequestsWriteADiagnostic()
+ {
+ List messages = new List();
+ this.clientFactory = () => ReplyWith(NamedPipeMessages.UnknownRequest);
+
+ this.CreateHook(trace: messages.Add).TrySendWiden(BuildArgs("add", "Z/z.txt"), ReplyBudgetMs);
+ this.CreateHook(trace: messages.Add).TrySendNarrow(BuildArgs("add", "Z/z.txt"), ReplyBudgetMs);
+
+ messages.ShouldMatchInOrder("widen not applied: Rejected", "narrow not applied: Rejected");
+ }
+
+ [TestCase(new[] { "pre-command", "add", "a.txt", "--git-pid=77" }, "77")]
+ [TestCase(new[] { "post-command", "add", "a.txt", "--git-pid=77", "--exit_code=0" }, "77")]
+ [TestCase(new[] { "pre-command", "diff", "--", "--git-pid=99", "--git-pid=77" }, "77")]
+ [TestCase(new[] { "pre-command", "add", "a.txt", "--git-pid=12a" }, "")]
+ [TestCase(new[] { "pre-command", "add", "a.txt" }, "")]
+ public void CommandIdIsTheGitProcessId(string[] args, string expected)
+ {
+ ConeManagementHook.GetCommandId(args).ShouldEqual(expected);
+ }
+
+ private static string[] BuildArgs(params string[] command)
+ {
+ List args = new List { "pre-command" };
+ args.AddRange(command);
+ args.Add(GitPid);
+ return args.ToArray();
+ }
+
+ private ConeRequestOutcome Widen(params string[] command)
+ {
+ return this.CreateHook().TrySendWiden(BuildArgs(command), ReplyBudgetMs);
+ }
+
+ private ConeRequestOutcome Narrow(params string[] command)
+ {
+ return this.CreateHook().TrySendNarrow(BuildArgs(command), ReplyBudgetMs);
+ }
+
+ private ConeManagementHook CreateHook(string gitPrefix = null, bool ignoreCase = false, Action trace = null)
+ {
+ return new ConeManagementHook(
+ (out bool readIgnoreCase) =>
+ {
+ this.configReadCount++;
+ readIgnoreCase = ignoreCase;
+ return this.featureEnabled;
+ },
+ () => this.coneFileContent,
+ () =>
+ {
+ MockNamedPipeClient client = this.clientFactory();
+ this.createdClients.Add(client);
+ return client;
+ },
+ Root,
+ () => Root,
+ gitPrefix,
+ trace);
+ }
+
+ private NamedPipeMessages.ConeManagement.WidenParameters GetSingleWidenRequest()
+ {
+ this.createdClients.Count.ShouldEqual(1);
+ this.createdClients[0].Requests.Count.ShouldEqual(1);
+
+ NamedPipeMessages.Message request = this.createdClients[0].Requests[0];
+ request.Header.ShouldEqual(NamedPipeMessages.ConeManagement.WidenRequest);
+ NamedPipeMessages.ConeManagement.WidenParameters.TryParse(request.Body, out NamedPipeMessages.ConeManagement.WidenParameters parameters).ShouldBeTrue();
+ return parameters;
+ }
+
+ private static MockNamedPipeClient ReplyWith(string responseHeader)
+ {
+ return new MockNamedPipeClient { Response = new NamedPipeMessages.Message(responseHeader, null) };
+ }
+
+ private static MockNamedPipeClient ReplyAfter(ManualResetEventSlim releaseReply)
+ {
+ return new MockNamedPipeClient
+ {
+ ReadResponseCallback = () =>
+ {
+ releaseReply.Wait();
+ return new NamedPipeMessages.Message(NamedPipeMessages.ConeManagement.SuccessResult, null);
+ },
+ };
+ }
+
+ private static MockNamedPipeClient NoMount()
+ {
+ return new MockNamedPipeClient { ConnectError = new IOException("no mount") };
+ }
+ }
+}
diff --git a/GVFS/GVFS.UnitTests/Mock/Common/MockNamedPipeClient.cs b/GVFS/GVFS.UnitTests/Mock/Common/MockNamedPipeClient.cs
index dd2fad641..521b28655 100644
--- a/GVFS/GVFS.UnitTests/Mock/Common/MockNamedPipeClient.cs
+++ b/GVFS/GVFS.UnitTests/Mock/Common/MockNamedPipeClient.cs
@@ -1,5 +1,6 @@
using GVFS.Common.NamedPipes;
using System;
+using System.Collections.Generic;
namespace GVFS.UnitTests.Mock.Common
{
@@ -10,16 +11,19 @@ public MockNamedPipeClient() : base("mock-pipe")
}
public Exception ConnectError { get; set; }
+ public Action ConnectCallback { get; set; }
public Exception SendError { get; set; }
public Exception ReadError { get; set; }
public Func ReadResponseCallback { get; set; }
public NamedPipeMessages.Message Response { get; set; }
public bool Disposed { get; private set; }
public int ConnectTimeoutMs { get; private set; }
+ public List Requests { get; } = new List();
public override bool Connect(int timeoutMilliseconds, out Exception error)
{
this.ConnectTimeoutMs = timeoutMilliseconds;
+ this.ConnectCallback?.Invoke();
error = this.ConnectError;
return error == null;
}
@@ -30,6 +34,8 @@ public override void SendRequest(NamedPipeMessages.Message message)
{
throw this.SendError;
}
+
+ this.Requests.Add(message);
}
public override NamedPipeMessages.Message ReadResponse()