OSDN Git Service

Add grep -B -C
[android-x86/external-toybox.git] / toys / posix / grep.c
1 /* grep.c - print lines what match given regular expression
2  *
3  * Copyright 2013 CE Strake <strake888 at gmail.com>
4  *
5  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html
6  *
7  * TODO: -ABC
8
9 USE_GREP(NEWTOY(grep, "C#B#A#ZzEFHabhinorsvwclqe*f*m#x[!wx][!EFw]", TOYFLAG_BIN))
10 USE_EGREP(OLDTOY(egrep, grep, TOYFLAG_BIN))
11 USE_FGREP(OLDTOY(fgrep, grep, TOYFLAG_BIN))
12
13 config GREP
14   bool "grep"
15   default y
16   help
17     usage: grep [-EFivwcloqsHbhn] [-A NUM] [-m MAX] [-e REGEX]... [-f REGFILE] [FILE]...
18
19     Show lines matching regular expressions. If no -e, first argument is
20     regular expression to match. With no files (or "-" filename) read stdin.
21     Returns 0 if matched, 1 if no match found.
22
23     -e  Regex to match. (May be repeated.)
24     -f  File containing regular expressions to match.
25
26     match type:
27     -A  Show NUM lines after     -B  Show NUM lines before match
28     -C  NUM lines context (A+B)  -E  extended regex syntax
29     -F  fixed (literal match)    -i  case insensitive
30     -m  match MAX many lines     -r  recursive (on dir)
31     -v  invert match             -w  whole word (implies -E)
32     -x  whole line               -z  input NUL terminated
33
34     display modes: (default: matched line)
35     -c  count of matching lines  -l  show matching filenames
36     -o  only matching part       -q  quiet (errors only)
37     -s  silent (no error msg)    -Z  output NUL terminated
38
39     output prefix (default: filename if checking more than 1 file)
40     -H  force filename           -b  byte offset of match
41     -h  hide filename            -n  line number of match
42
43 config EGREP
44   bool
45   default y
46   depends on GREP
47
48 config FGREP
49   bool
50   default y
51   depends on GREP
52 */
53
54 #define FOR_grep
55 #include "toys.h"
56 #include <regex.h>
57
58 GLOBALS(
59   long m;
60   struct arg_list *f;
61   struct arg_list *e;
62   long a;
63   long b;
64   long c;
65 )
66
67 // Show matches in one file
68 static void do_grep(int fd, char *name)
69 {
70   struct double_list *dlb = 0;
71   FILE *file = fdopen(fd, "r");
72   long offset = 0, after = 0, before = 0;
73   int lcount = 0, mcount = 0;
74   char *bars = 0, indelim = '\n' * !(toys.optflags&FLAG_z),
75        outdelim = '\n' * !(toys.optflags&FLAG_Z);
76
77   if (!fd) name = "(standard input)";
78
79   if (!file) {
80     perror_msg_raw(name);
81     return;
82   }
83
84   // Loop through lines of input
85   for (;;) {
86     char *line = 0, *start;
87     regmatch_t matches;
88     size_t unused;
89     long len;
90     int mmatch = 0;
91
92     lcount++;
93     if (0 > (len = getdelim(&line, &unused, indelim, file))) break;
94     if (line[len-1] == indelim) line[len-1] = 0;
95
96     start = line;
97
98     // Loop through matches in this line
99     do {
100       int rc = 0, skip = 0;
101
102       // Handle non-regex matches
103       if (toys.optflags & FLAG_F) {
104         struct arg_list *seek, fseek;
105         char *s = 0;
106
107         for (seek = TT.e; seek; seek = seek->next) {
108           if (toys.optflags & FLAG_x) {
109             int i = (toys.optflags & FLAG_i);
110
111             if ((i ? strcasecmp : strcmp)(seek->arg, line)) s = line;
112           } else if (!*seek->arg) {
113             seek = &fseek;
114             fseek.arg = s = line;
115             break;
116           }
117           if (toys.optflags & FLAG_i) {
118             long ll = strlen(seek->arg);;
119
120             // Alas, posix hasn't got strcasestr()
121             for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
122             if (!*s) s = 0;
123           } else s = strstr(line, seek->arg);
124           if (s) break;
125         }
126
127         if (s) {
128           matches.rm_so = (s-line);
129           skip = matches.rm_eo = (s-line)+strlen(seek->arg);
130         } else rc = 1;
131       } else {
132         rc = regexec((regex_t *)toybuf, start, 1, &matches,
133                      start==line ? 0 : REG_NOTBOL);
134         skip = matches.rm_eo;
135       }
136
137       if (toys.optflags & FLAG_x)
138         if (matches.rm_so || line[matches.rm_eo]) rc = 1;
139
140       if (!rc && (toys.optflags & FLAG_w)) {
141         char c = 0;
142
143         if ((start+matches.rm_so)!=line) {
144           c = start[matches.rm_so-1];
145           if (!isalnum(c) && c != '_') c = 0;
146         }
147         if (!c) {
148           c = start[matches.rm_eo];
149           if (!isalnum(c) && c != '_') c = 0;
150         }
151         if (c) {
152           start += matches.rm_so+1;
153
154           continue;
155         }
156       }
157
158       if (toys.optflags & FLAG_v) {
159         if (toys.optflags & FLAG_o) {
160           if (rc) skip = matches.rm_eo = strlen(start);
161           else if (!matches.rm_so) {
162             start += skip;
163             continue;
164           } else matches.rm_eo = matches.rm_so;
165         } else {
166           if (!rc) break;
167           matches.rm_eo = strlen(start);
168         }
169         matches.rm_so = 0;
170       } else if (rc) break;
171
172       // At least one line we didn't print since match while -ABC active
173       if (bars) {
174         xputs(bars);
175         bars = 0;
176       }
177       mmatch++;
178       toys.exitval = 0;
179       if (toys.optflags & FLAG_q) xexit();
180       if (toys.optflags & FLAG_l) {
181         printf("%s%c", name, outdelim);
182         free(line);
183         fclose(file);
184         return;
185       }
186       if (toys.optflags & FLAG_o)
187         if (matches.rm_eo == matches.rm_so)
188           break;
189
190       if (!(toys.optflags & FLAG_c)) {
191         if (toys.optflags & FLAG_H) printf("%s:", name);
192         if (toys.optflags & FLAG_n) printf("%d:", lcount);
193         if (toys.optflags & FLAG_b)
194           printf("%ld:", offset + (start-line) +
195               ((toys.optflags & FLAG_o) ? matches.rm_so : 0));
196         if (!(toys.optflags & FLAG_o)) {
197           while (dlb) {
198             struct double_list *dl = dlist_pop(&dlb);
199
200             xprintf("%s%c", dl->data, outdelim);
201             free(dl->data);
202             free(dl);
203             before--;
204           }
205
206           while (before) xprintf("%s%c", line, outdelim);
207           xprintf("%s%c", line, outdelim);
208           if (TT.a) after = TT.a+1;
209         } else {
210           xprintf("%.*s%c", (int)(matches.rm_eo-matches.rm_so),
211                   start+matches.rm_so, outdelim);
212         }
213       }
214
215       start += skip;
216       if (!(toys.optflags & FLAG_o)) break;
217     } while (*start);
218     offset += len;
219
220     if (mmatch) mcount++;
221     else {
222       int discard = (after || TT.b);
223
224       if (after && --after) {
225         xprintf("%s%c", line, outdelim);
226         discard = 0;
227       }
228       if (discard && TT.b) {
229         dlist_add(&dlb, line);
230         line = 0;
231         if (++before>TT.b) {
232           struct double_list *dl;
233
234           dl = dlist_pop(&dlb);
235           free(dl->data);
236           free(dl);
237           before--;
238         } else discard = 0;
239       }
240       if (discard && mcount) bars = "--";
241     }
242     free(line);
243
244     if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
245   }
246
247   if (toys.optflags & FLAG_c) {
248     if (toys.optflags & FLAG_H) printf("%s:", name);
249     xprintf("%d%c", mcount, outdelim);
250   }
251
252   // loopfiles will also close the fd, but this frees an (opaque) struct.
253   fclose(file);
254 }
255
256 static void parse_regex(void)
257 {
258   struct arg_list *al, *new, *list = NULL;
259   long len = 0;
260   char *s, *ss;
261
262   // Add all -f lines to -e list. (Yes, this is leaking allocation context for
263   // exit to free. Not supporting nofork for this command any time soon.)
264   al = TT.f ? TT.f : TT.e;
265   while (al) {
266     if (TT.f) s = ss = xreadfile(al->arg, 0, 0);
267     else s = ss = al->arg;
268
269     // Split lines at \n, add individual lines to new list.
270     do {
271       ss = strchr(s, '\n');
272       if (ss) *(ss++) = 0;
273       new = xmalloc(sizeof(struct arg_list));
274       new->next = list;
275       new->arg = s;
276       list = new;
277       s = ss;
278     } while (ss && *s);
279
280     // Advance, when we run out of -f switch to -e.
281     al = al->next;
282     if (!al && TT.f) {
283       TT.f = 0;
284       al = TT.e;
285     }
286   }
287   TT.e = list;
288
289   if (!(toys.optflags & FLAG_F)) {
290     char *regstr;
291     int i;
292
293     // Convert strings to one big regex
294     for (al = TT.e; al; al = al->next)
295       len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
296
297     regstr = s = xmalloc(len);
298     for (al = TT.e; al; al = al->next) {
299       s = stpcpy(s, al->arg);
300       if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
301       *(s++) = '|';
302     }
303     *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
304
305     i = regcomp((regex_t *)toybuf, regstr,
306                 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
307                 ((toys.optflags & FLAG_i) ? REG_ICASE    : 0));
308
309     if (i) {
310       regerror(i, (regex_t *)toybuf, toybuf+sizeof(regex_t),
311                sizeof(toybuf)-sizeof(regex_t));
312       error_exit("bad REGEX: %s", toybuf);
313     }
314   }
315 }
316
317 static int do_grep_r(struct dirtree *new)
318 {
319   char *name;
320
321   if (new->parent && !dirtree_notdotdot(new)) return 0;
322   if (S_ISDIR(new->st.st_mode)) return DIRTREE_RECURSE;
323
324   // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
325   if (new->parent && !(toys.optflags & FLAG_h)) toys.optflags |= FLAG_H;
326
327   name = dirtree_path(new, 0);
328   do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
329   free(name);
330
331   return 0;
332 }
333
334 void grep_main(void)
335 {
336   char **ss = toys.optargs;
337
338   if (!TT.a) TT.a = TT.c;
339   if (!TT.b) TT.b = TT.c;
340
341   // Handle egrep and fgrep
342   if (*toys.which->name == 'e') toys.optflags |= FLAG_E;
343   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
344
345   if (!TT.e && !TT.f) {
346     if (!*ss) error_exit("no REGEX");
347     TT.e = xzalloc(sizeof(struct arg_list));
348     TT.e->arg = *(ss++);
349     toys.optc--;
350   }
351
352   parse_regex();
353
354   if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
355
356   toys.exitval = 1;
357   if (toys.optflags & FLAG_s) {
358     close(2);
359     xopen("/dev/null", O_RDWR);
360   }
361
362   if (toys.optflags & FLAG_r) {
363     // Iterate through -r arguments. Use "." as default if none provided.
364     for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
365       if (!strcmp(*ss, "-")) do_grep(0, *ss);
366       else dirtree_read(*ss, do_grep_r);
367     }
368   } else loopfiles_rw(ss, O_RDONLY, 0, 1, do_grep);
369 }