Subject: [PATCH] always interpret GIT_WORK_DIR relative to $GIT_DIR

From: Matthias Lederhofer <[email-masked]>
Date: Mon, 12 Mar 2007 20:18:12 +0100

Signed-off-by: Matthias Lederhofer <[email-masked]>
---
 setup.c |   39 +++++++++++++++++++++++----------------
 1 files changed, 23 insertions(+), 16 deletions(-)

diff --git a/setup.c b/setup.c
index a8b9fae..f8c020e 100644
--- a/setup.c
+++ b/setup.c
@@ -192,16 +192,36 @@ int is_inside_git_dir(void)
 	return inside_git_dir;
 }
 
+static int stat_relative(const char *base, const char *path, struct stat *st)
+{
+	char cwd[PATH_MAX];
+	int ret;
+
+	if (path[0] != '/') {
+		if (!getcwd(cwd, sizeof(cwd)) || cwd[0] != '/')
+			die("Unable to read current working directory");
+		if (chdir(base))
+			die("Cannot change directory to '%s'", base);
+	}
+
+	ret = stat(path, st);
+
+	if (path[0] != '/' && chdir(cwd))
+		die("Cannot come back to cwd");
+
+	return ret;
+}
+
 static int stat_git_work_dir(struct stat *st)
 {
-	char workdir[PATH_MAX], cwd[PATH_MAX];
+	char workdir[PATH_MAX];
 	const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
 	const char *gitwd = getenv(GIT_WORKING_DIR_ENVIRONMENT);
 	int offset;
 	FILE *fp;
 
 	if (gitwd) {
-		if (!stat(gitwd, st))
+		if (!stat_relative(gitdir, gitwd, st))
 			return 1;
 		die("Unable to stat git working directory '%s'", gitwd);
 	}
@@ -231,21 +251,8 @@ static int stat_git_work_dir(struct stat *st)
 		--offset;
 	workdir[offset+1] = '\0';
 
-	/* relative path: change to gitdir for stat */
-	if (workdir[0] != '/') {
-		if (!getcwd(cwd, sizeof(cwd)) || cwd[0] != '/')
-			die("Unable to read current working directory");
-		if (chdir(gitdir))
-			die("Cannot change directory to '%s'", gitdir);
-	}
-
-	if (stat(workdir, st))
+	if (stat_relative(gitdir, workdir, st))
 		die("Unable to stat directory from GIT_DIR/workdir");
-	if (!(st->st_mode & S_IFDIR))
-		die("GIT_DIR/workdir does not point to a directory");
-
-	if (workdir[0] != '/' && chdir(cwd))
-		die("Cannot come back to cwd");
 
 	return 1;
 }
-- 
1.5.0.3.1007.g7ff7