Subject: [PATCH 1/2] worktree setup: return to original cwd if prefix is set NULL

From: Nguyễn Thái Ngọc Duy <[email-masked]>
Date: Sat, 24 Jul 2010 02:47:52 +0700

Commit a672ea6 (rehabilitate 'git index-pack' inside the object
store - 2008-10-20) worked around a fault in
setup_git_directory_gently(). When walking up from inside a git
repository, we will return NULL as prefix.

Prefix and cwd should be consistent. That is if cwd is moved, prefix
reflects that. If prefix is NULL, cwd is unmoved. In this case, to
retain current behavior, we move cwd back, with an eye on gitdir
because gitdir may be relative to cwd.

Signed-off-by: Nguyễn Thái Ngọc Duy <[email-masked]>
---
  On Sat, Jul 24, 2010 at 01:16:00AM +0000, Ævar Arnfjörð Bjarmason wrote:
  > On Sat, Jul 24, 2010 at 00:50, Nguyen Thai Ngoc Duy <[email-masked]> wrote:
  > 
  > > I don't want to pollute the repo early. If the test fails, rm would not be run.
  > 
  > Sure, I'm just asking if there's a reason to run rm in this
  > case. Because usually we defer the whole rm to be done inside
  > test-lib.sh once the entire test completes.
  
  "rm" removed. The rest of the tests do not seem to care whatelse in objects..

 setup.c             |    7 +++++++
 t/t1501-worktree.sh |   20 ++++++++++++++++++++
 2 files changed, 27 insertions(+), 0 deletions(-)

diff --git a/setup.c b/setup.c
index 87c21f0..33eb253 100644
--- a/setup.c
+++ b/setup.c
@@ -413,6 +413,13 @@ const char *setup_git_directory_gently(int *nongit_ok)
 			if (!work_tree_env)
 				inside_work_tree = 0;
 			if (offset != len) {
+				/*
+				 * The returned prefix in this code path is NULL
+				 * chdir() back to match NULL prefix, i.e. unmoved cwd
+				 */
+				if (chdir(cwd))
+					die_errno("Cannot come back to cwd");
+
 				root_len = offset_1st_component(cwd);
 				cwd[offset > root_len ? offset : root_len] = '\0';
 				set_git_dir(cwd);
diff --git a/t/t1501-worktree.sh b/t/t1501-worktree.sh
index bd8b607..a024056 100755
--- a/t/t1501-worktree.sh
+++ b/t/t1501-worktree.sh
@@ -33,6 +33,26 @@ mkdir -p work/sub/dir || exit 1
 mkdir -p work2 || exit 1
 mv .git repo.git || exit 1
 
+cat >repo.git/objects/patch <<\EOF
+diff one one
+--- one
++++ one
+@@ -1 +1,2 @@
+ 1
++2
+EOF
+
+test_expect_success 'cwd is unchanged when prefix is NULL (from within a repo)' '
+	(
+		cd repo.git/objects &&
+		echo 1 > one &&
+		cp one expected &&
+		echo 2 >> expected &&
+		git apply patch &&
+		test_cmp expected one
+	)
+'
+
 say "core.worktree = relative path"
 GIT_DIR=repo.git
 GIT_CONFIG="$(pwd)"/$GIT_DIR/config
-- 
1.7.1.rc1.69.g24c2f7