stash apply: report status correctly even in a worktree's subdirectory

When Git wants to spawn a child Git process inside a worktree's subdirectory while `GIT_DIR` is set, we need to take care of specifying the work tree's top-level directory explicitly because it cannot be discovered: the current directory is _not_ the top-level directory of the work tree, and neither is it inside the parent directory of `GIT_DIR`. This fixes the problem where `git stash apply` would report pretty much everything deleted or untracked when run inside a worktree's subdirectory. To make sure that we do not introduce the "reverse problem", i.e. when `GIT_WORK_TREE` is defined but `GIT_DIR` is not, we simply make sure that both are set. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Johannes Schindelin committed Oct 4, 2019 at 05:30 UTC dfd557c9783433bd6273987982f0665d99e52df2
2 files changed +31
builtin/stash.c
+4
@@ -497,6 +497,10 @@ static int do_apply_stash(const char *prefix, struct stash_info *info,
497 */
498 cp.git_cmd = 1;
499 cp.dir = prefix;
500 + argv_array_pushf(&cp.env_array, GIT_WORK_TREE_ENVIRONMENT"=%s",
501 + absolute_path(get_git_work_tree()));
502 + argv_array_pushf(&cp.env_array, GIT_DIR_ENVIRONMENT"=%s",
503 + absolute_path(get_git_dir()));
504 argv_array_push(&cp.args, "status");
505 run_command(&cp);
506 }
t/t3908-stash-in-worktree.sh new
+27
@@ -0,0 +1,27 @@
1 +#!/bin/sh
2 +#
3 +# Copyright (c) 2019 Johannes E Schindelin
4 +#
5 +
6 +test_description='Test git stash in a worktree'
7 +
8 +. ./test-lib.sh
9 +
10 +test_expect_success 'setup' '
11 + test_commit initial &&
12 + git worktree add wt &&
13 + test_commit -C wt in-worktree
14 +'
15 +
16 +test_expect_success 'apply in subdirectory' '
17 + mkdir wt/subdir &&
18 + (
19 + cd wt/subdir &&
20 + echo modified >../initial.t &&
21 + git stash &&
22 + git stash apply >out
23 + ) &&
24 + grep "\.\.\/initial\.t" wt/subdir/out
25 +'
26 +
27 +test_done