grep: die gracefully when outside repository

Die gracefully when `git grep --no-index` is run outside of a Git repository and the path is outside the directory tree. If you are not in a Git repository and say: git grep --no-index search .. You trigger a `BUG`: BUG: environment.c:213: git environment hasn't been setup Aborted (core dumped) Because `..` is a valid path which is treated as a pathspec. Then `pathspec` figures out that it is not in the current directory tree. The `BUG` is triggered when `pathspec` tries to advise the user about how the path is not in the current (non-existing) repository. Reported-by: ks1322 ks1322 <ks1322@gmail.com> Helped-by: Junio C Hamano <gitster@pobox.com> Signed-off-by: Kristoffer Haugsbakk <code@khaugsbakk.name> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Kristoffer Haugsbakk committed Oct 20, 2023 at 18:40 UTC b1688ea02df6fdefd5a228a0d52583356d433a99
2 files changed +33 -1
pathspec.c
+6 -1
@@ -467,7 +467,12 @@ static void init_pathspec_item(struct pathspec_item *item, unsigned flags,
467 match = prefix_path_gently(prefix, prefixlen,
468 &prefixlen, copyfrom);
469 if (!match) {
470 - const char *hint_path = get_git_work_tree();
470 + const char *hint_path;
471 +
472 + if (!have_git_dir())
473 + die(_("'%s' is outside the directory tree"),
474 + copyfrom);
475 + hint_path = get_git_work_tree();
476 if (!hint_path)
477 hint_path = get_git_dir();
478 die(_("%s: '%s' is outside repository at '%s'"), elt,
t/t7810-grep.sh
+27
@@ -1234,6 +1234,33 @@ test_expect_success 'outside of git repository with fallbackToNoIndex' '
1234 )
1235 '
1236
1237 +test_expect_success 'no repository with path outside $cwd' '
1238 + test_when_finished rm -fr non &&
1239 + rm -fr non &&
1240 + mkdir -p non/git/sub non/tig &&
1241 + (
1242 + GIT_CEILING_DIRECTORIES="$(pwd)/non" &&
1243 + export GIT_CEILING_DIRECTORIES &&
1244 + cd non/git &&
1245 + test_expect_code 128 git grep --no-index search .. 2>error &&
1246 + grep "is outside the directory tree" error
1247 + ) &&
1248 + (
1249 + GIT_CEILING_DIRECTORIES="$(pwd)/non" &&
1250 + export GIT_CEILING_DIRECTORIES &&
1251 + cd non/git &&
1252 + test_expect_code 128 git grep --no-index search ../tig 2>error &&
1253 + grep "is outside the directory tree" error
1254 + ) &&
1255 + (
1256 + GIT_CEILING_DIRECTORIES="$(pwd)/non" &&
1257 + export GIT_CEILING_DIRECTORIES &&
1258 + cd non/git &&
1259 + test_expect_code 128 git grep --no-index search ../non 2>error &&
1260 + grep "no such path in the working tree" error
1261 + )
1262 +'
1263 +
1264 test_expect_success 'inside git repository but with --no-index' '
1265 rm -fr is &&
1266 mkdir -p is/git/sub &&