git@vger.kernel.org mailing list mirror (one of many)
 help / color / mirror / code / Atom feed
* [PATCH 00/21] completion: __gitdir()-related improvements
@ 2016-02-25 22:50 SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 01/21] completion: improve __git_refs()'s in-code documentation SZEDER Gábor
                   ` (20 more replies)
  0 siblings, 21 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

Hi,

here is a big mixed bag of bugfixes, cleanups and optimizations mostly
related to how we find out the path to the repository and how we use
that path.

Noteworthier changes are the following:

  - Patch 18 shuts up error messages from git commands.  This is the
    one I mentioned some days ago[1].

  - Patches 13-16 make 'git -C <path> <cmd> <TAB>' work as it should,
    with the help of a new 'git rev-parse' option.

  - Patches 17, 19-21 get rid of a few fork()s and exec()s.
    Funfact: I submitted initial versions of patches 20-21 already in
    2012 ;) [2]

Tests pass with all 3.x and 4.x Bash versions[3].

This series is also available from:

  https://github.com/szeder/git completion-gitdir-improvements


Best,
Gábor


[1] - http://thread.gmane.org/gmane.comp.version-control.git/286074/focus=286078
[2] - http://thread.gmane.org/gmane.comp.version-control.git/197432/focus=197438
[3] - In case somebody feels interested, a little proof of concept
      (with Travis CI integration!):

        https://github.com/szeder/git completion-test-multiple-bash-versions


SZEDER Gábor (21):
  completion: improve __git_refs()'s in-code documentation
  completion tests: don't add test cruft to the test repository
  completion tests: make the $cur variable local to the test helper
    functions
  completion tests: consolidate getting path of current working
    directory
  completion tests: check __gitdir()'s output in the error cases
  completion tests: add tests for the __git_refs() helper function
  completion: ensure that the repository path given on the command line
    exists
  completion: fix most spots not respecting 'git --git-dir=<path>'
  completion: respect 'git --git-dir=<path>' when listing remote refs
  completion: list refs from remote when remote's name matches a
    directory
  completion: don't list 'HEAD' when trying refs completion outside of a
    repo
  completion: list short refs from a remote given as a URL
  rev-parse: add '--absolute-git-dir' option
  completion: don't offer commands when 'git --opt' needs an argument
  completion: fix completion after 'git -C <path>'
  completion: respect 'git -C <path>'
  completion: don't use __gitdir() for git commands
  completion: consolidate silencing errors from git commands
  completion: don't guard git executions with __gitdir()
  completion: extract repository discovery from __gitdir()
  completion: cache the path to the repository

 Documentation/git-rev-parse.txt        |   4 +
 builtin/rev-parse.c                    |  29 +-
 contrib/completion/git-completion.bash | 248 ++++++++++-----
 t/t1500-rev-parse.sh                   |  17 +-
 t/t9902-completion.sh                  | 560 ++++++++++++++++++++++++++++-----
 5 files changed, 682 insertions(+), 176 deletions(-)

-- 
2.7.2.410.g92cb358

^ permalink raw reply	[flat|nested] 25+ messages in thread

* [PATCH 01/21] completion: improve __git_refs()'s in-code documentation
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 02/21] completion tests: don't add test cruft to the test repository SZEDER Gábor
                   ` (19 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

That "first argument is passed to __gitdir()" statement in particular
is not really helpful, and after this series it won't be the case
anyway.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index e3918c87e3ad..0e1fd778bfe8 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -332,9 +332,11 @@ __git_tags ()
 	fi
 }
 
-# __git_refs accepts 0, 1 (to pass to __gitdir), or 2 arguments
-# presence of 2nd argument means use the guess heuristic employed
-# by checkout for tracking branches
+# Lists refs from the local (by default) or from a remote repository.
+# It accepts 0, 1 or 2 arguments:
+# 1: The remote to lists refs from (optional; ignored, if set but empty).
+# 2: In addition to local refs, list unique branches from refs/remotes/ for
+#    'git checkout's tracking DWIMery (optional; ignored, if set but empty).
 __git_refs ()
 {
 	local i hash dir="$(__gitdir "${1-}")" track="${2-}"
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 02/21] completion tests: don't add test cruft to the test repository
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 01/21] completion: improve __git_refs()'s in-code documentation SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 03/21] completion tests: make the $cur variable local to the test helper functions SZEDER Gábor
                   ` (18 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

While preparing commits, three tests added newly created files to the
index using 'git add .', which added not only the files in question
but leftover test cruft from previous tests like the files 'expected'
and 'actual' as well.  Luckily, this had no effect on the tests'
correctness.

Add only the files we are actually interested in.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 t/t9902-completion.sh | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 2ba62fbc178e..cec98a7e814c 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -491,7 +491,7 @@ test_expect_success 'git --help completion' '
 test_expect_success 'setup for ref completion' '
 	echo content >file1 &&
 	echo more >file2 &&
-	git add . &&
+	git add file1 file2 &&
 	git commit -m one &&
 	git branch mybranch &&
 	git tag mytag
@@ -522,7 +522,7 @@ test_expect_success '<ref>: completes paths' '
 
 test_expect_success 'complete tree filename with spaces' '
 	echo content >"name with spaces" &&
-	git add . &&
+	git add "name with spaces" &&
 	git commit -m spaces &&
 	test_completion "git show HEAD:nam" <<-\EOF
 	name with spaces Z
@@ -531,7 +531,7 @@ test_expect_success 'complete tree filename with spaces' '
 
 test_expect_success 'complete tree filename with metacharacters' '
 	echo content >"name with \${meta}" &&
-	git add . &&
+	git add "name with \${meta}" &&
 	git commit -m meta &&
 	test_completion "git show HEAD:nam" <<-\EOF
 	name with ${meta} Z
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 03/21] completion tests: make the $cur variable local to the test helper functions
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 01/21] completion: improve __git_refs()'s in-code documentation SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 02/21] completion tests: don't add test cruft to the test repository SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 04/21] completion tests: consolidate getting path of current working directory SZEDER Gábor
                   ` (17 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

The test helper functions test_gitcomp() and test_gitcomp_nl() leak
the $cur variable into the test environment.  Since this variable has
a special role in the Bash completion script (it holds the word
currently being completed) it influences the behavior of most
completion functions and thus this leakage could interfere with
subsequent tests.  Although there are no such issues in the current
tests, early versions of the new tests that will be added later in
this series suffered because of this.

It's better to play safe and declare $cur local in those test helper
functions.  'local' is bashism, of course, but the tests of the Bash
completion script are run under Bash anyway, and there are already
other variables declared local in this test script.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 t/t9902-completion.sh | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index cec98a7e814c..9f591c361fab 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -98,7 +98,7 @@ test_gitcomp ()
 {
 	local -a COMPREPLY &&
 	sed -e 's/Z$//' >expected &&
-	cur="$1" &&
+	local cur="$1" &&
 	shift &&
 	__gitcomp "$@" &&
 	print_comp &&
@@ -113,7 +113,7 @@ test_gitcomp_nl ()
 {
 	local -a COMPREPLY &&
 	sed -e 's/Z$//' >expected &&
-	cur="$1" &&
+	local cur="$1" &&
 	shift &&
 	__gitcomp_nl "$@" &&
 	print_comp &&
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 04/21] completion tests: consolidate getting path of current working directory
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (2 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 03/21] completion tests: make the $cur variable local to the test helper functions SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 05/21] completion tests: check __gitdir()'s output in the error cases SZEDER Gábor
                   ` (16 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

Some tests of the __gitdir() helper function use the $TRASH_DIRECTORY
variable in direct path comparisons.  In general this should be
avoided, because it might contain symbolic links.  There happens to be
no issues with this here, however, because those tests use
$TRASH_DIRECTORY both for specifying the expected result and for
specifying input which in turn is just 'echo'ed verbatim.

Other __gitdir() tests ask for the path of the trash directory by
running $(pwd -P) in each test, sometimes even twice in a single test.

Run $(pwd) only once at the beginning of the test script to store the
path of the trash directory in a variable, and use that variable in
all __gitdir() tests.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 t/t9902-completion.sh | 46 ++++++++++++++++++++++------------------------
 1 file changed, 22 insertions(+), 24 deletions(-)

diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 9f591c361fab..447f57b89291 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -124,15 +124,22 @@ invalid_variable_name='${foo.bar}'
 
 actual="$TRASH_DIRECTORY/actual"
 
+if test_have_prereq MINGW
+then
+	ROOT="$(pwd -W)"
+else
+	ROOT="$(pwd)"
+fi
+
 test_expect_success 'setup for __gitdir tests' '
 	mkdir -p subdir/subsubdir &&
 	git init otherrepo
 '
 
 test_expect_success '__gitdir - from command line (through $__git_dir)' '
-	echo "$TRASH_DIRECTORY/otherrepo/.git" >expected &&
+	echo "$ROOT/otherrepo/.git" >expected &&
 	(
-		__git_dir="$TRASH_DIRECTORY/otherrepo/.git" &&
+		__git_dir="$ROOT/otherrepo/.git" &&
 		__gitdir >"$actual"
 	) &&
 	test_cmp expected "$actual"
@@ -157,7 +164,7 @@ test_expect_success '__gitdir - .git directory in cwd' '
 '
 
 test_expect_success '__gitdir - .git directory in parent' '
-	echo "$(pwd -P)/.git" >expected &&
+	echo "$ROOT/.git" >expected &&
 	(
 		cd subdir/subsubdir &&
 		__gitdir >"$actual"
@@ -175,7 +182,7 @@ test_expect_success '__gitdir - cwd is a .git directory' '
 '
 
 test_expect_success '__gitdir - parent is a .git directory' '
-	echo "$(pwd -P)/.git" >expected &&
+	echo "$ROOT/.git" >expected &&
 	(
 		cd .git/refs/heads &&
 		__gitdir >"$actual"
@@ -184,9 +191,9 @@ test_expect_success '__gitdir - parent is a .git directory' '
 '
 
 test_expect_success '__gitdir - $GIT_DIR set while .git directory in cwd' '
-	echo "$TRASH_DIRECTORY/otherrepo/.git" >expected &&
+	echo "$ROOT/otherrepo/.git" >expected &&
 	(
-		GIT_DIR="$TRASH_DIRECTORY/otherrepo/.git" &&
+		GIT_DIR="$ROOT/otherrepo/.git" &&
 		export GIT_DIR &&
 		__gitdir >"$actual"
 	) &&
@@ -194,9 +201,9 @@ test_expect_success '__gitdir - $GIT_DIR set while .git directory in cwd' '
 '
 
 test_expect_success '__gitdir - $GIT_DIR set while .git directory in parent' '
-	echo "$TRASH_DIRECTORY/otherrepo/.git" >expected &&
+	echo "$ROOT/otherrepo/.git" >expected &&
 	(
-		GIT_DIR="$TRASH_DIRECTORY/otherrepo/.git" &&
+		GIT_DIR="$ROOT/otherrepo/.git" &&
 		export GIT_DIR &&
 		cd subdir &&
 		__gitdir >"$actual"
@@ -206,24 +213,15 @@ test_expect_success '__gitdir - $GIT_DIR set while .git directory in parent' '
 
 test_expect_success '__gitdir - non-existing $GIT_DIR' '
 	(
-		GIT_DIR="$TRASH_DIRECTORY/non-existing" &&
+		GIT_DIR="$ROOT/non-existing" &&
 		export GIT_DIR &&
 		test_must_fail __gitdir
 	)
 '
 
-function pwd_P_W () {
-	if test_have_prereq MINGW
-	then
-		pwd -W
-	else
-		pwd -P
-	fi
-}
-
 test_expect_success '__gitdir - gitfile in cwd' '
-	echo "$(pwd_P_W)/otherrepo/.git" >expected &&
-	echo "gitdir: $(pwd_P_W)/otherrepo/.git" >subdir/.git &&
+	echo "$ROOT/otherrepo/.git" >expected &&
+	echo "gitdir: $ROOT/otherrepo/.git" >subdir/.git &&
 	test_when_finished "rm -f subdir/.git" &&
 	(
 		cd subdir &&
@@ -233,8 +231,8 @@ test_expect_success '__gitdir - gitfile in cwd' '
 '
 
 test_expect_success '__gitdir - gitfile in parent' '
-	echo "$(pwd_P_W)/otherrepo/.git" >expected &&
-	echo "gitdir: $(pwd_P_W)/otherrepo/.git" >subdir/.git &&
+	echo "$ROOT/otherrepo/.git" >expected &&
+	echo "gitdir: $ROOT/otherrepo/.git" >subdir/.git &&
 	test_when_finished "rm -f subdir/.git" &&
 	(
 		cd subdir/subsubdir &&
@@ -244,7 +242,7 @@ test_expect_success '__gitdir - gitfile in parent' '
 '
 
 test_expect_success SYMLINKS '__gitdir - resulting path avoids symlinks' '
-	echo "$(pwd -P)/otherrepo/.git" >expected &&
+	echo "$ROOT/otherrepo/.git" >expected &&
 	mkdir otherrepo/dir &&
 	test_when_finished "rm -rf otherrepo/dir" &&
 	ln -s otherrepo/dir link &&
@@ -259,7 +257,7 @@ test_expect_success SYMLINKS '__gitdir - resulting path avoids symlinks' '
 test_expect_success '__gitdir - not a git repository' '
 	(
 		cd subdir/subsubdir &&
-		GIT_CEILING_DIRECTORIES="$TRASH_DIRECTORY" &&
+		GIT_CEILING_DIRECTORIES="$ROOT" &&
 		export GIT_CEILING_DIRECTORIES &&
 		test_must_fail __gitdir
 	)
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 05/21] completion tests: check __gitdir()'s output in the error cases
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (3 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 04/21] completion tests: consolidate getting path of current working directory SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 06/21] completion tests: add tests for the __git_refs() helper function SZEDER Gábor
                   ` (15 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

The __gitdir() helper function shouldn't output anything if not in a
git repository.  The relevant tests only checked its error code, so
extend them to ensure that there's no output.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 t/t9902-completion.sh | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 447f57b89291..1e8794747efd 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -215,8 +215,9 @@ test_expect_success '__gitdir - non-existing $GIT_DIR' '
 	(
 		GIT_DIR="$ROOT/non-existing" &&
 		export GIT_DIR &&
-		test_must_fail __gitdir
-	)
+		test_must_fail __gitdir >"$actual"
+	) &&
+	test_must_be_empty "$actual"
 '
 
 test_expect_success '__gitdir - gitfile in cwd' '
@@ -259,8 +260,9 @@ test_expect_success '__gitdir - not a git repository' '
 		cd subdir/subsubdir &&
 		GIT_CEILING_DIRECTORIES="$ROOT" &&
 		export GIT_CEILING_DIRECTORIES &&
-		test_must_fail __gitdir
-	)
+		test_must_fail __gitdir >"$actual"
+	) &&
+	test_must_be_empty "$actual"
 '
 
 test_expect_success '__gitcomp - trailing space - options' '
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 06/21] completion tests: add tests for the __git_refs() helper function
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (4 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 05/21] completion tests: check __gitdir()'s output in the error cases SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 07/21] completion: ensure that the repository path given on the command line exists SZEDER Gábor
                   ` (14 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

Check how __git_refs() lists refs in different scenarios, i.e.

  - short and full refs,
  - from a local or from a remote repository,
  - remote specified via path, name or URL,
  - with or without a repository specified on the command line,
  - non-existing remote,
  - unique remote branches for 'git checkout's tracking DWIMery,
  - not in a git repository, and
  - interesting combinations of the above.

Seven of these tests expect failure, mostly demonstrating bugs related
to listing refs from a remote repository:

  - ignoring the repository specified on the command line (2 tests),
  - listing refs from the wrong place when the name of a configured
    remote happens to match a directory,
  - listing only 'HEAD' but no short refs from a remote given as URL,
  - listing 'HEAD' even from non-existing remotes (2 tests), and
  - listing 'HEAD' when not in a repository.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 t/t9902-completion.sh | 266 ++++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 257 insertions(+), 9 deletions(-)

diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 1e8794747efd..7ab398568594 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -370,6 +370,263 @@ test_expect_success '__git_remotes - list remotes from $GIT_DIR/remotes and from
 	test_cmp expect actual
 '
 
+test_expect_success 'setup for ref completion' '
+	echo content >file1 &&
+	echo more >file2 &&
+	git add file1 file2 &&
+	git commit -m one &&
+	git branch mybranch &&
+	git tag mytag &&
+	(
+		cd otherrepo &&
+		>file &&
+		git add file &&
+		git commit -m initial &&
+		git branch branch
+	) &&
+	git remote add remote "$ROOT/otherrepo/.git" &&
+	git update-ref refs/remotes/remote/branch master &&
+	git update-ref refs/remotes/remote/master master &&
+	git init thirdrepo
+'
+
+test_expect_success '__git_refs - simple' '
+	cat >expected <<-EOF &&
+	HEAD
+	master
+	mybranch
+	remote/branch
+	remote/master
+	mytag
+	EOF
+	(
+		cur= &&
+		__git_refs >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__git_refs - full refs' '
+	cat >expected <<-EOF &&
+	refs/heads/master
+	refs/heads/mybranch
+	EOF
+	(
+		cur=refs/heads/ &&
+		__git_refs >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__git_refs - repo given on the command line' '
+	cat >expected <<-EOF &&
+	HEAD
+	branch
+	master
+	EOF
+	(
+		__git_dir="$ROOT/otherrepo/.git" &&
+		cur= &&
+		__git_refs >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__git_refs - remote on local file system' '
+	cat >expected <<-EOF &&
+	HEAD
+	branch
+	master
+	EOF
+	(
+		cur= &&
+		__git_refs otherrepo >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__git_refs - remote on local file system - full refs' '
+	cat >expected <<-EOF &&
+	refs/heads/branch
+	refs/heads/master
+	EOF
+	(
+		cur=refs/heads/ &&
+		__git_refs otherrepo >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__git_refs - configured remote' '
+	cat >expected <<-EOF &&
+	HEAD
+	branch
+	master
+	EOF
+	(
+		cur= &&
+		__git_refs remote >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__git_refs - configured remote - full refs' '
+	cat >expected <<-EOF &&
+	refs/heads/branch
+	refs/heads/master
+	EOF
+	(
+		cur=refs/heads/ &&
+		__git_refs remote >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_failure '__git_refs - configured remote - repo given on the command line' '
+	cat >expected <<-EOF &&
+	HEAD
+	branch
+	master
+	EOF
+	(
+		cd thirdrepo &&
+		__git_dir="$ROOT/.git" &&
+		cur= &&
+		__git_refs remote >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_failure '__git_refs - configured remote - full refs - repo given on the command line' '
+	cat >expected <<-EOF &&
+	refs/heads/branch
+	refs/heads/master
+	EOF
+	(
+		cd thirdrepo &&
+		__git_dir="$ROOT/.git" &&
+		cur=refs/heads/ &&
+		__git_refs remote >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_failure '__git_refs - configured remote - remote name matches a directory' '
+	cat >expected <<-EOF &&
+	HEAD
+	branch
+	master
+	EOF
+	mkdir remote &&
+	test_when_finished "rm -rf remote" &&
+	(
+		cur= &&
+		__git_refs remote >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_failure '__git_refs - URL remote' '
+	cat >expected <<-EOF &&
+	HEAD
+	branch
+	master
+	EOF
+	(
+		cur= &&
+		__git_refs "file://$ROOT/otherrepo/.git" >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__git_refs - URL remote - full refs' '
+	cat >expected <<-EOF &&
+	refs/heads/branch
+	refs/heads/master
+	EOF
+	(
+		cur=refs/heads/ &&
+		__git_refs "file://$ROOT/otherrepo/.git" >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_failure '__git_refs - non-existing remote' '
+	(
+		cur= &&
+		__git_refs non-existing >"$actual"
+	) &&
+	test_must_be_empty "$actual"
+'
+
+test_expect_success '__git_refs - non-existing remote - full refs' '
+	(
+		cur=refs/heads/ &&
+		__git_refs non-existing >"$actual"
+	) &&
+	test_must_be_empty "$actual"
+'
+
+test_expect_failure '__git_refs - non-existing URL remote' '
+	(
+		cur= &&
+		__git_refs "file://$ROOT/non-existing" >"$actual"
+	) &&
+	test_must_be_empty "$actual"
+'
+
+test_expect_success '__git_refs - non-existing URL remote - full refs' '
+	(
+		cur=refs/heads/ &&
+		__git_refs "file://$ROOT/non-existing" >"$actual"
+	) &&
+	test_must_be_empty "$actual"
+'
+
+test_expect_success '__git_refs - unique remote branches for git checkout DWIMery' '
+	cat >expected <<-EOF &&
+	HEAD
+	master
+	mybranch
+	otherremote/ambiguous
+	otherremote/otherbranch
+	remote/ambiguous
+	remote/branch
+	remote/master
+	mytag
+	branch
+	master
+	otherbranch
+	EOF
+	for remote_ref in refs/remotes/remote/ambiguous \
+		refs/remotes/otherremote/ambiguous \
+		refs/remotes/otherremote/otherbranch
+	do
+		git update-ref $remote_ref master &&
+		test_when_finished "git update-ref -d $remote_ref"
+	done &&
+	(
+		cur= &&
+		__git_refs "" 1 >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_failure '__git_refs - not in a git repository' '
+	(
+		GIT_CEILING_DIRECTORIES="$ROOT" &&
+		export GIT_CEILING_DIRECTORIES &&
+		cd subdir &&
+		cur= &&
+		__git_refs >"$actual"
+	) &&
+	test_must_be_empty "$actual"
+'
+
+test_expect_success 'remove configured remote used for refs completion' '
+	git remote remove remote
+'
+
 test_expect_success '__git_get_config_variables' '
 	cat >expect <<-EOF &&
 	name-1
@@ -488,15 +745,6 @@ test_expect_success 'git --help completion' '
 	test_completion "git --help core" "core-tutorial "
 '
 
-test_expect_success 'setup for ref completion' '
-	echo content >file1 &&
-	echo more >file2 &&
-	git add file1 file2 &&
-	git commit -m one &&
-	git branch mybranch &&
-	git tag mytag
-'
-
 test_expect_success 'checkout completes ref names' '
 	test_completion "git checkout m" <<-\EOF
 	master Z
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 07/21] completion: ensure that the repository path given on the command line exists
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (5 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 06/21] completion tests: add tests for the __git_refs() helper function SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 08/21] completion: fix most spots not respecting 'git --git-dir=<path>' SZEDER Gábor
                   ` (13 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

The __gitdir() helper function stays silent and returns with error
when it can't find a repository or when the repository given via
$GIT_DIR doesn't exist.

This is not the case, however, when the path in $__git_dir, i.e. the
path to the repository specified on the command line as 'git
--git-dir=<path>', doesn't exist: __gitdir() still outputs it and
returns with success, making completion functions believe that they
operate on an existing repository.

Check that the path in $__git_dir exists and return with error if it
doesn't.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 1 +
 t/t9902-completion.sh                  | 8 ++++++++
 2 files changed, 9 insertions(+)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 0e1fd778bfe8..0ec988c0ee26 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -40,6 +40,7 @@ __gitdir ()
 {
 	if [ -z "${1-}" ]; then
 		if [ -n "${__git_dir-}" ]; then
+			test -d "$__git_dir" || return 1
 			echo "$__git_dir"
 		elif [ -n "${GIT_DIR-}" ]; then
 			test -d "${GIT_DIR-}" || return 1
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 7ab398568594..809856110235 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -211,6 +211,14 @@ test_expect_success '__gitdir - $GIT_DIR set while .git directory in parent' '
 	test_cmp expected "$actual"
 '
 
+test_expect_success '__gitdir - non-existing path in $__git_dir' '
+	(
+		__git_dir="non-existing" &&
+		test_must_fail __gitdir >"$actual"
+	) &&
+	test_must_be_empty "$actual"
+'
+
 test_expect_success '__gitdir - non-existing $GIT_DIR' '
 	(
 		GIT_DIR="$ROOT/non-existing" &&
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 08/21] completion: fix most spots not respecting 'git --git-dir=<path>'
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (6 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 07/21] completion: ensure that the repository path given on the command line exists SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 09/21] completion: respect 'git --git-dir=<path>' when listing remote refs SZEDER Gábor
                   ` (12 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

The completion script already respects the path to the repository
specified on the command line most of the time, here we add the
necessary '--git-dir=$(__gitdir)' options to most of the places where
git was executed without it.  The exceptions where said option is not
added are the git invocations:

  - in __git_refs() which are non-trivial and will be the subject of
    the following patch,

  - getting the list of git commands, merge strategies and archive
    formats, because these are independent from the repository and
    thus don't need it, and

  - the 'git rev-parse --git-dir' in __gitdir() itself.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 0ec988c0ee26..59dffe7f39c2 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -283,11 +283,13 @@ __gitcomp_file ()
 # argument, and using the options specified in the second argument.
 __git_ls_files_helper ()
 {
+	local dir="$(__gitdir)"
+
 	if [ "$2" == "--committable" ]; then
-		git -C "$1" diff-index --name-only --relative HEAD
+		git --git-dir="$dir" -C "$1" diff-index --name-only --relative HEAD
 	else
 		# NOTE: $2 is not quoted in order to support multiple options
-		git -C "$1" ls-files --exclude-standard $2
+		git --git-dir="$dir" -C "$1" ls-files --exclude-standard $2
 	fi 2>/dev/null
 }
 
@@ -407,7 +409,7 @@ __git_refs2 ()
 __git_refs_remotes ()
 {
 	local i hash
-	git ls-remote "$1" 'refs/heads/*' 2>/dev/null | \
+	git --git-dir="$(__gitdir)" ls-remote "$1" 'refs/heads/*' 2>/dev/null | \
 	while read -r hash i; do
 		echo "$i:refs/remotes/$1/${i#refs/heads/}"
 	done
@@ -1138,7 +1140,7 @@ _git_commit ()
 		return
 	esac
 
-	if git rev-parse --verify --quiet HEAD >/dev/null; then
+	if git --git-dir="$(__gitdir)" rev-parse --verify --quiet HEAD >/dev/null; then
 		__git_complete_index_file "--committable"
 	else
 		# This is the first commit
@@ -1431,7 +1433,7 @@ _git_log ()
 {
 	__git_has_doubledash && return
 
-	local g="$(git rev-parse --git-dir 2>/dev/null)"
+	local g="$(__gitdir)"
 	local merge=""
 	if [ -f "$g/MERGE_HEAD" ]; then
 		merge="--merge"
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 09/21] completion: respect 'git --git-dir=<path>' when listing remote refs
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (7 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 08/21] completion: fix most spots not respecting 'git --git-dir=<path>' SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 10/21] completion: list refs from remote when remote's name matches a directory SZEDER Gábor
                   ` (11 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

In __git_refs() the git commands listing refs, both short and full,
from a given remote repository are run without giving them the path to
the git repository which might have been specified on the command line
via 'git --git-dir=<path>'.  This is bad, those git commands should
access the 'refs/remotes/<remote>/' hierarchy or the remote and
credentials configuration in that specified repository.

Use the __gitdir() helper only to find the path to the .git directory
and pass the resulting path to the 'git ls-remote' and 'for-each-ref'
executions that list remote refs.

Don't use __gitdir() to check that the given remote is on the file
system: basically it performs only a single if statement for us at the
considerable cost of fork()ing a subshell for a command substitution.
We are better off to perform all the necessary checks of the remote in
__git_refs().

Though __git_refs() was the last remaining callsite that passed a
remote to __gitdir(), don't delete __gitdir()'s remote-handling part
yet, just in case some users' custom completion scriptlets depend on
it.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 22 +++++++++++++++++-----
 t/t9902-completion.sh                  |  4 ++--
 2 files changed, 19 insertions(+), 7 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 59dffe7f39c2..adc968acea9d 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -342,9 +342,21 @@ __git_tags ()
 #    'git checkout's tracking DWIMery (optional; ignored, if set but empty).
 __git_refs ()
 {
-	local i hash dir="$(__gitdir "${1-}")" track="${2-}"
+	local i hash dir="$(__gitdir)" track="${2-}"
+	local from_local=y remote="${1-}"
 	local format refs
-	if [ -d "$dir" ]; then
+
+	if [ -n "$remote" ]; then
+		if [ -d "$remote/.git" ]; then
+			dir="$remote/.git"
+		elif [ -d "$remote" ]; then
+			dir="$remote"
+		else
+			from_local=n
+		fi
+	fi
+
+	if [ "$from_local" = y ] && [ -d "$dir" ]; then
 		case "$cur" in
 		refs|refs/*)
 			format="refname"
@@ -380,7 +392,7 @@ __git_refs ()
 	fi
 	case "$cur" in
 	refs|refs/*)
-		git ls-remote "$dir" "$cur*" 2>/dev/null | \
+		git --git-dir="$dir" ls-remote "$remote" "$cur*" 2>/dev/null | \
 		while read -r hash i; do
 			case "$i" in
 			*^{}) ;;
@@ -390,8 +402,8 @@ __git_refs ()
 		;;
 	*)
 		echo "HEAD"
-		git for-each-ref --format="%(refname:short)" -- \
-			"refs/remotes/$dir/" 2>/dev/null | sed -e "s#^$dir/##"
+		git --git-dir="$dir" for-each-ref --format="%(refname:short)" -- \
+			"refs/remotes/$remote/" 2>/dev/null | sed -e "s#^$remote/##"
 		;;
 	esac
 }
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 809856110235..f9993d2c005a 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -490,7 +490,7 @@ test_expect_success '__git_refs - configured remote - full refs' '
 	test_cmp expected "$actual"
 '
 
-test_expect_failure '__git_refs - configured remote - repo given on the command line' '
+test_expect_success '__git_refs - configured remote - repo given on the command line' '
 	cat >expected <<-EOF &&
 	HEAD
 	branch
@@ -505,7 +505,7 @@ test_expect_failure '__git_refs - configured remote - repo given on the command
 	test_cmp expected "$actual"
 '
 
-test_expect_failure '__git_refs - configured remote - full refs - repo given on the command line' '
+test_expect_success '__git_refs - configured remote - full refs - repo given on the command line' '
 	cat >expected <<-EOF &&
 	refs/heads/branch
 	refs/heads/master
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 10/21] completion: list refs from remote when remote's name matches a directory
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (8 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 09/21] completion: respect 'git --git-dir=<path>' when listing remote refs SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 11/21] completion: don't list 'HEAD' when trying refs completion outside of a repo SZEDER Gábor
                   ` (10 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

If the remote given to __git_refs() happens to match both the name of
a configured remote and the name of a directory in the current working
directory, then that directory is assumed to be a git repository, and
listing refs from that directory will be attempted.  This is wrong,
because in such a situation git commands (e.g. 'git fetch|pull|push
<remote>' whom these refs will eventually be passed to) give
precedence to the configured remote.  Therefore, __git_refs() should
list refs from the configured remote as well.

Add the helper function __git_is_configured_remote() that checks
whether its argument matches the name of a configured remote.  Use
this helper to decide how to handle the remote passed to __git_refs().

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 28 +++++++++++++++++++++++-----
 t/t9902-completion.sh                  | 11 ++++++++++-
 2 files changed, 33 insertions(+), 6 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index adc968acea9d..b85ab27fb18a 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -347,12 +347,18 @@ __git_refs ()
 	local format refs
 
 	if [ -n "$remote" ]; then
-		if [ -d "$remote/.git" ]; then
-			dir="$remote/.git"
-		elif [ -d "$remote" ]; then
-			dir="$remote"
-		else
+		if __git_is_configured_remote "$remote"; then
+			# configured remote takes precedence over a
+			# local directory with the same name
 			from_local=n
+		else
+			if [ -d "$remote/.git" ]; then
+				dir="$remote/.git"
+			elif [ -d "$remote" ]; then
+				dir="$remote"
+			else
+				from_local=n
+			fi
 		fi
 	fi
 
@@ -434,6 +440,18 @@ __git_remotes ()
 	git --git-dir="$d" remote
 }
 
+# Returns true if $1 matches the name of a configured remote, false otherwise.
+__git_is_configured_remote ()
+{
+	local remote
+	for remote in $(__git_remotes); do
+		if [ "$remote" = "$1" ]; then
+			return 0
+		fi
+	done
+	return 1
+}
+
 __git_list_merge_strategies ()
 {
 	git merge -s help 2>&1 |
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index f9993d2c005a..9f8be9ab1f3b 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -378,6 +378,15 @@ test_expect_success '__git_remotes - list remotes from $GIT_DIR/remotes and from
 	test_cmp expect actual
 '
 
+test_expect_success '__git_is_configured_remote' '
+	test_when_finished "git remote remove remote_1" &&
+	git remote add remote_1 git://remote_1 &&
+	test_when_finished "git remote remove remote_2" &&
+	git remote add remote_2 git://remote_2 &&
+	verbose __git_is_configured_remote remote_2 &&
+	test_must_fail __git_is_configured_remote non-existent
+'
+
 test_expect_success 'setup for ref completion' '
 	echo content >file1 &&
 	echo more >file2 &&
@@ -519,7 +528,7 @@ test_expect_success '__git_refs - configured remote - full refs - repo given on
 	test_cmp expected "$actual"
 '
 
-test_expect_failure '__git_refs - configured remote - remote name matches a directory' '
+test_expect_success '__git_refs - configured remote - remote name matches a directory' '
 	cat >expected <<-EOF &&
 	HEAD
 	branch
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 11/21] completion: don't list 'HEAD' when trying refs completion outside of a repo
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (9 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 10/21] completion: list refs from remote when remote's name matches a directory SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 12/21] completion: list short refs from a remote given as a URL SZEDER Gábor
                   ` (9 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

When refs completion is attempted while not in a git repository, the
completion script offers 'HEAD' erroneously.

Check early in __git_refs() that there is either a repository or a
remote to work on, and exit early if neither is given.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 4 ++++
 t/t9902-completion.sh                  | 2 +-
 2 files changed, 5 insertions(+), 1 deletion(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index b85ab27fb18a..f6ccfb708451 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -346,6 +346,10 @@ __git_refs ()
 	local from_local=y remote="${1-}"
 	local format refs
 
+	if [ -z "$dir" ] && [ -z "$remote" ]; then
+		return
+	fi
+
 	if [ -n "$remote" ]; then
 		if __git_is_configured_remote "$remote"; then
 			# configured remote takes precedence over a
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 9f8be9ab1f3b..f42a9ba9058f 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -629,7 +629,7 @@ test_expect_success '__git_refs - unique remote branches for git checkout DWIMer
 	test_cmp expected "$actual"
 '
 
-test_expect_failure '__git_refs - not in a git repository' '
+test_expect_success '__git_refs - not in a git repository' '
 	(
 		GIT_CEILING_DIRECTORIES="$ROOT" &&
 		export GIT_CEILING_DIRECTORIES &&
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 12/21] completion: list short refs from a remote given as a URL
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (10 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 11/21] completion: don't list 'HEAD' when trying refs completion outside of a repo SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 13/21] rev-parse: add '--absolute-git-dir' option SZEDER Gábor
                   ` (8 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

e832f5c09680 (completion: avoid ls-remote in certain scenarios,
2013-05-28) turned a 'git ls-remote <remote>' query into a 'git
for-each-ref refs/remotes/<remote>/' to improve responsiveness of
remote refs completion by avoiding potential network communication.
However, it inadvertently made impossible to complete short refs from
a remote given as a URL, e.g. 'git fetch git://server.com/repo.git
<TAB>', because there is, of course, no such thing as
'refs/remotes/git://server.com/repo.git'.

Since the previous commit we tell apart configured remotes, i.e. those
that can have a hierarchy under 'refs/remotes/', from others that
don't, including remotes given as URL, so we know when we can't use
the faster 'git for-each-ref'-based approach.

Resurrect the old, pre-e832f5c09680 'git ls-remote'-based code for the
latter case to support listing short refs from remotes given as a URL.
The code is slightly updated from the original to

  - take into account the path to the repository given on the command
    line (if any), and
  - omit 'ORIG_HEAD' from the query, as 'git ls-remote' will never
    list it anyway.

When the remote given to __git_refs() doesn't exist, then it will be
handled by this resurrected 'git ls-remote' query.  This code path
doesn't list 'HEAD' unconditionally, which has the nice side effect of
fixing two more expected test failures.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 22 ++++++++++++++++++----
 t/t9902-completion.sh                  |  6 +++---
 2 files changed, 21 insertions(+), 7 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index f6ccfb708451..6932d2a276eb 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -338,12 +338,13 @@ __git_tags ()
 # Lists refs from the local (by default) or from a remote repository.
 # It accepts 0, 1 or 2 arguments:
 # 1: The remote to lists refs from (optional; ignored, if set but empty).
+#    Can be the name of a configured remote, a path, or a URL.
 # 2: In addition to local refs, list unique branches from refs/remotes/ for
 #    'git checkout's tracking DWIMery (optional; ignored, if set but empty).
 __git_refs ()
 {
 	local i hash dir="$(__gitdir)" track="${2-}"
-	local from_local=y remote="${1-}"
+	local from_local=y remote="${1-}" named_remote=n
 	local format refs
 
 	if [ -z "$dir" ] && [ -z "$remote" ]; then
@@ -355,6 +356,7 @@ __git_refs ()
 			# configured remote takes precedence over a
 			# local directory with the same name
 			from_local=n
+			named_remote=y
 		else
 			if [ -d "$remote/.git" ]; then
 				dir="$remote/.git"
@@ -411,9 +413,21 @@ __git_refs ()
 		done
 		;;
 	*)
-		echo "HEAD"
-		git --git-dir="$dir" for-each-ref --format="%(refname:short)" -- \
-			"refs/remotes/$remote/" 2>/dev/null | sed -e "s#^$remote/##"
+		if [ "$named_remote" = y ]; then
+			echo "HEAD"
+			git --git-dir="$dir" for-each-ref --format="%(refname:short)" -- \
+				"refs/remotes/$remote/" 2>/dev/null | sed -e "s#^$remote/##"
+		else
+			git --git-dir="$dir" ls-remote "$remote" HEAD \
+				'refs/tags/*' 'refs/heads/*' 'refs/remotes/*' 2>/dev/null |
+			while read -r hash i; do
+				case "$i" in
+				*^{})	;;
+				refs/*)	echo "${i#refs/*/}" ;;
+				*)	echo "$i" ;;
+				esac
+			done
+		fi
 		;;
 	esac
 }
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index f42a9ba9058f..a1f69682e5ec 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -543,7 +543,7 @@ test_expect_success '__git_refs - configured remote - remote name matches a dire
 	test_cmp expected "$actual"
 '
 
-test_expect_failure '__git_refs - URL remote' '
+test_expect_success '__git_refs - URL remote' '
 	cat >expected <<-EOF &&
 	HEAD
 	branch
@@ -568,7 +568,7 @@ test_expect_success '__git_refs - URL remote - full refs' '
 	test_cmp expected "$actual"
 '
 
-test_expect_failure '__git_refs - non-existing remote' '
+test_expect_success '__git_refs - non-existing remote' '
 	(
 		cur= &&
 		__git_refs non-existing >"$actual"
@@ -584,7 +584,7 @@ test_expect_success '__git_refs - non-existing remote - full refs' '
 	test_must_be_empty "$actual"
 '
 
-test_expect_failure '__git_refs - non-existing URL remote' '
+test_expect_success '__git_refs - non-existing URL remote' '
 	(
 		cur= &&
 		__git_refs "file://$ROOT/non-existing" >"$actual"
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 13/21] rev-parse: add '--absolute-git-dir' option
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (11 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 12/21] completion: list short refs from a remote given as a URL SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-04-26  2:33   ` Mike Rappazzo
  2016-02-25 22:50 ` [PATCH 14/21] completion: don't offer commands when 'git --opt' needs an argument SZEDER Gábor
                   ` (7 subsequent siblings)
  20 siblings, 1 reply; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

Some scripts can benefit from not having to deal with the possibility
of relative paths to the repository, but the output of 'git rev-parse
--git-dir' can be a relative path.  Case in point: supporting 'git -C
<path>' in our Bash completion script turned out to be considerably
more difficult, error prone and required more subshells and git
processes when we had to cope with a relative path to the .git
directory.

Help these use cases and teach 'git rev-parse' a new
'--absolute-git-dir' option which always outputs a canonicalized
absolute path to the .git directory, regardless of whether the path is
discovered automatically or is specified via $GIT_DIR or 'git
--git-dir=<path>'.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 Documentation/git-rev-parse.txt |  4 ++++
 builtin/rev-parse.c             | 29 +++++++++++++++++++++--------
 t/t1500-rev-parse.sh            | 17 ++++++++++-------
 3 files changed, 35 insertions(+), 15 deletions(-)

diff --git a/Documentation/git-rev-parse.txt b/Documentation/git-rev-parse.txt
index b6c6326cdc7b..fb06e3118570 100644
--- a/Documentation/git-rev-parse.txt
+++ b/Documentation/git-rev-parse.txt
@@ -216,6 +216,10 @@ If `$GIT_DIR` is not defined and the current directory
 is not detected to lie in a Git repository or work tree
 print a message to stderr and exit with nonzero status.
 
+--absolute-git-dir::
+	Like `--git-dir`, but its output is always the canonicalized
+	absolute path.
+
 --git-common-dir::
 	Show `$GIT_COMMON_DIR` if defined, else `$GIT_DIR`.
 
diff --git a/builtin/rev-parse.c b/builtin/rev-parse.c
index cf8487b3b95f..90a4dd6032c0 100644
--- a/builtin/rev-parse.c
+++ b/builtin/rev-parse.c
@@ -744,17 +744,30 @@ int cmd_rev_parse(int argc, const char **argv, const char *prefix)
 				putchar('\n');
 				continue;
 			}
-			if (!strcmp(arg, "--git-dir")) {
+			if (!strcmp(arg, "--git-dir") ||
+			    !strcmp(arg, "--absolute-git-dir")) {
 				const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
 				char *cwd;
 				int len;
-				if (gitdir) {
-					puts(gitdir);
-					continue;
-				}
-				if (!prefix) {
-					puts(".git");
-					continue;
+				if (arg[2] == 'g') {	/* --git-dir */
+					if (gitdir) {
+						puts(gitdir);
+						continue;
+					}
+					if (!prefix) {
+						puts(".git");
+						continue;
+					}
+				} else {		/* --absolute-git-dir */
+					if (!gitdir && !prefix)
+						gitdir = ".git";
+					if (gitdir) {
+						char absolute_path[PATH_MAX];
+						if (!realpath(gitdir, absolute_path))
+							die_errno(_("unable to get absolute path"));
+						puts(absolute_path);
+						continue;
+					}
 				}
 				cwd = xgetcwd();
 				len = strlen(cwd);
diff --git a/t/t1500-rev-parse.sh b/t/t1500-rev-parse.sh
index 48ee07779d64..617fcd821309 100755
--- a/t/t1500-rev-parse.sh
+++ b/t/t1500-rev-parse.sh
@@ -31,23 +31,26 @@ test_rev_parse() {
 	"test '$1' = \"\$(git rev-parse --git-dir)\""
 	shift
 	[ $# -eq 0 ] && return
+
+	test_expect_success "$name: absolute-git-dir" \
+	"verbose test '$1' = \"\$(git rev-parse --absolute-git-dir)\""
 }
 
-# label is-bare is-inside-git is-inside-work prefix git-dir
+# label is-bare is-inside-git is-inside-work prefix git-dir absolute-git-dir
 
 ROOT=$(pwd)
 
-test_rev_parse toplevel false false true '' .git
+test_rev_parse toplevel false false true '' .git "$ROOT/.git"
 
 cd .git || exit 1
-test_rev_parse .git/ false true false '' .
+test_rev_parse .git/ false true false '' . "$ROOT/.git"
 cd objects || exit 1
-test_rev_parse .git/objects/ false true false '' "$ROOT/.git"
+test_rev_parse .git/objects/ false true false '' "$ROOT/.git" "$ROOT/.git"
 cd ../.. || exit 1
 
 mkdir -p sub/dir || exit 1
 cd sub/dir || exit 1
-test_rev_parse subdirectory false false true sub/dir/ "$ROOT/.git"
+test_rev_parse subdirectory false false true sub/dir/ "$ROOT/.git" "$ROOT/.git"
 cd ../.. || exit 1
 
 git config core.bare true
@@ -63,7 +66,7 @@ GIT_CONFIG="$(pwd)"/../.git/config
 export GIT_DIR GIT_CONFIG
 
 git config core.bare false
-test_rev_parse 'GIT_DIR=../.git, core.bare = false' false false true ''
+test_rev_parse 'GIT_DIR=../.git, core.bare = false' false false true '' "../.git" "$ROOT/.git"
 
 git config core.bare true
 test_rev_parse 'GIT_DIR=../.git, core.bare = true' true false false ''
@@ -76,7 +79,7 @@ GIT_DIR=../repo.git
 GIT_CONFIG="$(pwd)"/../repo.git/config
 
 git config core.bare false
-test_rev_parse 'GIT_DIR=../repo.git, core.bare = false' false false true ''
+test_rev_parse 'GIT_DIR=../repo.git, core.bare = false' false false true '' "../repo.git" "$ROOT/repo.git"
 
 git config core.bare true
 test_rev_parse 'GIT_DIR=../repo.git, core.bare = true' true false false ''
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 14/21] completion: don't offer commands when 'git --opt' needs an argument
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (12 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 13/21] rev-parse: add '--absolute-git-dir' option SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 15/21] completion: fix completion after 'git -C <path>' SZEDER Gábor
                   ` (6 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

The main git options '--git-dir', '-c', '-C', '--worktree' and
'--namespace' require an argument, but attempting completion right
after them lists git commands.

Don't offer anything right after these options, thus let Bash fall
back to filename completion, because

  - the three options '--git-dir', '-C' and '--worktree' do actually
    require a path argument, and

  - we don't complete the required argument of '-c' and '--namespace',
    and in that case the "standard" behavior of completion scripts in
    general is to not offer anything, but fall back to filename
    completion.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 6932d2a276eb..6027733a4b46 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -2666,6 +2666,14 @@ __git_main ()
 	done
 
 	if [ -z "$command" ]; then
+		case "$prev" in
+		--git-dir|-C|--work-tree)
+			return
+			;;
+		-c|--namespace)
+			return
+			;;
+		esac
 		case "$cur" in
 		--*)   __gitcomp "
 			--paginate
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 15/21] completion: fix completion after 'git -C <path>'
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (13 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 14/21] completion: don't offer commands when 'git --opt' needs an argument SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 16/21] completion: respect " SZEDER Gábor
                   ` (5 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

The main completion function finds the name of the git command by
iterating through all the words on the command line in search for the
first non-option-looking word.  As it is not aware of 'git -C's
mandatory path argument, if the '-C <path>' option is present, 'path'
will be the first such word and it will be mistaken for a git command.
This breaks completion in various ways:

 - If 'path' happens to match one of the commands supported by the
   completion script, then options of that command will be offered.

 - If 'path' doesn't match a supported command and doesn't contain any
   characters not allowed in Bash identifier names, then the
   completion script does basically nothing and Bash in turn falls
   back to filename completion for all subsequent words.

 - Otherwise, if 'path' does contain such an unallowed character, then
   it leads to a more or less ugly error message in the middle of the
   command line.  The standard '/' directory separator is such a
   character, and it happens to trigger one of the uglier errors:

     $ git -C some/path <TAB>sh.exe": declare: `_git_some/path': not a valid identifier
     error: invalid key: alias.some/path

Fix this by skipping 'git -C's mandatory path argument while iterating
over the words on the command line.  Extend the relevant test with
this case and, while at it, with cases that needed similar treatment
in the past ('--git-dir', '-c', '--work-tree' and '--namespace').

Additionally, silence the standard error of the 'declare' builtins
looking for the completion function associated with the git command
and of the 'git config' query for the aliased command.  So if git ever
learns a new option with a mandatory argument in the future, then,
though the completion script will again misbehave, at least the
command line will not be utterly disrupted by those error messages.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 8 ++++----
 t/t9902-completion.sh                  | 7 ++++++-
 2 files changed, 10 insertions(+), 5 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 6027733a4b46..5e5437d7a5c2 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -818,7 +818,7 @@ __git_aliases ()
 __git_aliased_command ()
 {
 	local word cmdline=$(git --git-dir="$(__gitdir)" \
-		config --get "alias.$1")
+		config --get "alias.$1" 2>/dev/null)
 	for word in $cmdline; do
 		case "$word" in
 		\!gitk|gitk)
@@ -2658,7 +2658,7 @@ __git_main ()
 		--git-dir)   ((c++)) ; __git_dir="${words[c]}" ;;
 		--bare)      __git_dir="." ;;
 		--help) command="help"; break ;;
-		-c|--work-tree|--namespace) ((c++)) ;;
+		-c|-C|--work-tree|--namespace) ((c++)) ;;
 		-*) ;;
 		*) command="$i"; break ;;
 		esac
@@ -2699,13 +2699,13 @@ __git_main ()
 	fi
 
 	local completion_func="_git_${command//-/_}"
-	declare -f $completion_func >/dev/null && $completion_func && return
+	declare -f $completion_func >/dev/null 2>/dev/null && $completion_func && return
 
 	local expansion=$(__git_aliased_command "$command")
 	if [ -n "$expansion" ]; then
 		words[1]=$expansion
 		completion_func="_git_${expansion//-/_}"
-		declare -f $completion_func >/dev/null && $completion_func
+		declare -f $completion_func >/dev/null 2>/dev/null && $completion_func
 	fi
 }
 
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index a1f69682e5ec..d172199ed256 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -754,7 +754,12 @@ test_expect_success 'general options plus command' '
 	test_completion "git --namespace=foo check" "checkout " &&
 	test_completion "git --paginate check" "checkout " &&
 	test_completion "git --info-path check" "checkout " &&
-	test_completion "git --no-replace-objects check" "checkout "
+	test_completion "git --no-replace-objects check" "checkout " &&
+	test_completion "git --git-dir some/path check" "checkout " &&
+	test_completion "git -c conf.var=value check" "checkout " &&
+	test_completion "git -C some/path check" "checkout " &&
+	test_completion "git --work-tree some/path check" "checkout " &&
+	test_completion "git --namespace name/space check" "checkout "
 '
 
 test_expect_success 'git --help completion' '
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 16/21] completion: respect 'git -C <path>'
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (14 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 15/21] completion: fix completion after 'git -C <path>' SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 17/21] completion: don't use __gitdir() for git commands SZEDER Gábor
                   ` (4 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

'git -C <path>' option(s) on the command line should be taken into
account during completion, because

  - like '--git-dir=<path>', it can lead us to a different repository,
    and

  - a few git commands executed in the completion script do actually
    care about from which directory they are executed from.

However, unlike '--git-dir=<path>', the '-C <path>' option can be
specified multiple times and their effect is cumulative, so we can't
just store a single '<path>' in a variable.  Nor can we simply
concatenate a path from '-C <path1> -C <path2> ...', because e.g. (in
an arguably pathological corner case) a relative path might be
followed by an absolute path.

Instead, store all '-C <path>' options word by word in the
$__git_C_args array in the main git completion function, and pass this
array, if present, to 'git rev-parse --absolute-git-dir' when
discovering the repository in __gitdir(), and let it take care of
multiple options, relative paths, absolute paths and everything.

Also pass all '-C <path> options via the $__git_C_args array to those
git executions which require a worktree and for which it matters from
which directory they are executed from.  There are only three such
cases:

  - 'git diff-index' and 'git ls-files' in __git_ls_files_helper()
    used for git-aware filename completion, and

  - the 'git ls-tree' used for completing the 'ref:path' notation.

The other git commands executed in the completion script don't need
these '-C <path>' options, because __gitdir() already took those
options into account.  It would not hurt them, either, but let's not
induce unnecessary code churn.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 19 ++++++--
 t/t9902-completion.sh                  | 87 ++++++++++++++++++++++++++++++++++
 2 files changed, 101 insertions(+), 5 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 5e5437d7a5c2..9ffea9580ff7 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -39,7 +39,11 @@ esac
 __gitdir ()
 {
 	if [ -z "${1-}" ]; then
-		if [ -n "${__git_dir-}" ]; then
+		if [ -n "${__git_C_args-}" ]; then
+			git "${__git_C_args[@]}" \
+				${__git_dir:+--git-dir="$__git_dir"} \
+				rev-parse --absolute-git-dir 2>/dev/null
+		elif [ -n "${__git_dir-}" ]; then
 			test -d "$__git_dir" || return 1
 			echo "$__git_dir"
 		elif [ -n "${GIT_DIR-}" ]; then
@@ -286,10 +290,10 @@ __git_ls_files_helper ()
 	local dir="$(__gitdir)"
 
 	if [ "$2" == "--committable" ]; then
-		git --git-dir="$dir" -C "$1" diff-index --name-only --relative HEAD
+		git ${__git_C_args:+"${__git_C_args[@]}"} --git-dir="$dir" -C "$1" diff-index --name-only --relative HEAD
 	else
 		# NOTE: $2 is not quoted in order to support multiple options
-		git --git-dir="$dir" -C "$1" ls-files --exclude-standard $2
+		git ${__git_C_args:+"${__git_C_args[@]}"} --git-dir="$dir" -C "$1" ls-files --exclude-standard $2
 	fi 2>/dev/null
 }
 
@@ -521,7 +525,7 @@ __git_complete_revlist_file ()
 		*)   pfx="$ref:$pfx" ;;
 		esac
 
-		__gitcomp_nl "$(git --git-dir="$(__gitdir)" ls-tree "$ls" 2>/dev/null \
+		__gitcomp_nl "$(git ${__git_C_args:+"${__git_C_args[@]}"} --git-dir="$(__gitdir)" ls-tree "$ls" 2>/dev/null \
 				| sed '/^100... blob /{
 				           s,^.*	,,
 				           s,$, ,
@@ -2650,6 +2654,7 @@ _git_whatchanged ()
 __git_main ()
 {
 	local i c=1 command __git_dir
+	local __git_C_args C_args_count=0
 
 	while [ $c -lt $cword ]; do
 		i="${words[c]}"
@@ -2658,7 +2663,11 @@ __git_main ()
 		--git-dir)   ((c++)) ; __git_dir="${words[c]}" ;;
 		--bare)      __git_dir="." ;;
 		--help) command="help"; break ;;
-		-c|-C|--work-tree|--namespace) ((c++)) ;;
+		-c|--work-tree|--namespace) ((c++)) ;;
+		-C)	__git_C_args[C_args_count++]=-C
+			((c++))
+			__git_C_args[C_args_count++]="${words[c]}"
+			;;
 		-*) ;;
 		*) command="$i"; break ;;
 		esac
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index d172199ed256..f68b3383caa3 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -211,6 +211,87 @@ test_expect_success '__gitdir - $GIT_DIR set while .git directory in parent' '
 	test_cmp expected "$actual"
 '
 
+test_expect_success '__gitdir - from command line while "git -C"' '
+	echo "$ROOT/.git" >expected &&
+	(
+		__git_dir="$ROOT/.git" &&
+		__git_C_args=(-C otherrepo) &&
+		__gitdir >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__gitdir - relative dir from command line and "git -C"' '
+	echo "$ROOT/otherrepo/.git" >expected &&
+	(
+		cd subdir &&
+		__git_dir="otherrepo/.git" &&
+		__git_C_args=(-C ..) &&
+		__gitdir >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__gitdir - $GIT_DIR set while "git -C"' '
+	echo "$ROOT/.git" >expected &&
+	(
+		GIT_DIR="$ROOT/.git" &&
+		export GIT_DIR &&
+		__git_C_args=(-C otherrepo) &&
+		__gitdir >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__gitdir - relative dir in $GIT_DIR and "git -C"' '
+	echo "$ROOT/otherrepo/.git" >expected &&
+	(
+		cd subdir &&
+		GIT_DIR="otherrepo/.git" &&
+		export GIT_DIR &&
+		__git_C_args=(-C ..) &&
+		__gitdir >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__gitdir - "git -C" while .git directory in cwd' '
+	echo "$ROOT/otherrepo/.git" >expected &&
+	(
+		__git_C_args=(-C otherrepo) &&
+		__gitdir >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__gitdir - "git -C" while cwd is a .git directory' '
+	echo "$ROOT/otherrepo/.git" >expected &&
+	(
+		cd .git &&
+		__git_C_args=(-C .. -C otherrepo) &&
+		__gitdir >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__gitdir - "git -C" while .git directory in parent' '
+	echo "$ROOT/otherrepo/.git" >expected &&
+	(
+		cd subdir &&
+		__git_C_args=(-C .. -C otherrepo) &&
+		__gitdir >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__gitdir - non-existing path in "git -C"' '
+	(
+		__git_C_args=(-C non-existing) &&
+		test_must_fail __gitdir >"$actual"
+	) &&
+	test_must_be_empty "$actual"
+'
+
 test_expect_success '__gitdir - non-existing path in $__git_dir' '
 	(
 		__git_dir="non-existing" &&
@@ -775,6 +856,12 @@ test_expect_success 'checkout completes ref names' '
 	EOF
 '
 
+test_expect_success 'git -C <path> checkout uses the right repo' '
+	test_completion "git -C subdir -C subsubdir -C .. -C ../otherrepo checkout b" <<-\EOF
+	branch Z
+	EOF
+'
+
 test_expect_success 'show completes all refs' '
 	test_completion "git show m" <<-\EOF
 	master Z
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 17/21] completion: don't use __gitdir() for git commands
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (15 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 16/21] completion: respect " SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 18/21] completion: consolidate silencing errors from " SZEDER Gábor
                   ` (3 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

Several completion functions contain the following pattern to run git
commands respecting the path to the repository specified on the
command line:

  git --git-dir="$(__gitdir)" <cmd> <options>

This imposes the overhead of fork()ing a subshell for the command
substitution and potentially fork()+exec()ing 'git rev-parse' inside
__gitdir().

Now, if neither '--gitdir=<path>' nor '-C <path>' options are
specified on the command line, then those git commands are perfectly
capable to discover the repository on their own.  If either one or
both of those options are specified on the command line, then, again,
the git commands could discover the repository, if we pass them all of
those options from the command line.

This means we don't have to run __gitdir() at all for git commands and
can spare its fork()+exec() overhead.

Use Bash parameter expansions to check the $__git_dir variable and
$__git_C_args array and to assemble the appropriate '--git-dir=<path>'
and '-C <path>' options if either one or both are present on the
command line.  These parameter expansions are, however, rather long,
so instead of changing all git executions and make already long lines
even longer, encapsulate running git with '--git-dir=<path> -C <path>'
options into the new __git() wrapper function.

There's one tricky case, though: in __git_refs() local refs are listed
with 'git for-each-ref', where "local" is not necessarily the
repository we are currently in, but it might mean a remote repository
in the filesystem (e.g. listing refs for 'git fetch /some/other/repo
<TAB>').  Use one-shot variable assignment to override $__git_dir with
the path of the repository where the refs should come from.  Although
one-shot variable assignments in front of shell functions are to be
avoided in our scripts in general, in the Bash completion script we
can do that safely.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 58 ++++++++++++++++++----------------
 1 file changed, 30 insertions(+), 28 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 9ffea9580ff7..c496f4026fc8 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -61,6 +61,14 @@ __gitdir ()
 	fi
 }
 
+# Runs git with all the options given as argument, respecting any
+# '--git-dir=<path>' and '-C <path>' options present on the command line
+__git ()
+{
+	git ${__git_C_args:+"${__git_C_args[@]}"} \
+		${__git_dir:+--git-dir="$__git_dir"} "$@"
+}
+
 # The following function is based on code from:
 #
 #   bash_completion - programmable completion functions for bash 3.2+
@@ -287,13 +295,11 @@ __gitcomp_file ()
 # argument, and using the options specified in the second argument.
 __git_ls_files_helper ()
 {
-	local dir="$(__gitdir)"
-
 	if [ "$2" == "--committable" ]; then
-		git ${__git_C_args:+"${__git_C_args[@]}"} --git-dir="$dir" -C "$1" diff-index --name-only --relative HEAD
+		__git -C "$1" diff-index --name-only --relative HEAD
 	else
 		# NOTE: $2 is not quoted in order to support multiple options
-		git ${__git_C_args:+"${__git_C_args[@]}"} --git-dir="$dir" -C "$1" ls-files --exclude-standard $2
+		__git -C "$1" ls-files --exclude-standard $2
 	fi 2>/dev/null
 }
 
@@ -323,8 +329,7 @@ __git_heads ()
 {
 	local dir="$(__gitdir)"
 	if [ -d "$dir" ]; then
-		git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
-			refs/heads
+		__git for-each-ref --format='%(refname:short)' refs/heads
 		return
 	fi
 }
@@ -333,8 +338,7 @@ __git_tags ()
 {
 	local dir="$(__gitdir)"
 	if [ -d "$dir" ]; then
-		git --git-dir="$dir" for-each-ref --format='%(refname:short)' \
-			refs/tags
+		__git for-each-ref --format='%(refname:short)' refs/tags
 		return
 	fi
 }
@@ -387,14 +391,14 @@ __git_refs ()
 			refs="refs/tags refs/heads refs/remotes"
 			;;
 		esac
-		git --git-dir="$dir" for-each-ref --format="%($format)" \
+		__git_dir="$dir" __git for-each-ref --format="%($format)" \
 			$refs
 		if [ -n "$track" ]; then
 			# employ the heuristic used by git checkout
 			# Try to find a remote branch that matches the completion word
 			# but only output if the branch name is unique
 			local ref entry
-			git --git-dir="$dir" for-each-ref --shell --format="ref=%(refname:short)" \
+			__git for-each-ref --shell --format="ref=%(refname:short)" \
 				"refs/remotes/" | \
 			while read -r entry; do
 				eval "$entry"
@@ -408,7 +412,7 @@ __git_refs ()
 	fi
 	case "$cur" in
 	refs|refs/*)
-		git --git-dir="$dir" ls-remote "$remote" "$cur*" 2>/dev/null | \
+		__git ls-remote "$remote" "$cur*" 2>/dev/null | \
 		while read -r hash i; do
 			case "$i" in
 			*^{}) ;;
@@ -419,10 +423,10 @@ __git_refs ()
 	*)
 		if [ "$named_remote" = y ]; then
 			echo "HEAD"
-			git --git-dir="$dir" for-each-ref --format="%(refname:short)" -- \
+			__git for-each-ref --format="%(refname:short)" -- \
 				"refs/remotes/$remote/" 2>/dev/null | sed -e "s#^$remote/##"
 		else
-			git --git-dir="$dir" ls-remote "$remote" HEAD \
+			__git ls-remote "$remote" HEAD \
 				'refs/tags/*' 'refs/heads/*' 'refs/remotes/*' 2>/dev/null |
 			while read -r hash i; do
 				case "$i" in
@@ -449,7 +453,7 @@ __git_refs2 ()
 __git_refs_remotes ()
 {
 	local i hash
-	git --git-dir="$(__gitdir)" ls-remote "$1" 'refs/heads/*' 2>/dev/null | \
+	__git ls-remote "$1" 'refs/heads/*' 2>/dev/null | \
 	while read -r hash i; do
 		echo "$i:refs/remotes/$1/${i#refs/heads/}"
 	done
@@ -459,7 +463,7 @@ __git_remotes ()
 {
 	local d="$(__gitdir)"
 	test -d "$d/remotes" && ls -1 "$d/remotes"
-	git --git-dir="$d" remote
+	__git remote
 }
 
 # Returns true if $1 matches the name of a configured remote, false otherwise.
@@ -525,7 +529,7 @@ __git_complete_revlist_file ()
 		*)   pfx="$ref:$pfx" ;;
 		esac
 
-		__gitcomp_nl "$(git ${__git_C_args:+"${__git_C_args[@]}"} --git-dir="$(__gitdir)" ls-tree "$ls" 2>/dev/null \
+		__gitcomp_nl "$(__git ls-tree "$ls" 2>/dev/null \
 				| sed '/^100... blob /{
 				           s,^.*	,,
 				           s,$, ,
@@ -803,7 +807,7 @@ __git_compute_porcelain_commands ()
 __git_get_config_variables ()
 {
 	local section="$1" i IFS=$'\n'
-	for i in $(git --git-dir="$(__gitdir)" config --name-only --get-regexp "^$section\..*" 2>/dev/null); do
+	for i in $(__git config --name-only --get-regexp "^$section\..*" 2>/dev/null); do
 		echo "${i#$section.}"
 	done
 }
@@ -821,8 +825,7 @@ __git_aliases ()
 # __git_aliased_command requires 1 argument
 __git_aliased_command ()
 {
-	local word cmdline=$(git --git-dir="$(__gitdir)" \
-		config --get "alias.$1" 2>/dev/null)
+	local word cmdline=$(__git config --get "alias.$1" 2>/dev/null)
 	for word in $cmdline; do
 		case "$word" in
 		\!gitk|gitk)
@@ -1192,7 +1195,7 @@ _git_commit ()
 		return
 	esac
 
-	if git --git-dir="$(__gitdir)" rev-parse --verify --quiet HEAD >/dev/null; then
+	if __git rev-parse --verify --quiet HEAD >/dev/null; then
 		__git_complete_index_file "--committable"
 	else
 		# This is the first commit
@@ -1778,7 +1781,7 @@ _git_send_email ()
 	case "$prev" in
 	--to|--cc|--bcc|--from)
 		__gitcomp "
-		$(git --git-dir="$(__gitdir)" send-email --dump-aliases 2>/dev/null)
+		$(__git send-email --dump-aliases 2>/dev/null)
 		"
 		return
 		;;
@@ -1810,7 +1813,7 @@ _git_send_email ()
 		;;
 	--to=*|--cc=*|--bcc=*|--from=*)
 		__gitcomp "
-		$(git --git-dir="$(__gitdir)" send-email --dump-aliases 2>/dev/null)
+		$(__git send-email --dump-aliases 2>/dev/null)
 		" "" "${cur#--*=}"
 		return
 		;;
@@ -1855,7 +1858,7 @@ __git_config_get_set_variables ()
 		c=$((--c))
 	done
 
-	git --git-dir="$(__gitdir)" config $config_file --name-only --list 2>/dev/null
+	__git config $config_file --name-only --list 2>/dev/null
 }
 
 _git_config ()
@@ -1890,9 +1893,8 @@ _git_config ()
 	remote.*.push)
 		local remote="${prev#remote.}"
 		remote="${remote%.push}"
-		__gitcomp_nl "$(git --git-dir="$(__gitdir)" \
-			for-each-ref --format='%(refname):%(refname)' \
-			refs/heads)"
+		__gitcomp_nl "$(__git for-each-ref
+			--format='%(refname):%(refname)' refs/heads)"
 		return
 		;;
 	pull.twohead|pull.octopus)
@@ -2475,12 +2477,12 @@ _git_stash ()
 			if [ $cword -eq 3 ]; then
 				__gitcomp_nl "$(__git_refs)";
 			else
-				__gitcomp_nl "$(git --git-dir="$(__gitdir)" stash list \
+				__gitcomp_nl "$(__git stash list \
 						| sed -n -e 's/:.*//p')"
 			fi
 			;;
 		show,*|apply,*|drop,*|pop,*)
-			__gitcomp_nl "$(git --git-dir="$(__gitdir)" stash list \
+			__gitcomp_nl "$(__git stash list \
 					| sed -n -e 's/:.*//p')"
 			;;
 		*)
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 18/21] completion: consolidate silencing errors from git commands
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (16 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 17/21] completion: don't use __gitdir() for git commands SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 19/21] completion: don't guard git executions with __gitdir() SZEDER Gábor
                   ` (2 subsequent siblings)
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

Outputting error messages during completion is bad: they disrupt the
command line, can't be deleted, and the user is forced to Ctrl-C and
start over most of the time.  We already silence stderr of many git
commands in our Bash completion script, but there are still some in
there that can spew error messages when something goes wrong.

We could add the missing stderr redirections to all the remaining
places, but instead let's leverage that git commands are now executed
through the previously introduced __git() wrapper function, and
redirect standard error to /dev/null only in that function.  This way
we need only one redirection to take care of errors from almost all
git commands.  Redirecting standard error of the __git() wrapper
function thus became redundant, remove them.

The exceptions, i.e. the repo-independent git executions and those in
the __gitdir() function that don't go through __git() already have
their standard error silenced.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 28 ++++++++++++----------------
 1 file changed, 12 insertions(+), 16 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index c496f4026fc8..2d0bd018701e 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -66,7 +66,7 @@ __gitdir ()
 __git ()
 {
 	git ${__git_C_args:+"${__git_C_args[@]}"} \
-		${__git_dir:+--git-dir="$__git_dir"} "$@"
+		${__git_dir:+--git-dir="$__git_dir"} "$@" 2>/dev/null
 }
 
 # The following function is based on code from:
@@ -300,7 +300,7 @@ __git_ls_files_helper ()
 	else
 		# NOTE: $2 is not quoted in order to support multiple options
 		__git -C "$1" ls-files --exclude-standard $2
-	fi 2>/dev/null
+	fi
 }
 
 
@@ -412,7 +412,7 @@ __git_refs ()
 	fi
 	case "$cur" in
 	refs|refs/*)
-		__git ls-remote "$remote" "$cur*" 2>/dev/null | \
+		__git ls-remote "$remote" "$cur*" | \
 		while read -r hash i; do
 			case "$i" in
 			*^{}) ;;
@@ -424,10 +424,10 @@ __git_refs ()
 		if [ "$named_remote" = y ]; then
 			echo "HEAD"
 			__git for-each-ref --format="%(refname:short)" -- \
-				"refs/remotes/$remote/" 2>/dev/null | sed -e "s#^$remote/##"
+				"refs/remotes/$remote/" | sed -e "s#^$remote/##"
 		else
 			__git ls-remote "$remote" HEAD \
-				'refs/tags/*' 'refs/heads/*' 'refs/remotes/*' 2>/dev/null |
+				'refs/tags/*' 'refs/heads/*' 'refs/remotes/*' |
 			while read -r hash i; do
 				case "$i" in
 				*^{})	;;
@@ -453,7 +453,7 @@ __git_refs2 ()
 __git_refs_remotes ()
 {
 	local i hash
-	__git ls-remote "$1" 'refs/heads/*' 2>/dev/null | \
+	__git ls-remote "$1" 'refs/heads/*' | \
 	while read -r hash i; do
 		echo "$i:refs/remotes/$1/${i#refs/heads/}"
 	done
@@ -529,7 +529,7 @@ __git_complete_revlist_file ()
 		*)   pfx="$ref:$pfx" ;;
 		esac
 
-		__gitcomp_nl "$(__git ls-tree "$ls" 2>/dev/null \
+		__gitcomp_nl "$(__git ls-tree "$ls" \
 				| sed '/^100... blob /{
 				           s,^.*	,,
 				           s,$, ,
@@ -807,7 +807,7 @@ __git_compute_porcelain_commands ()
 __git_get_config_variables ()
 {
 	local section="$1" i IFS=$'\n'
-	for i in $(__git config --name-only --get-regexp "^$section\..*" 2>/dev/null); do
+	for i in $(__git config --name-only --get-regexp "^$section\..*"); do
 		echo "${i#$section.}"
 	done
 }
@@ -825,7 +825,7 @@ __git_aliases ()
 # __git_aliased_command requires 1 argument
 __git_aliased_command ()
 {
-	local word cmdline=$(__git config --get "alias.$1" 2>/dev/null)
+	local word cmdline=$(__git config --get "alias.$1")
 	for word in $cmdline; do
 		case "$word" in
 		\!gitk|gitk)
@@ -1780,9 +1780,7 @@ _git_send_email ()
 {
 	case "$prev" in
 	--to|--cc|--bcc|--from)
-		__gitcomp "
-		$(__git send-email --dump-aliases 2>/dev/null)
-		"
+		__gitcomp "$(__git send-email --dump-aliases)"
 		return
 		;;
 	esac
@@ -1812,9 +1810,7 @@ _git_send_email ()
 		return
 		;;
 	--to=*|--cc=*|--bcc=*|--from=*)
-		__gitcomp "
-		$(__git send-email --dump-aliases 2>/dev/null)
-		" "" "${cur#--*=}"
+		__gitcomp "$(__git send-email --dump-aliases)" "" "${cur#--*=}"
 		return
 		;;
 	--*)
@@ -1858,7 +1854,7 @@ __git_config_get_set_variables ()
 		c=$((--c))
 	done
 
-	__git config $config_file --name-only --list 2>/dev/null
+	__git config $config_file --name-only --list
 }
 
 _git_config ()
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 19/21] completion: don't guard git executions with __gitdir()
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (17 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 18/21] completion: consolidate silencing errors from " SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 20/21] completion: extract repository discovery from __gitdir() SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 21/21] completion: cache the path to the repository SZEDER Gábor
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

Three completion functions first run __gitdir() and check that the
path it outputs exists, i.e. that there is a git repository, and run a
git command only if there is one.

After the previous changes in this series there are no further uses of
__gitdir()'s output in these functions besides those checks.  And
those checks are unnecessary, because we can just execute those git
commands outside of a repository and let them error out.  We don't
perform such a check in other places either.

Remove this check and the __gitdir() call from these functions,
sparing the fork()+exec() overhead of the command substitution and the
potential 'git rev-parse' execution.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 32 +++++++++++---------------------
 1 file changed, 11 insertions(+), 21 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 2d0bd018701e..605ab84296a2 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -312,35 +312,25 @@ __git_ls_files_helper ()
 #    slash.
 __git_index_files ()
 {
-	local dir="$(__gitdir)" root="${2-.}" file
-
-	if [ -d "$dir" ]; then
-		__git_ls_files_helper "$root" "$1" |
-		while read -r file; do
-			case "$file" in
-			?*/*) echo "${file%%/*}" ;;
-			*) echo "$file" ;;
-			esac
-		done | sort | uniq
-	fi
+	local root="${2-.}" file
+
+	__git_ls_files_helper "$root" "$1" |
+	while read -r file; do
+		case "$file" in
+		?*/*) echo "${file%%/*}" ;;
+		*) echo "$file" ;;
+		esac
+	done | sort | uniq
 }
 
 __git_heads ()
 {
-	local dir="$(__gitdir)"
-	if [ -d "$dir" ]; then
-		__git for-each-ref --format='%(refname:short)' refs/heads
-		return
-	fi
+	__git for-each-ref --format='%(refname:short)' refs/heads
 }
 
 __git_tags ()
 {
-	local dir="$(__gitdir)"
-	if [ -d "$dir" ]; then
-		__git for-each-ref --format='%(refname:short)' refs/tags
-		return
-	fi
+	__git for-each-ref --format='%(refname:short)' refs/tags
 }
 
 # Lists refs from the local (by default) or from a remote repository.
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 20/21] completion: extract repository discovery from __gitdir()
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (18 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 19/21] completion: don't guard git executions with __gitdir() SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  2016-02-25 22:50 ` [PATCH 21/21] completion: cache the path to the repository SZEDER Gábor
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

To prepare for caching the path to the repository in the following
commit, extract the repository discovering part of __gitdir() into the
__git_find_repo_path() helper function, which stores the found path in
the $__git_repo_path variable instead of printing it.  Make __gitdir()
a wrapper around this new function.  Declare $__git_repo_path local in
the toplevel completion functions __git_main() and __gitk_main() to
prevent it from leaking into the environment and influencing
subsequent completions.

Adjust tests checking __gitdir() or any other completion function
calling __gitdir() to perform those checks in a subshell to prevent
$__git_repo_path from leaking into the test environment.  Otherwise
leave the tests unchanged to demonstrate that this change doesn't
alter __gitdir()'s behavior.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash | 42 +++++++++++++++++++++-------------
 t/t9902-completion.sh                  | 22 +++++++++++++-----
 2 files changed, 42 insertions(+), 22 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 605ab84296a2..69000a33bcfa 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -34,26 +34,35 @@ case "$COMP_WORDBREAKS" in
 *)   COMP_WORDBREAKS="$COMP_WORDBREAKS:"
 esac
 
+# Discovers the path to the git repository taking any '--git-dir=<path>' and
+# '-C <path>' options into account and stores it in the $__git_repo_path
+# variable.
+__git_find_repo_path ()
+{
+	if [ -n "${__git_C_args-}" ]; then
+		__git_repo_path="$(git "${__git_C_args[@]}" \
+			${__git_dir:+--git-dir="$__git_dir"} \
+			rev-parse --absolute-git-dir 2>/dev/null)"
+	elif [ -n "${__git_dir-}" ]; then
+		test -d "$__git_dir" &&
+		__git_repo_path="$__git_dir"
+	elif [ -n "${GIT_DIR-}" ]; then
+		test -d "${GIT_DIR-}" &&
+		__git_repo_path="$GIT_DIR"
+	elif [ -d .git ]; then
+		__git_repo_path=.git
+	else
+		__git_repo_path="$(git rev-parse --git-dir 2>/dev/null)"
+	fi
+}
+
 # __gitdir accepts 0 or 1 arguments (i.e., location)
 # returns location of .git repo
 __gitdir ()
 {
 	if [ -z "${1-}" ]; then
-		if [ -n "${__git_C_args-}" ]; then
-			git "${__git_C_args[@]}" \
-				${__git_dir:+--git-dir="$__git_dir"} \
-				rev-parse --absolute-git-dir 2>/dev/null
-		elif [ -n "${__git_dir-}" ]; then
-			test -d "$__git_dir" || return 1
-			echo "$__git_dir"
-		elif [ -n "${GIT_DIR-}" ]; then
-			test -d "${GIT_DIR-}" || return 1
-			echo "$GIT_DIR"
-		elif [ -d .git ]; then
-			echo .git
-		else
-			git rev-parse --git-dir 2>/dev/null
-		fi
+		__git_find_repo_path || return 1
+		echo "$__git_repo_path"
 	elif [ -d "$1/.git" ]; then
 		echo "$1/.git"
 	else
@@ -2641,7 +2650,7 @@ _git_whatchanged ()
 
 __git_main ()
 {
-	local i c=1 command __git_dir
+	local i c=1 command __git_dir __git_repo_path
 	local __git_C_args C_args_count=0
 
 	while [ $c -lt $cword ]; do
@@ -2710,6 +2719,7 @@ __gitk_main ()
 {
 	__git_has_doubledash && return
 
+	local __git_repo_path
 	local g="$(__gitdir)"
 	local merge=""
 	if [ -f "$g/MERGE_HEAD" ]; then
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index f68b3383caa3..d44e72066328 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -147,19 +147,25 @@ test_expect_success '__gitdir - from command line (through $__git_dir)' '
 
 test_expect_success '__gitdir - repo as argument' '
 	echo "otherrepo/.git" >expected &&
-	__gitdir "otherrepo" >"$actual" &&
+	(
+		__gitdir "otherrepo" >"$actual"
+	) &&
 	test_cmp expected "$actual"
 '
 
 test_expect_success '__gitdir - remote as argument' '
 	echo "remote" >expected &&
-	__gitdir "remote" >"$actual" &&
+	(
+		__gitdir "remote" >"$actual"
+	) &&
 	test_cmp expected "$actual"
 '
 
 test_expect_success '__gitdir - .git directory in cwd' '
 	echo ".git" >expected &&
-	__gitdir >"$actual" &&
+	(
+		__gitdir >"$actual"
+	) &&
 	test_cmp expected "$actual"
 '
 
@@ -455,7 +461,9 @@ test_expect_success '__git_remotes - list remotes from $GIT_DIR/remotes and from
 	git remote add remote_in_config_1 git://remote_1 &&
 	test_when_finished "git remote remove remote_in_config_2" &&
 	git remote add remote_in_config_2 git://remote_2 &&
-	__git_remotes >actual &&
+	(
+		__git_remotes >actual
+	) &&
 	test_cmp expect actual
 '
 
@@ -464,8 +472,10 @@ test_expect_success '__git_is_configured_remote' '
 	git remote add remote_1 git://remote_1 &&
 	test_when_finished "git remote remove remote_2" &&
 	git remote add remote_2 git://remote_2 &&
-	verbose __git_is_configured_remote remote_2 &&
-	test_must_fail __git_is_configured_remote non-existent
+	(
+		verbose __git_is_configured_remote remote_2 &&
+		test_must_fail __git_is_configured_remote non-existent
+	)
 '
 
 test_expect_success 'setup for ref completion' '
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* [PATCH 21/21] completion: cache the path to the repository
  2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
                   ` (19 preceding siblings ...)
  2016-02-25 22:50 ` [PATCH 20/21] completion: extract repository discovery from __gitdir() SZEDER Gábor
@ 2016-02-25 22:50 ` SZEDER Gábor
  20 siblings, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-02-25 22:50 UTC (permalink / raw)
  To: Junio C Hamano; +Cc: Jeff King, Sebastian Schuberth, git, SZEDER Gábor

After the previous changes in this series there are only a handful of
$(__gitdir) command substitutions left in the completion script, but
there is still a bit of room for improvements:

  1. The command substitution involves the forking of a subshell,
     which has considerable overhead on some platforms.

  2. There are a few cases, where this command substitution is
     executed more than once during a single completion, which means
     multiple subshells and possibly multiple 'git rev-parse'
     executions.  __gitdir() is invoked twice while completing refs
     for e.g. 'git log', 'git rebase', 'gitk', or while completing
     remote refs for 'git fetch' or 'git push'.

Both of these points can be addressed by using the
__git_find_repo_path() helper function introduced in the previous
commit:

  1. __git_find_repo_path() stores the path to the repository in a
     variable instead of printing it, so the command substitution
     around the function can be avoided.  Or rather: the command
     substitution should be avoided to make the new value of the
     variable set inside the function visible to the callers.
     (Yes, there is now a command substitution inside
     __git_find_repo_path() around each 'git rev-parse', but that's
     executed only if necessary, and only once per completion, see
     point 2. below.)

  2. $__git_repo_path, the variable holding the path to the
     repository, is declared local in the toplevel completion
     functions __git_main() and __gitk_main().  Thus, once set, the
     path is visible in all completion functions, including all
     subsequent calls to __git_find_repo_path(), meaning that they
     wouldn't have to re-discover the path to the repository.

So call __git_find_repo_path() and use $__git_repo_path instead of the
$(__gitdir) command substitution to access paths in the .git
directory.  Turn tests checking __gitdir()'s repository discovery into
tests of __git_find_repo_path() such that only the tested function
changes but the expected results don't, ensuring that repo discovery
keeps working as it did before.

As __gitdir() is not used anymore in the completion script, mark it as
deprecated and direct users' attention to __git_find_repo_path() and
$__git_repo_path.  Yet keep four __gitdir() tests to ensure that it
handles success and failure of __git_find_repo_path() and that it
still handles its optional remote argument.

Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
---
 contrib/completion/git-completion.bash |  46 ++++++----
 t/t9902-completion.sh                  | 155 +++++++++++++++++++++------------
 2 files changed, 126 insertions(+), 75 deletions(-)

diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index 69000a33bcfa..7300a2b64bab 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -39,6 +39,11 @@ esac
 # variable.
 __git_find_repo_path ()
 {
+	if [ -n "$__git_repo_path" ]; then
+		# we already know where it is
+		return
+	fi
+
 	if [ -n "${__git_C_args-}" ]; then
 		__git_repo_path="$(git "${__git_C_args[@]}" \
 			${__git_dir:+--git-dir="$__git_dir"} \
@@ -56,6 +61,7 @@ __git_find_repo_path ()
 	fi
 }
 
+# Deprecated: use __git_find_repo_path() and $__git_repo_path instead
 # __gitdir accepts 0 or 1 arguments (i.e., location)
 # returns location of .git repo
 __gitdir ()
@@ -350,10 +356,13 @@ __git_tags ()
 #    'git checkout's tracking DWIMery (optional; ignored, if set but empty).
 __git_refs ()
 {
-	local i hash dir="$(__gitdir)" track="${2-}"
+	local i hash dir track="${2-}"
 	local from_local=y remote="${1-}" named_remote=n
 	local format refs
 
+	__git_find_repo_path
+	dir="$__git_repo_path"
+
 	if [ -z "$dir" ] && [ -z "$remote" ]; then
 		return
 	fi
@@ -460,8 +469,8 @@ __git_refs_remotes ()
 
 __git_remotes ()
 {
-	local d="$(__gitdir)"
-	test -d "$d/remotes" && ls -1 "$d/remotes"
+	__git_find_repo_path
+	test -d "$__git_repo_path/remotes" && ls -1 "$__git_repo_path/remotes"
 	__git remote
 }
 
@@ -915,8 +924,8 @@ __git_whitespacelist="nowarn warn error error-all fix"
 
 _git_am ()
 {
-	local dir="$(__gitdir)"
-	if [ -d "$dir"/rebase-apply ]; then
+	__git_find_repo_path
+	if [ -d "$__git_repo_path"/rebase-apply ]; then
 		__gitcomp "--skip --continue --resolved --abort"
 		return
 	fi
@@ -999,7 +1008,8 @@ _git_bisect ()
 	local subcommands="start bad good skip reset visualize replay log run"
 	local subcommand="$(__git_find_on_cmdline "$subcommands")"
 	if [ -z "$subcommand" ]; then
-		if [ -f "$(__gitdir)"/BISECT_START ]; then
+		__git_find_repo_path
+		if [ -f "$__git_repo_path"/BISECT_START ]; then
 			__gitcomp "$subcommands"
 		else
 			__gitcomp "replay start"
@@ -1104,8 +1114,8 @@ _git_cherry ()
 
 _git_cherry_pick ()
 {
-	local dir="$(__gitdir)"
-	if [ -f "$dir"/CHERRY_PICK_HEAD ]; then
+	__git_find_repo_path
+	if [ -f "$__git_repo_path"/CHERRY_PICK_HEAD ]; then
 		__gitcomp "--continue --quit --abort"
 		return
 	fi
@@ -1486,10 +1496,10 @@ __git_log_date_formats="relative iso8601 rfc2822 short local default raw"
 _git_log ()
 {
 	__git_has_doubledash && return
+	__git_find_repo_path
 
-	local g="$(__gitdir)"
 	local merge=""
-	if [ -f "$g/MERGE_HEAD" ]; then
+	if [ -f "$__git_repo_path/MERGE_HEAD" ]; then
 		merge="--merge"
 	fi
 	case "$cur" in
@@ -1727,11 +1737,12 @@ _git_push ()
 
 _git_rebase ()
 {
-	local dir="$(__gitdir)"
-	if [ -f "$dir"/rebase-merge/interactive ]; then
+	__git_find_repo_path
+	if [ -f "$__git_repo_path"/rebase-merge/interactive ]; then
 		__gitcomp "--continue --skip --abort --edit-todo"
 		return
-	elif [ -d "$dir"/rebase-apply ] || [ -d "$dir"/rebase-merge ]; then
+	elif [ -d "$__git_repo_path"/rebase-apply ] || \
+	     [ -d "$__git_repo_path"/rebase-merge ]; then
 		__gitcomp "--continue --skip --abort"
 		return
 	fi
@@ -2355,8 +2366,8 @@ _git_reset ()
 
 _git_revert ()
 {
-	local dir="$(__gitdir)"
-	if [ -f "$dir"/REVERT_HEAD ]; then
+	__git_find_repo_path
+	if [ -f "$__git_repo_path"/REVERT_HEAD ]; then
 		__gitcomp "--continue --quit --abort"
 		return
 	fi
@@ -2720,9 +2731,10 @@ __gitk_main ()
 	__git_has_doubledash && return
 
 	local __git_repo_path
-	local g="$(__gitdir)"
+	__git_find_repo_path
+
 	local merge=""
-	if [ -f "$g/MERGE_HEAD" ]; then
+	if [ -f "$__git_repo_path/MERGE_HEAD" ]; then
 		merge="--merge"
 	fi
 	case "$cur" in
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index d44e72066328..458850641635 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -131,213 +131,216 @@ else
 	ROOT="$(pwd)"
 fi
 
-test_expect_success 'setup for __gitdir tests' '
+test_expect_success 'setup for __git_find_repo_path/__gitdir tests' '
 	mkdir -p subdir/subsubdir &&
 	git init otherrepo
 '
 
-test_expect_success '__gitdir - from command line (through $__git_dir)' '
+test_expect_success '__git_find_repo_path - from command line (through $__git_dir)' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	(
 		__git_dir="$ROOT/otherrepo/.git" &&
-		__gitdir >"$actual"
-	) &&
-	test_cmp expected "$actual"
-'
-
-test_expect_success '__gitdir - repo as argument' '
-	echo "otherrepo/.git" >expected &&
-	(
-		__gitdir "otherrepo" >"$actual"
-	) &&
-	test_cmp expected "$actual"
-'
-
-test_expect_success '__gitdir - remote as argument' '
-	echo "remote" >expected &&
-	(
-		__gitdir "remote" >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - .git directory in cwd' '
+test_expect_success '__git_find_repo_path - .git directory in cwd' '
 	echo ".git" >expected &&
 	(
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - .git directory in parent' '
+test_expect_success '__git_find_repo_path - .git directory in parent' '
 	echo "$ROOT/.git" >expected &&
 	(
 		cd subdir/subsubdir &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - cwd is a .git directory' '
+test_expect_success '__git_find_repo_path - cwd is a .git directory' '
 	echo "." >expected &&
 	(
 		cd .git &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - parent is a .git directory' '
+test_expect_success '__git_find_repo_path - parent is a .git directory' '
 	echo "$ROOT/.git" >expected &&
 	(
 		cd .git/refs/heads &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - $GIT_DIR set while .git directory in cwd' '
+test_expect_success '__git_find_repo_path - $GIT_DIR set while .git directory in cwd' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	(
 		GIT_DIR="$ROOT/otherrepo/.git" &&
 		export GIT_DIR &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - $GIT_DIR set while .git directory in parent' '
+test_expect_success '__git_find_repo_path - $GIT_DIR set while .git directory in parent' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	(
 		GIT_DIR="$ROOT/otherrepo/.git" &&
 		export GIT_DIR &&
 		cd subdir &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - from command line while "git -C"' '
+test_expect_success '__git_find_repo_path - from command line while "git -C"' '
 	echo "$ROOT/.git" >expected &&
 	(
 		__git_dir="$ROOT/.git" &&
 		__git_C_args=(-C otherrepo) &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - relative dir from command line and "git -C"' '
+test_expect_success '__git_find_repo_path - relative dir from command line and "git -C"' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	(
 		cd subdir &&
 		__git_dir="otherrepo/.git" &&
 		__git_C_args=(-C ..) &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - $GIT_DIR set while "git -C"' '
+test_expect_success '__git_find_repo_path - $GIT_DIR set while "git -C"' '
 	echo "$ROOT/.git" >expected &&
 	(
 		GIT_DIR="$ROOT/.git" &&
 		export GIT_DIR &&
 		__git_C_args=(-C otherrepo) &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - relative dir in $GIT_DIR and "git -C"' '
+test_expect_success '__git_find_repo_path - relative dir in $GIT_DIR and "git -C"' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	(
 		cd subdir &&
 		GIT_DIR="otherrepo/.git" &&
 		export GIT_DIR &&
 		__git_C_args=(-C ..) &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - "git -C" while .git directory in cwd' '
+test_expect_success '__git_find_repo_path - "git -C" while .git directory in cwd' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	(
 		__git_C_args=(-C otherrepo) &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - "git -C" while cwd is a .git directory' '
+test_expect_success '__git_find_repo_path - "git -C" while cwd is a .git directory' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	(
 		cd .git &&
 		__git_C_args=(-C .. -C otherrepo) &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - "git -C" while .git directory in parent' '
+test_expect_success '__git_find_repo_path - "git -C" while .git directory in parent' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	(
 		cd subdir &&
 		__git_C_args=(-C .. -C otherrepo) &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - non-existing path in "git -C"' '
+test_expect_success '__git_find_repo_path - non-existing path in "git -C"' '
 	(
 		__git_C_args=(-C non-existing) &&
-		test_must_fail __gitdir >"$actual"
+		test_must_fail __git_find_repo_path &&
+		printf "$__git_repo_path" >"$actual"
 	) &&
 	test_must_be_empty "$actual"
 '
 
-test_expect_success '__gitdir - non-existing path in $__git_dir' '
+test_expect_success '__git_find_repo_path - non-existing path in $__git_dir' '
 	(
 		__git_dir="non-existing" &&
-		test_must_fail __gitdir >"$actual"
+		test_must_fail __git_find_repo_path &&
+		printf "$__git_repo_path" >"$actual"
 	) &&
 	test_must_be_empty "$actual"
 '
 
-test_expect_success '__gitdir - non-existing $GIT_DIR' '
+test_expect_success '__git_find_repo_path - non-existing $GIT_DIR' '
 	(
 		GIT_DIR="$ROOT/non-existing" &&
 		export GIT_DIR &&
-		test_must_fail __gitdir >"$actual"
+		test_must_fail __git_find_repo_path &&
+		printf "$__git_repo_path" >"$actual"
 	) &&
 	test_must_be_empty "$actual"
 '
 
-test_expect_success '__gitdir - gitfile in cwd' '
+test_expect_success '__git_find_repo_path - gitfile in cwd' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	echo "gitdir: $ROOT/otherrepo/.git" >subdir/.git &&
 	test_when_finished "rm -f subdir/.git" &&
 	(
 		cd subdir &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - gitfile in parent' '
+test_expect_success '__git_find_repo_path - gitfile in parent' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	echo "gitdir: $ROOT/otherrepo/.git" >subdir/.git &&
 	test_when_finished "rm -f subdir/.git" &&
 	(
 		cd subdir/subsubdir &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success SYMLINKS '__gitdir - resulting path avoids symlinks' '
+test_expect_success SYMLINKS '__git_find_repo_path - resulting path avoids symlinks' '
 	echo "$ROOT/otherrepo/.git" >expected &&
 	mkdir otherrepo/dir &&
 	test_when_finished "rm -rf otherrepo/dir" &&
@@ -345,21 +348,57 @@ test_expect_success SYMLINKS '__gitdir - resulting path avoids symlinks' '
 	test_when_finished "rm -f link" &&
 	(
 		cd link &&
-		__gitdir >"$actual"
+		__git_find_repo_path &&
+		echo "$__git_repo_path" >"$actual"
 	) &&
 	test_cmp expected "$actual"
 '
 
-test_expect_success '__gitdir - not a git repository' '
+test_expect_success '__git_find_repo_path - not a git repository' '
 	(
 		cd subdir/subsubdir &&
 		GIT_CEILING_DIRECTORIES="$ROOT" &&
 		export GIT_CEILING_DIRECTORIES &&
+		test_must_fail __git_find_repo_path &&
+		printf "$__git_repo_path" >"$actual"
+	) &&
+	test_must_be_empty "$actual"
+'
+
+test_expect_success '__gitdir - finds repo' '
+	echo "$ROOT/.git" >expected &&
+	(
+		cd subdir/subsubdir &&
+		__gitdir >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+
+test_expect_success '__gitdir - returns error when cant find repo' '
+	(
+		__git_dir="non-existing" &&
 		test_must_fail __gitdir >"$actual"
 	) &&
 	test_must_be_empty "$actual"
 '
 
+test_expect_success '__gitdir - repo as argument' '
+	echo "otherrepo/.git" >expected &&
+	(
+		__gitdir "otherrepo" >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
+test_expect_success '__gitdir - remote as argument' '
+	echo "remote" >expected &&
+	(
+		__gitdir "remote" >"$actual"
+	) &&
+	test_cmp expected "$actual"
+'
+
 test_expect_success '__gitcomp - trailing space - options' '
 	test_gitcomp "--re" "--dry-run --reuse-message= --reedit-message=
 		--reset-author" <<-EOF
-- 
2.7.2.410.g92cb358

^ permalink raw reply related	[flat|nested] 25+ messages in thread

* Re: [PATCH 13/21] rev-parse: add '--absolute-git-dir' option
  2016-02-25 22:50 ` [PATCH 13/21] rev-parse: add '--absolute-git-dir' option SZEDER Gábor
@ 2016-04-26  2:33   ` Mike Rappazzo
  2016-04-26  5:35     ` Jeff King
  2016-05-18 16:58     ` SZEDER Gábor
  0 siblings, 2 replies; 25+ messages in thread
From: Mike Rappazzo @ 2016-04-26  2:33 UTC (permalink / raw)
  To: SZEDER Gábor, Junio C Hamano
  Cc: Jeff King, Sebastian Schuberth, Git List

On Thu, Feb 25, 2016 at 5:54 PM SZEDER Gábor <szeder@ira.uka.de> wrote:
>
> Some scripts can benefit from not having to deal with the possibility
> of relative paths to the repository, but the output of 'git rev-parse
> --git-dir' can be a relative path.  Case in point: supporting 'git -C
> <path>' in our Bash completion script turned out to be considerably
> more difficult, error prone and required more subshells and git
> processes when we had to cope with a relative path to the .git
> directory.
>
> Help these use cases and teach 'git rev-parse' a new
> '--absolute-git-dir' option which always outputs a canonicalized
> absolute path to the .git directory, regardless of whether the path is
> discovered automatically or is specified via $GIT_DIR or 'git
> --git-dir=<path>'.
>
> Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
> ---
>  Documentation/git-rev-parse.txt |  4 ++++
>  builtin/rev-parse.c             | 29 +++++++++++++++++++++--------
>  t/t1500-rev-parse.sh            | 17 ++++++++++-------
>  3 files changed, 35 insertions(+), 15 deletions(-)
>
> diff --git a/Documentation/git-rev-parse.txt b/Documentation/git-rev-parse.txt
> index b6c6326cdc7b..fb06e3118570 100644
> --- a/Documentation/git-rev-parse.txt
> +++ b/Documentation/git-rev-parse.txt
> @@ -216,6 +216,10 @@ If `$GIT_DIR` is not defined and the current directory
>  is not detected to lie in a Git repository or work tree
>  print a message to stderr and exit with nonzero status.
>
> +--absolute-git-dir::
> +       Like `--git-dir`, but its output is always the canonicalized
> +       absolute path.
> +
>  --git-common-dir::
>         Show `$GIT_COMMON_DIR` if defined, else `$GIT_DIR`.
>

After working a little bit with rev-parse [1], I feel that this might
be better served as a
stand-alone option.  Consider that in addition to --git-dir, the
options --git-common-dir,
--git-path, and --git-shared-index produce relative paths.

I propose that it might make more sense to use something like
`--abs-path` to indicate
that the result should include an absolute path (or we could also just spell out
`--absolute-path`).  That way we don't have to add additional options
for any other type
that might want an absolute path.

    git rev-parse --git-dir --abs-path
    git rev-parse --git-common-dir --absolute-path

I do understand that this might be more work than is necessary for the
completion series
here.  Would it be unreasonable to suggest a partial implementation
that, for now, only
works with `--git-dir`?

> diff --git a/builtin/rev-parse.c b/builtin/rev-parse.c
> index cf8487b3b95f..90a4dd6032c0 100644
> --- a/builtin/rev-parse.c
> +++ b/builtin/rev-parse.c
> @@ -744,17 +744,30 @@ int cmd_rev_parse(int argc, const char **argv, const char *prefix)
>                                 putchar('\n');
>                                 continue;
>                         }
> -                       if (!strcmp(arg, "--git-dir")) {
> +                       if (!strcmp(arg, "--git-dir") ||
> +                           !strcmp(arg, "--absolute-git-dir")) {
>                                 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
>                                 char *cwd;
>                                 int len;
> -                               if (gitdir) {
> -                                       puts(gitdir);
> -                                       continue;
> -                               }
> -                               if (!prefix) {
> -                                       puts(".git");
> -                                       continue;
> +                               if (arg[2] == 'g') {    /* --git-dir */
> +                                       if (gitdir) {
> +                                               puts(gitdir);
> +                                               continue;
> +                                       }
> +                                       if (!prefix) {
> +                                               puts(".git");
> +                                               continue;
> +                                       }
> +                               } else {                /* --absolute-git-dir */
> +                                       if (!gitdir && !prefix)
> +                                               gitdir = ".git";
> +                                       if (gitdir) {
> +                                               char absolute_path[PATH_MAX];
> +                                               if (!realpath(gitdir, absolute_path))
> +                                                       die_errno(_("unable to get absolute path"));
> +                                               puts(absolute_path);
> +                                               continue;
> +                                       }
>                                 }
>                                 cwd = xgetcwd();
>                                 len = strlen(cwd);
> diff --git a/t/t1500-rev-parse.sh b/t/t1500-rev-parse.sh
> index 48ee07779d64..617fcd821309 100755
> --- a/t/t1500-rev-parse.sh
> +++ b/t/t1500-rev-parse.sh
> @@ -31,23 +31,26 @@ test_rev_parse() {
>         "test '$1' = \"\$(git rev-parse --git-dir)\""
>         shift
>         [ $# -eq 0 ] && return
> +
> +       test_expect_success "$name: absolute-git-dir" \
> +       "verbose test '$1' = \"\$(git rev-parse --absolute-git-dir)\""
>  }
>
> -# label is-bare is-inside-git is-inside-work prefix git-dir
> +# label is-bare is-inside-git is-inside-work prefix git-dir absolute-git-dir
>
>  ROOT=$(pwd)
>
> -test_rev_parse toplevel false false true '' .git
> +test_rev_parse toplevel false false true '' .git "$ROOT/.git"
>
>  cd .git || exit 1
> -test_rev_parse .git/ false true false '' .
> +test_rev_parse .git/ false true false '' . "$ROOT/.git"
>  cd objects || exit 1
> -test_rev_parse .git/objects/ false true false '' "$ROOT/.git"
> +test_rev_parse .git/objects/ false true false '' "$ROOT/.git" "$ROOT/.git"
>  cd ../.. || exit 1
>
>  mkdir -p sub/dir || exit 1
>  cd sub/dir || exit 1
> -test_rev_parse subdirectory false false true sub/dir/ "$ROOT/.git"
> +test_rev_parse subdirectory false false true sub/dir/ "$ROOT/.git" "$ROOT/.git"
>  cd ../.. || exit 1
>
>  git config core.bare true
> @@ -63,7 +66,7 @@ GIT_CONFIG="$(pwd)"/../.git/config
>  export GIT_DIR GIT_CONFIG
>
>  git config core.bare false
> -test_rev_parse 'GIT_DIR=../.git, core.bare = false' false false true ''
> +test_rev_parse 'GIT_DIR=../.git, core.bare = false' false false true '' "../.git" "$ROOT/.git"
>
>  git config core.bare true
>  test_rev_parse 'GIT_DIR=../.git, core.bare = true' true false false ''
> @@ -76,7 +79,7 @@ GIT_DIR=../repo.git
>  GIT_CONFIG="$(pwd)"/../repo.git/config
>
>  git config core.bare false
> -test_rev_parse 'GIT_DIR=../repo.git, core.bare = false' false false true ''
> +test_rev_parse 'GIT_DIR=../repo.git, core.bare = false' false false true '' "../repo.git" "$ROOT/repo.git"
>
>  git config core.bare true
>  test_rev_parse 'GIT_DIR=../repo.git, core.bare = true' true false false ''
> --
> 2.7.2.410.g92cb358
>
> --

[1] http://thread.gmane.org/gmane.comp.version-control.git/292272

^ permalink raw reply	[flat|nested] 25+ messages in thread

* Re: [PATCH 13/21] rev-parse: add '--absolute-git-dir' option
  2016-04-26  2:33   ` Mike Rappazzo
@ 2016-04-26  5:35     ` Jeff King
  2016-05-18 16:58     ` SZEDER Gábor
  1 sibling, 0 replies; 25+ messages in thread
From: Jeff King @ 2016-04-26  5:35 UTC (permalink / raw)
  To: Mike Rappazzo
  Cc: SZEDER Gábor, Junio C Hamano, Sebastian Schuberth, Git List

On Mon, Apr 25, 2016 at 10:33:13PM -0400, Mike Rappazzo wrote:

> I propose that it might make more sense to use something like
> `--abs-path` to indicate
> that the result should include an absolute path (or we could also just spell out
> `--absolute-path`).  That way we don't have to add additional options
> for any other type
> that might want an absolute path.
> 
>     git rev-parse --git-dir --abs-path
>     git rev-parse --git-common-dir --absolute-path
> 
> I do understand that this might be more work than is necessary for the
> completion series
> here.  Would it be unreasonable to suggest a partial implementation
> that, for now, only
> works with `--git-dir`?

I do like the concept of keeping "--absolute-path" orthogonal. The only
trick is that we need to either support it for all appropriate options,
or document which options it _does_ work with. Otherwise, we're going to
get bug reports when somebody tries "--absolute-path --git-common-dir".

It would be cleaner to provide a separate option to let people compose
the options, like:

  git rev-parse --git-dir | git rev-parse --realpath

but that's a lot less efficient.

> > +                                       if (gitdir) {
> > +                                               char absolute_path[PATH_MAX];
> > +                                               if (!realpath(gitdir, absolute_path))
> > +                                                       die_errno(_("unable to get absolute path"));
> > +                                               puts(absolute_path);
> > +                                               continue;
> > +                                       }

I don't recall if this came up in earlier review, but I happened to
notice the use of realpath() here. We should be using our custom
real_path() instead. There are some platforms without realpath(), I
think, and our real_path() is not limited to the static PATH_MAX (which
is too small on some platforms).

-Peff

^ permalink raw reply	[flat|nested] 25+ messages in thread

* Re: [PATCH 13/21] rev-parse: add '--absolute-git-dir' option
  2016-04-26  2:33   ` Mike Rappazzo
  2016-04-26  5:35     ` Jeff King
@ 2016-05-18 16:58     ` SZEDER Gábor
  1 sibling, 0 replies; 25+ messages in thread
From: SZEDER Gábor @ 2016-05-18 16:58 UTC (permalink / raw)
  To: Mike Rappazzo
  Cc: Junio C Hamano, Jeff King, Sebastian Schuberth, Git List,
	Nguyễn Thái Ngọc Duy


Quoting Mike Rappazzo <rappazzo@gmail.com>:

> On Thu, Feb 25, 2016 at 5:54 PM SZEDER Gábor <szeder@ira.uka.de> wrote:
>>
>> Some scripts can benefit from not having to deal with the possibility
>> of relative paths to the repository, but the output of 'git rev-parse
>> --git-dir' can be a relative path.  Case in point: supporting 'git -C
>> <path>' in our Bash completion script turned out to be considerably
>> more difficult, error prone and required more subshells and git
>> processes when we had to cope with a relative path to the .git
>> directory.
>>
>> Help these use cases and teach 'git rev-parse' a new
>> '--absolute-git-dir' option which always outputs a canonicalized
>> absolute path to the .git directory, regardless of whether the path is
>> discovered automatically or is specified via $GIT_DIR or 'git
>> --git-dir=<path>'.
>>
>> Signed-off-by: SZEDER Gábor <szeder@ira.uka.de>
>> ---
>> Documentation/git-rev-parse.txt |  4 ++++
>> builtin/rev-parse.c             | 29 +++++++++++++++++++++--------
>> t/t1500-rev-parse.sh            | 17 ++++++++++-------
>> 3 files changed, 35 insertions(+), 15 deletions(-)
>>
>> diff --git a/Documentation/git-rev-parse.txt
>> b/Documentation/git-rev-parse.txt
>> index b6c6326cdc7b..fb06e3118570 100644
>> --- a/Documentation/git-rev-parse.txt
>> +++ b/Documentation/git-rev-parse.txt
>> @@ -216,6 +216,10 @@ If `$GIT_DIR` is not defined and the current directory
>> is not detected to lie in a Git repository or work tree
>> print a message to stderr and exit with nonzero status.
>>
>> +--absolute-git-dir::
>> +       Like `--git-dir`, but its output is always the canonicalized
>> +       absolute path.
>> +
>> --git-common-dir::
>>    Show `$GIT_COMMON_DIR` if defined, else `$GIT_DIR`.
>>
>
> After working a little bit with rev-parse [1], I feel that this might
> be better served as a
> stand-alone option.  Consider that in addition to --git-dir, the
> options --git-common-dir,
> --git-path, and --git-shared-index produce relative paths.
>
> I propose that it might make more sense to use something like
> `--abs-path` to indicate
> that the result should include an absolute path (or we could also
> just spell out
> `--absolute-path`).  That way we don't have to add additional options
> for any other type
> that might want an absolute path.

Do you have a specific use case in mind, where scripts struggle because
in some cases '--git-dir', '--git-common-dir' or '--git-path' return a
relative path?  (Assuming that these options produce the right relative
paths, of course.  At the moment some don't in some cases, but your
patches elsewhere will eventually take care of that.)

As far as git is concerned, relative paths are relative to the current
working directory of the git process or script.  If a script is invoked
as 'git -C subdir myscript', then the CWD is changed accordingly by the
main git process first going into the given directory before starting
the script.

Now, though I wrote that generalizing "some scripts" and "these use
cases" in the commit message, I really only meant the completion
script, because it is rather special in that it's executed in the
user's interactive shell environment.  This means that it can't just
simply 'cd' around and it has to cope with 'git -C subdir' options on
it's own, because in that case the CWD of the git processes invoked
from the completion script will be different from the CWD of the
user's shell.  That's the situation where a relative path returned
from 'git rev-parse --git-dir' causes troubles.

I can't really see other scripts in this situation, and I really don't
expect that the completion script would need any path other than the
path to the git repository, i.e. it only needs '--absolute-git-dir'.
Therefore I think that a separate '--absolute-path' option would offer
little benefit, but at the same time would pose considerable
complications, more on that below.

> git rev-parse --git-dir --abs-path
> git rev-parse --git-common-dir --absolute-path

'git rev-parse's command line option parsing loop not just parses an
option but in a lot of cases performs the necessary action right away,
before examining any subsequent options.  In the above example
it would print the path to the .git directory as soon as it encounters
'--git-dir' while iterating through the command line options, before
even noticing that there is an '--absolute-path' option as well.  If
anything, then the other way around:

     git rev-parse --absolute-path --git-dir

And if we were to go this route, then there are a bunch of questions
about the gory details that would have to be cleared up first:

Should the presence of an '--absolute-path' option influence all
subsequent path-returning options or just the one immediately
following it?  I.e. should all these options always return an
absolute path?

     git rev-parse --absolute-path --git-dir --git-common-dir \
                   --git-path objects

What about this, i.e. when there are other option(s) between
'--absolute-path' and a path-returning option?

     git rev-parse --absolute-path --is-bare-repository --git-dir

I'd think they should all return an absolute path then.

Now, should '--absolute-path' have an effect on '--show-prefix'
and '--prefix' as well?

     git rev-parse --absolute-path --show-prefix
     git rev-parse --absolute-path --prefix t/ README

Luckily, options after a filename are not allowed, so we don't even
have to think about cases like

     git rev-parse --prefix t/ README --absolute-path Makefile

as it would error out anyway.

Would we need a '--no-absolute-path' (or '--relative-path', perhaps?)
option to turn off the effect of a previous '--absolute-path', e.g.

     git rev-parse --absolute-path --git-dir \
                   --no-absolute-path --git-common-dir

If yes, should a '--no-abolute-path' force subsequent path-returning
options to return a relative path even when they by default would
return an absolute path, e.g.:

     git -C t/ rev-parse --no-absolute-path --git-dir

Or should it return a relative path even when paths are explicitly
specified as absolute paths?

     git --git-dir=/absolute/path/to/repo.git rev-parse  
--no-absolute-path --git-dir
     git rev-parse --prefix /home/szeder/src/git/t/ --no-absolute-path README

^ permalink raw reply	[flat|nested] 25+ messages in thread

end of thread, other threads:[~2016-05-18 16:58 UTC | newest]

Thread overview: 25+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2016-02-25 22:50 [PATCH 00/21] completion: __gitdir()-related improvements SZEDER Gábor
2016-02-25 22:50 ` [PATCH 01/21] completion: improve __git_refs()'s in-code documentation SZEDER Gábor
2016-02-25 22:50 ` [PATCH 02/21] completion tests: don't add test cruft to the test repository SZEDER Gábor
2016-02-25 22:50 ` [PATCH 03/21] completion tests: make the $cur variable local to the test helper functions SZEDER Gábor
2016-02-25 22:50 ` [PATCH 04/21] completion tests: consolidate getting path of current working directory SZEDER Gábor
2016-02-25 22:50 ` [PATCH 05/21] completion tests: check __gitdir()'s output in the error cases SZEDER Gábor
2016-02-25 22:50 ` [PATCH 06/21] completion tests: add tests for the __git_refs() helper function SZEDER Gábor
2016-02-25 22:50 ` [PATCH 07/21] completion: ensure that the repository path given on the command line exists SZEDER Gábor
2016-02-25 22:50 ` [PATCH 08/21] completion: fix most spots not respecting 'git --git-dir=<path>' SZEDER Gábor
2016-02-25 22:50 ` [PATCH 09/21] completion: respect 'git --git-dir=<path>' when listing remote refs SZEDER Gábor
2016-02-25 22:50 ` [PATCH 10/21] completion: list refs from remote when remote's name matches a directory SZEDER Gábor
2016-02-25 22:50 ` [PATCH 11/21] completion: don't list 'HEAD' when trying refs completion outside of a repo SZEDER Gábor
2016-02-25 22:50 ` [PATCH 12/21] completion: list short refs from a remote given as a URL SZEDER Gábor
2016-02-25 22:50 ` [PATCH 13/21] rev-parse: add '--absolute-git-dir' option SZEDER Gábor
2016-04-26  2:33   ` Mike Rappazzo
2016-04-26  5:35     ` Jeff King
2016-05-18 16:58     ` SZEDER Gábor
2016-02-25 22:50 ` [PATCH 14/21] completion: don't offer commands when 'git --opt' needs an argument SZEDER Gábor
2016-02-25 22:50 ` [PATCH 15/21] completion: fix completion after 'git -C <path>' SZEDER Gábor
2016-02-25 22:50 ` [PATCH 16/21] completion: respect " SZEDER Gábor
2016-02-25 22:50 ` [PATCH 17/21] completion: don't use __gitdir() for git commands SZEDER Gábor
2016-02-25 22:50 ` [PATCH 18/21] completion: consolidate silencing errors from " SZEDER Gábor
2016-02-25 22:50 ` [PATCH 19/21] completion: don't guard git executions with __gitdir() SZEDER Gábor
2016-02-25 22:50 ` [PATCH 20/21] completion: extract repository discovery from __gitdir() SZEDER Gábor
2016-02-25 22:50 ` [PATCH 21/21] completion: cache the path to the repository SZEDER Gábor

Code repositories for project(s) associated with this public inbox

	https://80x24.org/mirrors/git.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).