Skip to content

Fix NullReferenceException when cloning into a non-empty directory - #2065

Closed
Tyrie Vella (tyrielv) wants to merge 1 commit into
microsoft:masterfrom
tyrielv:tyrielv/fix-clone-nonempty-nre
Closed

Tyrie Vella (tyrielv) wants to merge 1 commit into
microsoft:masterfrom
tyrielv:tyrielv/fix-clone-nonempty-nre

Conversation

@tyrielv

@tyrielv Tyrie Vella (tyrielv) commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

gvfs clone <url> <target> into a non-empty <target> directory throws an unhandled NullReferenceException instead of reporting the expected error:

Cannot clone @ <target>: System.NullReferenceException: Object reference not set to an instance of an object.
   at GVFS.CommandLine.CloneVerb.Execute() + 0x9fc

v1.0 behavior (expected):

Cannot clone @ <target>
Error: Clone directory '<target>' exists and is not empty

Root cause

CloneVerb.Execute() unconditionally read enlistment.WorkingDirectoryBackingRoot to determine trustPackIndexes, even when TryCreateEnlistment failed (e.g. because the target directory already exists and is not empty). In that failure path enlistment is null, so the dereference throws.

Fix

Extracted the lookup into internal bool GetTrustPackIndexes(ITracer, Result, GVFSEnlistment), which only touches enlistment when cloneResult.Success is true; otherwise it returns the default without dereferencing enlistment. Delegates to the shared LibGit2Repo.GetConfigBoolOrDefault helper added in #2066.

Testing

GVFS.UnitTests.CommandLine.CloneVerbTests:

  • TryCreateEnlistmentFailsWithoutEnlistmentWhenTargetDirectoryIsNotEmpty — confirms the failure precondition (null enlistment on non-empty target dir).
  • TryCreateEnlistmentDoesNotFailForEmptyTargetDirectory — boundary case: an empty target directory does not trigger the "exists and is not empty" error.
  • TryCreateEnlistmentReportsNormalizedPathWhenItDiffersFromFullPath — covers the divergent full-vs-normalized-path error message branch.
  • GetTrustPackIndexesDoesNotThrowWhenCloneFailedAndEnlistmentIsNull — the actual regression test: drives the exact failed-clone/null-enlistment composition that used to throw. Verified by temporarily removing the cloneResult.Success gate — the test failed with the original NullReferenceException, then passed again once the gate was restored.

Review

Reviewed with an internal 6-lens review-swarm pass. The main finding: an earlier draft of the regression test only proved TryCreateEnlistment's own contract (already true pre-fix) without exercising the actual Execute() null-dereference — addressed by the extraction and new test above.

Validation

Full unit test suite: 895 passed, 0 failed (11 pre-existing skips, unrelated to this change).

@tyrielv
Tyrie Vella (tyrielv) marked this pull request as ready for review July 15, 2026 18:37
@tyrielv
Tyrie Vella (tyrielv) force-pushed the tyrielv/fix-clone-nonempty-nre branch from 37377d1 to f4a4a25 Compare July 15, 2026 19:11
@tyrielv
Tyrie Vella (tyrielv) marked this pull request as draft July 15, 2026 19:55
auto-merge was automatically disabled July 15, 2026 19:55

Pull request was converted to draft

@tyrielv
Tyrie Vella (tyrielv) force-pushed the tyrielv/fix-clone-nonempty-nre branch from f4a4a25 to 72ce378 Compare August 7, 2026 22:19
@tyrielv
Tyrie Vella (tyrielv) marked this pull request as ready for review August 7, 2026 22:47
@tyrielv
Tyrie Vella (tyrielv) force-pushed the tyrielv/fix-clone-nonempty-nre branch from 72ce378 to 332b4fc Compare August 7, 2026 22:53
@tyrielv
Tyrie Vella (tyrielv) force-pushed the tyrielv/fix-clone-nonempty-nre branch from 332b4fc to 7a42e95 Compare August 27, 2026 17:06
@ShiningMassXAcc

Copy link
Copy Markdown
Member

Now that #2066 has merged to master, could you rebase this branch onto master? The diff still carries the #2066 LibGit2Repo config-lookup helper (the "Share transient libgit2 config lookup helper" commit), so a rebase should reduce this to the single fix commit described in the note. I'd like that clean single-commit diff before I give final approval.

`gvfs clone <url> <target>` into a non-empty <target> directory throws an
unhandled NullReferenceException instead of reporting the expected error:

  Cannot clone @ <target>: System.NullReferenceException: Object
  reference not set to an instance of an object.
     at GVFS.CommandLine.CloneVerb.Execute() + 0x9fc

v1.0 behavior (expected):

  Cannot clone @ <target>
  Error: Clone directory '<target>' exists and is not empty

Root cause: CloneVerb.Execute() unconditionally read
enlistment.WorkingDirectoryBackingRoot to determine trustPackIndexes, even
when TryCreateEnlistment failed (e.g. because the target directory already
exists and is not empty). In that failure path enlistment is null, so the
dereference throws.

Extract the lookup into internal bool GetTrustPackIndexes(ITracer, Result,
GVFSEnlistment), which only touches enlistment when cloneResult.Success is
true; otherwise it returns the default without dereferencing enlistment.
Delegates to the shared LibGit2Repo.GetConfigBoolOrDefault helper.

Widen TryCreateEnlistment/Result from private to internal so they are
directly unit-testable (GVFS assembly already grants InternalsVisibleTo to
GVFS.UnitTests).

Add GVFS.UnitTests.CommandLine.CloneVerbTests:
- TryCreateEnlistmentFailsWithoutEnlistmentWhenTargetDirectoryIsNotEmpty:
  confirms the failure precondition (null enlistment on non-empty target
  dir).
- TryCreateEnlistmentDoesNotFailForEmptyTargetDirectory: boundary case, an
  empty target directory does not trigger the "exists and is not empty"
  error.
- TryCreateEnlistmentReportsNormalizedPathWhenItDiffersFromFullPath: covers
  the divergent full-vs-normalized-path error message branch.
- GetTrustPackIndexesDoesNotThrowWhenCloneFailedAndEnlistmentIsNull: the
  actual regression test, driving the exact failed-clone/null-enlistment
  composition that used to throw. Verified by temporarily removing the
  cloneResult.Success gate: the test failed with the original
  NullReferenceException, then passed again once the gate was restored.

Reviewed with an internal 6-lens review-swarm pass; the main finding was
that an earlier draft of the regression test only proved
TryCreateEnlistment's own contract (already true pre-fix) without
exercising the actual Execute() null-dereference, addressed by the
extraction and test above.

Full unit test suite: 895 passed, 0 failed, 11 skipped (pre-existing,
unrelated).

Assisted-by: Claude Opus 4.8
Signed-off-by: Tyrie Vella <[email protected]>

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review — PR #2065: Fix NullReferenceException when cloning into a non-empty directory

Recommendation: request changes (not a blocker on correctness — the change is safe — but the PR
no longer does what it says, and one of the four new tests doesn't test anything).

1. Blocking: after the rebase, the NRE is already fixed on master

You rebased onto master as I asked, and that rebase removed the actual fix. This branch's
merge base is now 92020a4f, and at that commit CloneVerb.Execute() already reads:

if (!cloneResult.Success)
{
    tracer.RelatedError(cloneResult.ErrorMessage);
}
else
{
    trustPackIndexes = LibGit2Repo.GetConfigBoolOrDefault(
        tracer,
        enlistment.WorkingDirectoryBackingRoot,
        ...);
}

enlistment is only dereferenced when cloneResult.Success is true, so the crash described in
the PR body cannot happen on the base branch.

The NRE was real — in the pre-#2066 shape the config read sat outside the if:

if (!cloneResult.Success)
{
    tracer.RelatedError(cloneResult.ErrorMessage);
}

using (var repo = new LibGit2RepoInvoker(tracer, enlistment.WorkingDirectoryBackingRoot))  // <- NRE

but 6ba0bb2a ("Share transient libgit2 config lookup helper", #2066, merged 2026-08-27)
introduced both the else gate and the trustPackIndexes = TrustPackIndexesDefault initializer,
which is exactly the fix. So #2066 already shipped it.

What's left in this PR is a behaviour-preserving refactor plus tests. That's fine to take, but
please retitle/rewrite the description accordingly — and drop the "This gating is what fixes the
NullReferenceException regression" sentence from the GetTrustPackIndexes XML doc, which will
mislead the next reader into thinking the gate originated here.

2. Blocking: TryCreateEnlistmentDoesNotFailForEmptyTargetDirectory is vacuous

I instrumented the test and ran it. For the empty-directory case it observes:

Success=False, ErrorMessage=<Could not find git.exe.  Ensure that Git is installed.>, enlistment=null

MockGitInstallation.GetInstalledGitBinPath() returns null, so TryCreateEnlistment bails at the
GitIsNotInstalledError branch and never reaches enlistment creation. The test is named
"DoesNotFail" but the call does fail; the only assertion
(DoesNotContain("exists and is not empty", ...)) is trivially satisfied by any unrelated error, so
it would keep passing even if the empty-directory boundary broke completely.

It's also fragile in a non-obvious way: the only reason it doesn't crash is the early null
return. If MockGitInstallation ever returns a path, the next statement is CheckGVFSHooksVersion,
and MockPlatform.TryGetGVFSHooksVersion throws NotSupportedException (and past that,
ReportErrorAndExit would tear down the process).

Either assert the actual contract (result.ErrorMessage.ShouldEqual(GVFSConstants.GitIsNotInstalledError),
i.e. "the empty directory was accepted and we moved past the emptiness check"), or drop the test.

3. The "regression test" doesn't guard the regression

GetTrustPackIndexesDoesNotThrowWhenCloneFailedAndEnlistmentIsNull exercises the extracted helper,
not the call site that used to crash. I verified this by mutation: I restored Execute() to the
exact pre-#2066 buggy form (unconditional enlistment.WorkingDirectoryBackingRoot deref) while
leaving GetTrustPackIndexes in place, rebuilt, and re-ran the fixture:

Overall result: Passed
Test Count: 4, Passed: 4, Failed: 0

So the test cannot fail for the bug it names. The PR body is candid that Execute() isn't unit
testable, which is true — but then the honest framing is "coverage for the new helper", not a
regression guard. Worth saying so in the comment above the test.

4. Non-blocking

  • GetTrustPackIndexes only reads cloneResult.Success. Taking a bool instead of a Result
    would avoid widening the nested Result class from private to internal purely for test
    reachability.
  • GetTrustPackIndexes doesn't touch instance state and could be internal static.
  • Setup/TearDown create and delete a real temp directory per test. That's fine here, but
    GVFS.UnitTests is otherwise mock-based; a short comment on why real I/O is needed would help.

Verification performed

  • Built GVFS.UnitTests at d487f91b (x64 Debug, net10.0-windows, real vcpkg libgit2): 0 warnings,
    0 errors.
  • Full unit suite: 986 tests, 975 passed, 0 failed, 11 skipped.
  • CloneVerbTests alone: 4/4 passed.
  • Mutation A (restore buggy Execute()): 4/4 still passed — see §3.
  • Probe of the empty-directory case: see §2.
  • Confirmed git log -S that 6ba0bb2a is the sole origin of the else gate and the
    TrustPackIndexesDefault initializer.

@tyrielv

Copy link
Copy Markdown
Contributor Author

Closing without merging. Nathan Baird (@ShiningMassXAcc)'s review caught that the actual fix for the NullReferenceException landed in #2066 (the else gate added around the trustPackIndexes config read in 6ba0bb2a), which already merged to master. What remained here after rebasing onto master was a behavior-preserving refactor (extracting GetTrustPackIndexes) plus test coverage, two of which don't hold up under mutation testing as regression guards.

Thanks for the thorough review — no further action needed on this one.

auto-merge was automatically disabled September 24, 2026 15:53

Pull request was closed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants