Skip to content

Commit 5b2424b

Browse files
committed
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 <[email protected]>
1 parent 43c8a30 commit 5b2424b

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

builtin/grep.c

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
* Copyright (c) 2006 Junio C Hamano
55
*/
66
#include "builtin.h"
7+
#include "abspath.h"
78
#include "gettext.h"
89
#include "hex.h"
910
#include "repository.h"
@@ -812,14 +813,20 @@ static int file_callback(const struct option *opt, const char *arg, int unset)
812813
{
813814
struct grep_opt *grep_opt = opt->value;
814815
int from_stdin;
816+
const char *filename = arg;
815817
FILE *patterns;
816818
int lno = 0;
817819
struct strbuf sb = STRBUF_INIT;
818820

819821
BUG_ON_OPT_NEG(unset);
820822

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");
823830
if (!patterns)
824831
die_errno(_("cannot open '%s'"), arg);
825832
while (strbuf_getline(&sb, patterns) == 0) {
@@ -833,6 +840,8 @@ static int file_callback(const struct option *opt, const char *arg, int unset)
833840
if (!from_stdin)
834841
fclose(patterns);
835842
strbuf_release(&sb);
843+
if (filename != arg)
844+
free((void *)filename);
836845
return 0;
837846
}
838847

t/t7810-grep.sh

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,19 @@ test_expect_success 'grep -f, ignore empty lines, read patterns from stdin' '
808808
test_cmp expected actual
809809
'
810810

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+
811824
cat >expected <<EOF
812825
y:y yy
813826
--

0 commit comments

Comments
 (0)