builtin-grep: binary files -a and -I
Signed-off-by: Junio C Hamano <junkio@cox.net>
Junio C Hamano committed
May 3, 2006 at 21:05 UTC
b8d0f5a00313bc5fb173f77c9a91a94f94a5aa1b
1 file changed
+44
builtin-grep.c
+44
@@ -95,6 +95,10 @@ struct grep_opt {
95
unsigned name_only:1;
96
unsigned count:1;
97
unsigned word_regexp:1;
98
+#define GREP_BINARY_DEFAULT 0
99
+#define GREP_BINARY_NOMATCH 1
100
+#define GREP_BINARY_TEXT 2
101
+ unsigned binary:2;
102
int regflags;
103
unsigned pre_context;
104
unsigned post_context;
@@ -148,6 +152,19 @@ static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
152
printf("%.*s\n", (int)(eol-bol), bol);
153
}
154
155
+/*
156
+ * NEEDSWORK: share code with diff.c
157
+ */
158
+#define FIRST_FEW_BYTES 8000
159
+static int buffer_is_binary(const char *ptr, unsigned long size)
160
+{
161
+ if (FIRST_FEW_BYTES < size)
162
+ size = FIRST_FEW_BYTES;
163
+ if (memchr(ptr, 0, size))
164
+ return 1;
165
+ return 0;
166
+}
167
+
168
static int grep_buffer(struct grep_opt *opt, const char *name,
169
char *buf, unsigned long size)
170
{
@@ -160,9 +177,23 @@ static int grep_buffer(struct grep_opt *opt, const char *name,
177
} *prev = NULL, *pcl;
178
unsigned last_hit = 0;
179
unsigned last_shown = 0;
180
+ int binary_match_only = 0;
181
const char *hunk_mark = "";
182
unsigned count = 0;
183
184
+ if (buffer_is_binary(buf, size)) {
185
+ switch (opt->binary) {
186
+ case GREP_BINARY_DEFAULT:
187
+ binary_match_only = 1;
188
+ break;
189
+ case GREP_BINARY_NOMATCH:
190
+ return 0; /* Assume unmatch */
191
+ break;
192
+ default:
193
+ break;
194
+ }
195
+ }
196
+
197
if (opt->pre_context)
198
prev = xcalloc(opt->pre_context, sizeof(*prev));
199
if (opt->pre_context || opt->post_context)
@@ -212,6 +243,10 @@ static int grep_buffer(struct grep_opt *opt, const char *name,
243
hit = !hit;
244
if (hit) {
245
count++;
246
+ if (binary_match_only) {
247
+ printf("Binary file %s matches\n", name);
248
+ return 1;
249
+ }
250
if (opt->name_only) {
251
printf("%s\n", name);
252
return 1;
@@ -453,11 +488,20 @@ int cmd_grep(int argc, const char **argv, char **envp)
488
cached = 1;
489
continue;
490
}
491
+ if (!strcmp("-a", arg) ||
492
+ !strcmp("--text", arg)) {
493
+ opt.binary = GREP_BINARY_TEXT;
494
+ continue;
495
+ }
496
if (!strcmp("-i", arg) ||
497
!strcmp("--ignore-case", arg)) {
498
opt.regflags |= REG_ICASE;
499
continue;
500
}
501
+ if (!strcmp("-I", arg)) {
502
+ opt.binary = GREP_BINARY_NOMATCH;
503
+ continue;
504
+ }
505
if (!strcmp("-v", arg) ||
506
!strcmp("--invert-match", arg)) {
507
opt.invert = 1;