Skip to content

Commit dca3b5f

Browse files
jonathantanmygitster
authored andcommitted
grep: do not unnecessarily query repo for "--"
When running a command of the form git grep --no-index pattern -- path in the absence of a Git repository, an error message will be printed: fatal: BUG: setup_git_env called without repository This is because "git grep" tries to interpret "--" as a rev. "git grep" has always tried to first interpret "--" as a rev for at least a few years, but this issue was upgraded from a pessimization to a bug in commit 59332d1 ("Resurrect "git grep --no-index"", 2010-02-06), which calls get_sha1 regardless of whether --no-index was specified. This bug appeared to be benign until commit b1ef400 ("setup_git_env: avoid blind fall-back to ".git"", 2016-10-20) when Git was taught to die in this situation. (This "git grep" bug appears to be one of the bugs that commit b1ef400 is meant to flush out.) Therefore, always interpret "--" as signaling the end of options, instead of trying to interpret it as a rev first. Signed-off-by: Jonathan Tan <[email protected]> Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent a0fe2b0 commit dca3b5f

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

builtin/grep.c

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1154,6 +1154,11 @@ int cmd_grep(int argc, const char **argv, const char *prefix)
11541154
const char *arg = argv[i];
11551155
unsigned char sha1[20];
11561156
struct object_context oc;
1157+
if (!strcmp(arg, "--")) {
1158+
i++;
1159+
seen_dashdash = 1;
1160+
break;
1161+
}
11571162
/* Is it a rev? */
11581163
if (!get_sha1_with_context(arg, 0, sha1, &oc)) {
11591164
struct object *object = parse_object_or_die(sha1, arg);
@@ -1162,10 +1167,6 @@ int cmd_grep(int argc, const char **argv, const char *prefix)
11621167
add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
11631168
continue;
11641169
}
1165-
if (!strcmp(arg, "--")) {
1166-
i++;
1167-
seen_dashdash = 1;
1168-
}
11691170
break;
11701171
}
11711172

t/t7810-grep.sh

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -982,6 +982,21 @@ test_expect_success 'grep -e -- -- path' '
982982
test_cmp expected actual
983983
'
984984

985+
test_expect_success 'grep --no-index pattern -- path' '
986+
rm -fr non &&
987+
mkdir -p non/git &&
988+
(
989+
GIT_CEILING_DIRECTORIES="$(pwd)/non" &&
990+
export GIT_CEILING_DIRECTORIES &&
991+
cd non/git &&
992+
echo hello >hello &&
993+
echo goodbye >goodbye &&
994+
echo hello:hello >expect &&
995+
git grep --no-index o -- hello >actual &&
996+
test_cmp expect actual
997+
)
998+
'
999+
9851000
cat >expected <<EOF
9861001
hello.c:int main(int argc, const char **argv)
9871002
hello.c: printf("Hello world.\n");

0 commit comments

Comments
 (0)