Skip to content

Commit c30c10c

Browse files
René Scharfegitster
authored andcommitted
grep: --count over binary
The intent of showing the message "Binary file xyz matches" for binary files is to avoid annoying users by potentially messing up their terminals by printing control characters. In --count mode, this precaution isn't necessary. Display counts of matches if -c/--count was specified, even if -a was not given. GNU grep does the same. Moving the check for ->count before the code for handling binary file also avoids printing context lines if --count and -[ABC] were used together, so we can remove the part of the comment that mentions this behaviour. Again, GNU grep does the same. Signed-off-by: Rene Scharfe <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 64fcec7 commit c30c10c

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

grep.c

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -873,6 +873,8 @@ static int grep_buffer_1(struct grep_opt *opt, const char *name,
873873
count++;
874874
if (opt->status_only)
875875
return 1;
876+
if (opt->count)
877+
goto next_line;
876878
if (binary_match_only) {
877879
opt->output(opt, "Binary file ", 12);
878880
output_color(opt, name, strlen(name),
@@ -886,16 +888,12 @@ static int grep_buffer_1(struct grep_opt *opt, const char *name,
886888
}
887889
/* Hit at this line. If we haven't shown the
888890
* pre-context lines, we would need to show them.
889-
* When asked to do "count", this still show
890-
* the context which is nonsense, but the user
891-
* deserves to get that ;-).
892891
*/
893892
if (opt->pre_context)
894893
show_pre_context(opt, name, buf, bol, lno);
895894
else if (opt->funcname)
896895
show_funcname_line(opt, name, buf, bol, lno);
897-
if (!opt->count)
898-
show_line(opt, bol, eol, name, lno, ':');
896+
show_line(opt, bol, eol, name, lno, ':');
899897
last_hit = lno;
900898
}
901899
else if (last_hit &&
@@ -939,6 +937,7 @@ static int grep_buffer_1(struct grep_opt *opt, const char *name,
939937
output_sep(opt, ':');
940938
snprintf(buf, sizeof(buf), "%u\n", count);
941939
opt->output(opt, buf, strlen(buf));
940+
return 1;
942941
}
943942
return !!last_hit;
944943
}

t/t7008-grep-binary.sh

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ test_expect_success 'git grep -I ina a' '
2727
test_cmp expect actual
2828
'
2929

30+
test_expect_success 'git grep -c ina a' '
31+
echo a:1 >expect &&
32+
git grep -c ina a >actual &&
33+
test_cmp expect actual
34+
'
35+
3036
test_expect_success 'git grep -L bar a' '
3137
echo a >expect &&
3238
git grep -L bar a >actual &&

0 commit comments

Comments
 (0)