@matheusbsbs / matheus-bagliano / commits / 2c866cf1c2
Fork 0

builtin-grep: support -c (--count).

Signed-off-by: Junio C Hamano <junkio@cox.net>

Junio C Hamano committed May 2, 2006 at 15:40 UTC 2c866cf1c2b2f3a289b7f3c21adb4f05af6626e4
1 file changed +20 -1
builtin-grep.c
+20 -1
@@ -88,6 +88,7 @@ struct grep_opt {
88 unsigned linenum:1;
89 unsigned invert:1;
90 unsigned name_only:1;
91 + unsigned count:1;
92 int regflags;
93 unsigned pre_context;
94 unsigned post_context;
@@ -149,6 +150,7 @@ static int grep_buffer(struct grep_opt *opt, const char *name,
150 unsigned last_hit = 0;
151 unsigned last_shown = 0;
152 const char *hunk_mark = "";
153 + unsigned count = 0;
154
155 if (opt->pre_context)
156 prev = xcalloc(opt->pre_context, sizeof(*prev));
@@ -179,12 +181,16 @@ static int grep_buffer(struct grep_opt *opt, const char *name,
181 if (opt->invert)
182 hit = !hit;
183 if (hit) {
184 + count++;
185 if (opt->name_only) {
186 printf("%s\n", name);
187 return 1;
188 }
189 /* Hit at this line. If we haven't shown the
190 * pre-context lines, we would need to show them.
191 + * When asked to do "count", this still show
192 + * the context which is nonsense, but the user
193 + * deserves to get that ;-).
194 */
195 if (opt->pre_context) {
196 unsigned from;
@@ -206,7 +212,8 @@ static int grep_buffer(struct grep_opt *opt, const char *name,
212 }
213 if (last_shown && lno != last_shown + 1)
214 printf(hunk_mark);
209 - show_line(opt, bol, eol, name, lno, ':');
215 + if (!opt->count)
216 + show_line(opt, bol, eol, name, lno, ':');
217 last_shown = last_hit = lno;
218 }
219 else if (last_hit &&
@@ -230,6 +237,13 @@ static int grep_buffer(struct grep_opt *opt, const char *name,
237 left--;
238 lno++;
239 }
240 + /* NEEDSWORK:
241 + * The real "grep -c foo *.c" gives many "bar.c:0" lines,
242 + * which feels mostly useless but sometimes useful. Maybe
243 + * make it another option? For now suppress them.
244 + */
245 + if (opt->count && count)
246 + printf("%s:%u\n", name, count);
247 return !!last_hit;
248 }
249
@@ -442,6 +456,11 @@ int cmd_grep(int argc, const char **argv, char **envp)
456 opt.name_only = 1;
457 continue;
458 }
459 + if (!strcmp("-c", arg) ||
460 + !strcmp("--count", arg)) {
461 + opt.count = 1;
462 + continue;
463 + }
464 if (!strncmp("-A", arg, 2) ||
465 !strncmp("-B", arg, 2) ||
466 !strncmp("-C", arg, 2) ||