git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH 2/2] worktree: provide better prefix to go back to original cwd

From
pclouds@gmail.com <pclouds@gmail.com>
Date
Oct 7, 2010, 04:46 UTC
Message-ID
<4cad50da.0e958e0a.40e3.5efd@mx.google.com>
In-Reply-To
<y>
From: Nguyễn Thái Ngọc Duy <pclouds@gmail.com>

When both GIT_DIR and GIT_WORK_TREE are set, if cwd is outside worktree, prefix (the one passed to every builtin commands) will be set to NULL, which means "user stays at worktree topdir", but cwd is not moved to worktree topdir.

As a consequence, command line arguments will be interpreted differently. Assume there is a file named "bar" in foo/.git. A command can expect command line arguments to be "path in repository":

$ GIT_DIR=foo/.git GIT_WORK_TREE=foo git blah bar
or "path in file system":
$ GIT_DIR=foo/.git GIT_WORK_TREE=foo git blah foo/bar

Some commands may want "path in repository" and "path in file system" to be identical. Moreover, output from commands in such situations are relative to worktree topdir (because prefix is NULL), not what users expect. It's just confusing.

This patch does not address that. Instead it prepares some variables to ease access to original cwd in this case. Commands that work well outside worktree should:

 - detect this case, via is_inside_work_tree()
 - enter_work_tree() (not strictly needed, but I believe it would
   less work this way)
 - prepend startup_info->cwd_to_worktree to output so it becomes
   relative to original cwd
 - prepend startup_info->worktree_to_cwd to command line arguments
   if they are meant to access file system
Signed-off-by: Nguyễn Thái Ngọc Duy <pclouds@gmail.com>
---
 I don't care Windows UNC path. And I did not test the case
 where cwd is on C:\ while worktree is on another drive.
 As stated elsewhere, I neglect other cases where cwd may be
 outside worktree. The goal of these patches is to help
 Chris' grep series. If it works out, I'll fix the rest.
 Sorry Chris, I think I have dragged you into worktree setup
 mess.
 builtin/rev-parse.c        |   10 ++++
 cache.h                    |    2 +
 setup.c                    |  119 ++++++++++++++++++++++++++++++++++++++++++--
 t/t1510-worktree-prefix.sh |   52 +++++++++++++++++++
 4 files changed, 179 insertions(+), 4 deletions(-)
 create mode 100755 t/t1510-worktree-prefix.sh
diff --git a/builtin/rev-parse.c b/builtin/rev-parse.c
index a5a1c86..525610e 100644
--- a/builtin/rev-parse.c
+++ b/builtin/rev-parse.c
@@ -623,6 +623,16 @@ int cmd_rev_parse(int argc, const char **argv, const char *prefix)
 					puts(prefix);
 				continue;
 			}
+			if (!strcmp(arg, "--cwd-to-worktree")) {
+				if (startup_info->cwd_to_worktree)
+					puts(startup_info->cwd_to_worktree);
+				continue;
+			}
+			if (!strcmp(arg, "--worktree-to-cwd")) {
+				if (startup_info->worktree_to_cwd)
+					puts(startup_info->worktree_to_cwd);
+				continue;
+			}
 			if (!strcmp(arg, "--show-cdup")) {
 				const char *pfx = prefix;
 				if (!is_inside_work_tree()) {
diff --git a/cache.h b/cache.h
index e71db23..be35b8f 100644
--- a/cache.h
+++ b/cache.h
@@ -1111,6 +1111,8 @@ const char *split_cmdline_strerror(int cmdline_errno);
 /* git.c */
 struct startup_info {
 	int have_repository;
+	char *cwd_to_worktree; /* path from original cwd to worktree */
+	char *worktree_to_cwd; /* path from worktree to original cwd */
 };
 extern struct startup_info *startup_info;
 
diff --git a/setup.c b/setup.c
index 3fbe928..1f5117a 100644
--- a/setup.c
+++ b/setup.c
@@ -320,10 +320,120 @@ const char *read_gitfile_gently(const char *path)
 	return path;
 }
 
+/*
+ * Given "foo/bar" and "hey/hello/world", return "../../hey/hello/world/"
+ * Either path1 or path2 can be NULL. All must be canonical.
+ */
+static char *make_path_to_path(const char *path1, const char *path2)
+{
+	int nr_back = 0;
+	int i, pathlen = path2 ? strlen(path2) : 0;
+	char *buf, *p;
+
+	if (path1 && *path1) {
+		nr_back = 1;
+		while (*path1) {
+			if (is_dir_sep(*path1))
+				nr_back++;
+			path1++;
+		}
+	}
+
+	if (!nr_back && !pathlen)
+		return NULL;
+
+	p = buf = xmalloc(3*nr_back + pathlen + 2); /* "../"^nr_back + path2 + '/' + NULL */
+	for (i = 0; i < nr_back; i++) {
+		memcpy(p, "../", 3);
+		p += 3;
+	}
+	if (pathlen) {
+		memcpy(p, path2, pathlen);
+		p += pathlen;
+		if (p[-1] != '/') /* path2 may be c:/, don't put another slash  */
+			*p++ = '/';
+	}
+	*p = '\0';
+	return buf;
+}
+
+/*
+ * Return a prefix if cwd inside worktree, or NULL otherwise.
+ * Also fill startup_info struct.
+ */
+static const char *setup_prefix(const char *cwd)
+{
+	const char *worktree = get_git_work_tree();
+	int len = 0, cwd_len = strlen(cwd), worktree_len = strlen(worktree);
+
+	while (worktree[len] && worktree[len] == cwd[len])
+		len++;
+
+	if (!worktree[len] && !cwd[len]) {
+		if (startup_info) {
+			startup_info->cwd_to_worktree = NULL;
+			startup_info->worktree_to_cwd = NULL;
+		}
+		return NULL;
+	}
+	/* get /foo/, not /foo/baa if /foo/baa1 and /foo/baa2 are given */
+	else if (worktree[len] && cwd[len]) {
+		while (len && !is_dir_sep(worktree[len]))
+			len--;
+		len++;
+
+		/* Worktree and cwd are on different drives? */
+		if (len == 3 && has_dos_drive_prefix(cwd)) {
+			if (startup_info) {
+				/* make_path_to_path will add the trailing slash */
+				startup_info->cwd_to_worktree = make_path_to_path(NULL, worktree);
+				startup_info->worktree_to_cwd = make_path_to_path(NULL, cwd);
+			}
+			return NULL;
+		}
+	}
+	else {
+		if (worktree[len]) {
+			if (!is_dir_sep(worktree[len])) {
+				while (len && !is_dir_sep(worktree[len]))
+					len--;
+			}
+		}
+		else {
+			if (!is_dir_sep(cwd[len])) {
+				while (len && !is_dir_sep(cwd[len]))
+					len--;
+			}
+		}
+		len++;		/* must be a slash here, skip it */
+	}
+
+	if (len < cwd_len && len < worktree_len) {
+		if (startup_info) {
+			startup_info->cwd_to_worktree = make_path_to_path(cwd+len, worktree+len);
+			startup_info->worktree_to_cwd = make_path_to_path(worktree+len, cwd+len);
+		}
+		return NULL;
+	}
+
+	if (startup_info) {
+		if (len < cwd_len) { /* cwd inside worktree */
+			startup_info->cwd_to_worktree = make_path_to_path(cwd+len, NULL);
+			startup_info->worktree_to_cwd = make_path_to_path(NULL, cwd+len);
+		}
+		else {
+			startup_info->cwd_to_worktree = make_path_to_path(NULL, worktree+len);
+			startup_info->worktree_to_cwd = make_path_to_path(worktree+len, NULL);
+		}
+	}
+
+	return len < cwd_len ? cwd+len : NULL;
+}
+
 static const char *setup_explicit_git_dir(const char *gitdirenv,
 				const char *work_tree_env, int *nongit_ok)
 {
-	static char buffer[1024 + 1];
+	static char buffer[PATH_MAX];
 	const char *retval;
 
 	if (PATH_MAX - 40 < strlen(gitdirenv))
@@ -344,9 +454,10 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
 	}
 	if (check_repository_format_gently(nongit_ok))
 		return NULL;
-	retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
-			get_git_work_tree());
-	if (!retval || !*retval)
+	if (!getcwd(buffer, sizeof(buffer)))
+		die_errno("can't find the current directory");
+	retval = setup_prefix(buffer);
+	if (!retval)
 		return NULL;
 	set_git_dir(make_absolute_path(gitdirenv));
 	if (chdir(work_tree_env) < 0)
diff --git a/t/t1510-worktree-prefix.sh b/t/t1510-worktree-prefix.sh
new file mode 100755
index 0000000..3839493
--- /dev/null
+++ b/t/t1510-worktree-prefix.sh
@@ -0,0 +1,52 @@
+#!/bin/sh
+
+test_description='test rev-parse --cwd-to-worktree and --worktree-to-cwd'
+
+. ./test-lib.sh
+
+test_expect_success 'setup' '
+	mkdir foo bar &&
+	mv .git foo &&
+	mkdir foo/bar &&
+	GIT_DIR=`pwd`/foo/.git &&
+	GIT_WORK_TREE=`pwd`/foo &&
+	export GIT_DIR GIT_WORK_TREE
+'
+
+test_expect_success 'at root' '
+	(
+	cd foo &&
+	git rev-parse --cwd-to-worktree --worktree-to-cwd >result &&
+	: >expected &&
+	test_cmp expected result
+	)
+'
+
+test_expect_success 'cwd inside worktree' '
+	(
+	cd foo/bar &&
+	git rev-parse --cwd-to-worktree --worktree-to-cwd >result &&
+	echo ../ >expected &&
+	echo bar/ >>expected &&
+	test_cmp expected result
+	)
+'
+
+test_expect_success 'cwd outside worktree' '
+	git rev-parse --cwd-to-worktree --worktree-to-cwd >result &&
+	echo foo/ >expected &&
+	echo ../ >>expected &&
+	test_cmp expected result
+'
+
+test_expect_success 'cwd outside worktree (2)' '
+	(
+	cd bar &&
+	git rev-parse --cwd-to-worktree --worktree-to-cwd >result &&
+	echo ../foo/ >expected &&
+	echo ../bar/ >>expected &&
+	test_cmp expected result
+	)
+'
+
+test_done
-- 
1.7.1.rc1.70.g788ca
Previous: pclouds@gmail.comNext: Nguyen Thai Ngoc Duy
Message 26 of 98 in “Close a forgotten reference to the HEAD ref.”
  1. 1/2 Close a forgotten reference to the HEAD ref.Robin Rosenberg, Dec 2, 2008
  2. 2/2 Improve closing of files in error situations.Robin Rosenberg, Dec 2, 2008
  3. 2/2 Improve closing of files in error situations.Robin Rosenberg, Dec 2, 2008
  4. 0/3 Ref log readerRobin Rosenberg, Jun 7, 2009
  5. 1/3 Assert the name and origName properties of Ref objectsRobin Rosenberg, Jun 7, 2009
  6. 2/3 Add methods to RawParseUtils for scanning backwards.Robin Rosenberg, Jun 7, 2009
  7. 3/3 Add a ref log reader classRobin Rosenberg, Jun 7, 2009
  8. Shawn O. PearceJun 7, 2009
  9. Robin RosenbergJun 7, 2009
  10. Shawn O. PearceJun 7, 2009
  11. 1/2 Add methods to RawParseUtils for scanning backwards.Robin Rosenberg, Jun 8, 2009
  12. 2/2 Add a ref log reader classRobin Rosenberg, Jun 8, 2009
  13. Shawn O. PearceJun 12, 2009
  14. 1/2 Use a UTC relative time zone for PersonIdentRobin Rosenberg, Jun 15, 2009
  15. 2/2 Add a ref log reader classRobin Rosenberg, Jun 15, 2009
  16. Robin RosenbergJun 15, 2009
  17. [BUG] apply: test for trailing whitespace & no new line bugy@vger.kernel.org, Jun 22, 2009
  18. [BUG] apply: test for trailing whitespace & no new line bugy@vger.kernel.org, Jun 22, 2009
  19. diff.c: fix a graph output bugstruggleyb.nku@gmail.com, Jul 8, 2010
  20. Junio C HamanoJul 9, 2010
  21. Junio C HamanoJul 9, 2010
  22. Nazri RamliyJul 9, 2010
  23. Junio C HamanoJul 9, 2010
  24. Bo YangJul 11, 2010
  25. 1/2 setup.c: add enter_work_tree()pclouds@gmail.com, Oct 7, 2010
  26. 2/2 worktree: provide better prefix to go back to original cwdpclouds@gmail.com, Oct 7, 2010
  27. Nguyen Thai Ngoc DuyOct 7, 2010
  28. Junio C HamanoOct 7, 2010
  29. Nguyen Thai Ngoc DuyOct 7, 2010
  30. Junio C HamanoOct 7, 2010
  31. Nguyen Thai Ngoc DuyOct 7, 2010
  32. Corrected cmitmode set in the right lower window when initiating a diff.Michał Pomorski, Nov 23, 2010
  33. git-p4: replace each tab with 8 spaces for consistencyAndrew Garber, Apr 7, 2011
  34. Junio C HamanoApr 7, 2011
  35. Phil HordApr 7, 2011
  36. Junio C HamanoApr 7, 2011
  37. git-p4: replace each tab with 8 spaces for consistencyAndrew Garber, Apr 7, 2011
  38. file import functionality for git-remote-mwPavel Volek, Jun 4, 2012
  39. Matthieu MoyJun 4, 2012
  40. Export file attachements in git-remote-mediawikiNGUYEN Kim Thuat, Jun 4, 2012
  41. Matthieu MoyJun 4, 2012
  42. nguyenkiJun 5, 2012
  43. Matthieu MoyJun 5, 2012
  44. nguyenkiJun 6, 2012
  45. nguyenkiJun 5, 2012
  46. [PATCHv1] Export file in git-remote-mediawikiKim Thuat NGUYEN, Jun 8, 2012
  47. Matthieu MoyJun 8, 2012
  48. nguyenkiJun 8, 2012
  49. Matthieu MoyJun 10, 2012
  50. [PATCHv2] git-remote-mediawiki: export File: attachmentsKim Thuat NGUYEN, Jun 12, 2012
  51. Matthieu MoyJun 12, 2012
  52. nguyenkiJun 12, 2012
  53. Max HornJun 12, 2012
  54. [PATCHv3] git-remote-mediawiki: export File: attachmentskim-thuat.nguyen@ensimag.imag.fr, Jun 13, 2012
  55. Matthieu MoyJun 13, 2012
  56. git send-email should not allow 'y' for in-reply-toEric Blake, Jan 11, 2013
  57. Jeff KingJan 11, 2013
  58. Eric BlakeJan 11, 2013
  59. Hilco WijbengaJan 11, 2013
  60. Jeff KingJan 11, 2013
  61. Junio C HamanoFeb 24, 2013
  62. v3 [PATCH 1/2] status: introduce status.short to enable --short by defaulty@ensimag.imag.fr, Jun 10, 2013
  63. v3 [PATCH 1/2] status: introduce status.short to enable --short by defaulty@ensimag.imag.fr, Jun 10, 2013
  64. v3 [PATCH 2/2] status:introduce status.branch to enable --branch by defaulty@ensimag.imag.fr, Jun 10, 2013
  65. v3 [PATCH 2/2] status:introduce status.branch to enable --branch by defaulty@ensimag.imag.fr, Jun 10, 2013
  66. Matthieu MoyJun 10, 2013
  67. Junio C HamanoJun 10, 2013
  68. 3/3 builtin/blame.c: reduce scope of variablesElia Pinto, Jan 29, 2014
  69. use strchrnul() in place of strchr() and strlen()Rohit Mani, Mar 5, 2014
  70. Junio C HamanoMar 6, 2014
  71. [GSoC][PATCH v2] use strchrnul() in place of strchr() and strlen()Rohit Mani, Mar 8, 2014
  72. Junio C HamanoMar 10, 2014
  73. [GSOC2014]TamerTas, Mar 10, 2014
  74. [GSOC2014] changed logical chain in branch.c to lookup tablesTamerTas, Mar 10, 2014
  75. Stefan BellerMar 10, 2014
  76. Eric SunshineMar 10, 2014
  77. Tamer TASMar 10, 2014
  78. Eric SunshineMar 10, 2014
  79. Tamer TASMar 11, 2014
  80. Eric SunshineMar 11, 2014
  81. [GSOC2014] add: Rewrite run_add_interactive to use struct argv_arrayMovchan Pavel, Mar 18, 2014
  82. Junio C HamanoMar 18, 2014
  83. Use "working tree" instead of "working directory" for git statusLars Vogel, Jun 9, 2016
  84. Eric SunshineJun 9, 2016
  85. Lars VogelJun 9, 2016
  86. 1/1 git-stash.txt: correct "git stash" behavior with no argumentsTakahito Ogawa, Oct 11, 2017
  87. Junio C HamanoOct 12, 2017
  88. 小川恭史Oct 12, 2017
  89. 小川恭史Oct 12, 2017
  90. Junio C HamanoOct 12, 2017
  91. Allow usage of --gpg-sign flag in commit-tree builtin.Brandon Richardson, Jan 17, 2019
  92. Martin ÅgrenJan 17, 2019
  93. commit-tree: add missing --gpg-sign flagBrandon Richardson, Jan 18, 2019
  94. Martin ÅgrenJan 18, 2019
  95. Brandon RichardsonJan 18, 2019
  96. Junio C HamanoJan 18, 2019
  97. [L10N] Kickoff for Git 2.22.0 round #1Jiang Xin, May 14, 2019
  98. [L10N] Kickoff for Git 2.49.0Jiang Xin, Feb 27, 2025

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.