grep: -f <path> is relative to $cwd

Just like OPT_FILENAME() does, "git grep -f <path>" should treat the <path> relative to the original $cwd by paying attention to the prefix the command is given. Signed-off-by: Junio C Hamano <gitster@pobox.com>

Junio C Hamano committed Oct 12, 2023 at 10:28 UTC 5b2424b658701c16e4fe12babf83fdb15d0f165a
2 files changed +24 -2
builtin/grep.c
+11 -2
@@ -4,6 +4,7 @@
4 * Copyright (c) 2006 Junio C Hamano
5 */
6 #include "builtin.h"
7 +#include "abspath.h"
8 #include "gettext.h"
9 #include "hex.h"
10 #include "repository.h"
@@ -812,14 +813,20 @@ static int file_callback(const struct option *opt, const char *arg, int unset)
813 {
814 struct grep_opt *grep_opt = opt->value;
815 int from_stdin;
816 + const char *filename = arg;
817 FILE *patterns;
818 int lno = 0;
819 struct strbuf sb = STRBUF_INIT;
820
821 BUG_ON_OPT_NEG(unset);
822
821 - from_stdin = !strcmp(arg, "-");
822 - patterns = from_stdin ? stdin : fopen(arg, "r");
823 + if (!*filename)
824 + ; /* leave it as-is */
825 + else
826 + filename = prefix_filename_except_for_dash(grep_prefix, filename);
827 +
828 + from_stdin = !strcmp(filename, "-");
829 + patterns = from_stdin ? stdin : fopen(filename, "r");
830 if (!patterns)
831 die_errno(_("cannot open '%s'"), arg);
832 while (strbuf_getline(&sb, patterns) == 0) {
@@ -833,6 +840,8 @@ static int file_callback(const struct option *opt, const char *arg, int unset)
840 if (!from_stdin)
841 fclose(patterns);
842 strbuf_release(&sb);
843 + if (filename != arg)
844 + free((void *)filename);
845 return 0;
846 }
847
t/t7810-grep.sh
+13
@@ -808,6 +808,19 @@ test_expect_success 'grep -f, ignore empty lines, read patterns from stdin' '
808 test_cmp expected actual
809 '
810
811 +test_expect_success 'grep -f, use cwd relative file' '
812 + test_when_finished "git rm -f sub/dir/file" &&
813 + mkdir -p sub/dir &&
814 + echo hit >sub/dir/file &&
815 + git add sub/dir/file &&
816 + echo hit >sub/dir/pattern &&
817 + echo miss >pattern &&
818 + (
819 + cd sub/dir && git grep -f pattern file
820 + ) &&
821 + git -C sub/dir grep -f pattern file
822 +'
823 +
824 cat >expected <<EOF
825 y:y yy
826 --