{"thread":{"id":"26793","subject":"[PATCH] grep: read patterns from stdin with -f -","startedAt":"2011-03-19T18:33:15Z","lastAt":"2011-03-19T18:33:15Z","messageCount":1,"participants":["René Scharfe"],"isPatch":true,"patchVersion":1,"patchTotal":null},"messages":[{"id":"163770","messageId":"4D84F6EB.5000009@lsrfire.ath.cx","threadId":"26793","inReplyTo":null,"subject":"[PATCH] grep: read patterns from stdin with -f -","fromName":"René Scharfe","fromEmail":"rene.scharfe@lsrfire.ath.cx","sentAt":"2011-03-19T18:33:15Z","receivedAt":"2011-03-19T18:33:15Z","isPatch":true,"sender":{"key":"l.s.r@web.de","avatar":"https://avatars.githubusercontent.com/u/26122331?v=4"},"body":"Support the well-know convention of reading standard input instead of a\nnamed file if \"-\" (dash) is specified.  GNU grep does the same.\n\nSigned-off-by: Rene Scharfe <rene.scharfe@lsrfire.ath.cx>\n---\nI was trying to look for the string \"/pack\", but MinGW mangles arguments\nthat look like paths.  \"echo /pack | git grep -f-\" was my first try to\ncircumvent this, as echo's arguments are not mangled.  I ended up with\n\"git grep '[/]pack'\" -- and also this patch.\n\n builtin/grep.c  |    6 ++++--\n t/t7810-grep.sh |    5 +++++\n 2 files changed, 9 insertions(+), 2 deletions(-)\n\ndiff --git a/builtin/grep.c b/builtin/grep.c\nindex eaf8560..0bf8c01 100644\n--- a/builtin/grep.c\n+++ b/builtin/grep.c\n@@ -659,11 +659,12 @@ static int context_callback(const struct option *opt, const char *arg,\n static int file_callback(const struct option *opt, const char *arg, int unset)\n {\n \tstruct grep_opt *grep_opt = opt->value;\n+\tint from_stdin = !strcmp(arg, \"-\");\n \tFILE *patterns;\n \tint lno = 0;\n \tstruct strbuf sb = STRBUF_INIT;\n \n-\tpatterns = fopen(arg, \"r\");\n+\tpatterns = from_stdin ? stdin : fopen(arg, \"r\");\n \tif (!patterns)\n \t\tdie_errno(\"cannot open '%s'\", arg);\n \twhile (strbuf_getline(&sb, patterns, '\\n') == 0) {\n@@ -677,7 +678,8 @@ static int file_callback(const struct option *opt, const char *arg, int unset)\n \t\ts = strbuf_detach(&sb, &len);\n \t\tappend_grep_pat(grep_opt, s, len, arg, ++lno, GREP_PATTERN);\n \t}\n-\tfclose(patterns);\n+\tif (!from_stdin)\n+\t\tfclose(patterns);\n \tstrbuf_release(&sb);\n \treturn 0;\n }\ndiff --git a/t/t7810-grep.sh b/t/t7810-grep.sh\nindex 8a7788d..dbc6cd8 100755\n--- a/t/t7810-grep.sh\n+++ b/t/t7810-grep.sh\n@@ -303,6 +303,11 @@ test_expect_success 'grep -f, ignore empty lines' '\n \ttest_cmp expected actual\n '\n \n+test_expect_success 'grep -f, ignore empty lines, read patterns from stdin' '\n+\tgit grep -f - <patterns >actual &&\n+\ttest_cmp expected actual\n+'\n+\n cat >expected <<EOF\n y:y yy\n --\n-- \n1.7.4\n"}]}