OSDN Git Service

Merge remote-tracking branch 'toybox/master' into HEAD
[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   char indelim, outdelim;
67 )
68
69 // Emit line with various potential prefixes and delimiter
70 static void outline(char *line, char dash, char *name, long lcount, long bcount,
71   int trim)
72 {
73   if (name && (toys.optflags&FLAG_H)) printf("%s%c", name, dash);
74   if (!line || (lcount && (toys.optflags&FLAG_n)))
75     printf("%ld%c", lcount, line ? dash : TT.outdelim);
76   if (bcount && (toys.optflags&FLAG_b)) printf("%ld%c", bcount-1, dash);
77   if (line) xprintf("%.*s%c", trim ? trim : INT_MAX, line, TT.outdelim);
78 }
79
80 // Show matches in one file
81 static void do_grep(int fd, char *name)
82 {
83   struct double_list *dlb = 0;
84   FILE *file = fdopen(fd, "r");
85   long lcount = 0, mcount = 0, offset = 0, after = 0, before = 0;
86   char *bars = 0;
87
88   if (!fd) name = "(standard input)";
89
90   if (!file) {
91     perror_msg_raw(name);
92     return;
93   }
94
95   // Loop through lines of input
96   for (;;) {
97     char *line = 0, *start;
98     regmatch_t matches;
99     size_t unused;
100     long len;
101     int mmatch = 0;
102
103     lcount++;
104     if (0 > (len = getdelim(&line, &unused, TT.indelim, file))) break;
105     if (line[len-1] == TT.indelim) line[len-1] = 0;
106
107     start = line;
108
109     // Loop through matches in this line
110     do {
111       int rc = 0, skip = 0;
112
113       // Handle non-regex matches
114       if (toys.optflags & FLAG_F) {
115         struct arg_list *seek, fseek;
116         char *s = 0;
117
118         for (seek = TT.e; seek; seek = seek->next) {
119           if (toys.optflags & FLAG_x) {
120             int i = (toys.optflags & FLAG_i);
121
122             if ((i ? strcasecmp : strcmp)(seek->arg, line)) s = line;
123           } else if (!*seek->arg) {
124             seek = &fseek;
125             fseek.arg = s = line;
126             break;
127           }
128           if (toys.optflags & FLAG_i) {
129             long ll = strlen(seek->arg);;
130
131             // Alas, posix hasn't got strcasestr()
132             for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
133             if (!*s) s = 0;
134           } else s = strstr(line, seek->arg);
135           if (s) break;
136         }
137
138         if (s) {
139           matches.rm_so = (s-line);
140           skip = matches.rm_eo = (s-line)+strlen(seek->arg);
141         } else rc = 1;
142       } else {
143         rc = regexec((regex_t *)toybuf, start, 1, &matches,
144                      start==line ? 0 : REG_NOTBOL);
145         skip = matches.rm_eo;
146       }
147
148       if (toys.optflags & FLAG_x)
149         if (matches.rm_so || line[matches.rm_eo]) rc = 1;
150
151       if (!rc && (toys.optflags & FLAG_w)) {
152         char c = 0;
153
154         if ((start+matches.rm_so)!=line) {
155           c = start[matches.rm_so-1];
156           if (!isalnum(c) && c != '_') c = 0;
157         }
158         if (!c) {
159           c = start[matches.rm_eo];
160           if (!isalnum(c) && c != '_') c = 0;
161         }
162         if (c) {
163           start += matches.rm_so+1;
164
165           continue;
166         }
167       }
168
169       if (toys.optflags & FLAG_v) {
170         if (toys.optflags & FLAG_o) {
171           if (rc) skip = matches.rm_eo = strlen(start);
172           else if (!matches.rm_so) {
173             start += skip;
174             continue;
175           } else matches.rm_eo = matches.rm_so;
176         } else {
177           if (!rc) break;
178           matches.rm_eo = strlen(start);
179         }
180         matches.rm_so = 0;
181       } else if (rc) break;
182
183       // At least one line we didn't print since match while -ABC active
184       if (bars) {
185         xputs(bars);
186         bars = 0;
187       }
188       mmatch++;
189       toys.exitval = 0;
190       if (toys.optflags & FLAG_q) xexit();
191       if (toys.optflags & FLAG_l) {
192         xprintf("%s%c", name, TT.outdelim);
193         free(line);
194         fclose(file);
195         return;
196       }
197       if (toys.optflags & FLAG_o)
198         if (matches.rm_eo == matches.rm_so)
199           break;
200
201       if (!(toys.optflags & FLAG_c)) {
202         long bcount = 1 + offset + (start-line) +
203           ((toys.optflags & FLAG_o) ? matches.rm_so : 0);
204  
205         if (!(toys.optflags & FLAG_o)) {
206           while (dlb) {
207             struct double_list *dl = dlist_pop(&dlb);
208
209             outline(dl->data, '-', name, lcount-before, 0, 0);
210             free(dl->data);
211             free(dl);
212             before--;
213           }
214
215           outline(line, ':', name, lcount, bcount, 0);
216           if (TT.a) after = TT.a+1;
217         } else outline(start+matches.rm_so, ':', name, lcount, bcount,
218                        matches.rm_eo-matches.rm_so);
219       }
220
221       start += skip;
222       if (!(toys.optflags & FLAG_o)) break;
223     } while (*start);
224     offset += len;
225
226     if (mmatch) mcount++;
227     else {
228       int discard = (after || TT.b);
229
230       if (after && --after) {
231         outline(line, '-', name, lcount, 0, 0);
232         discard = 0;
233       }
234       if (discard && TT.b) {
235         dlist_add(&dlb, line);
236         line = 0;
237         if (++before>TT.b) {
238           struct double_list *dl;
239
240           dl = dlist_pop(&dlb);
241           free(dl->data);
242           free(dl);
243           before--;
244         } else discard = 0;
245       }
246       // If we discarded a line while displaying context, show bars before next
247       // line (but don't show them now in case that was last match in file)
248       if (discard && mcount) bars = "--";
249     }
250     free(line);
251
252     if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
253   }
254
255   if (toys.optflags & FLAG_c) outline(0, ':', name, mcount, 0, 0);
256
257   // loopfiles will also close the fd, but this frees an (opaque) struct.
258   fclose(file);
259 }
260
261 static void parse_regex(void)
262 {
263   struct arg_list *al, *new, *list = NULL;
264   long len = 0;
265   char *s, *ss;
266
267   // Add all -f lines to -e list. (Yes, this is leaking allocation context for
268   // exit to free. Not supporting nofork for this command any time soon.)
269   al = TT.f ? TT.f : TT.e;
270   while (al) {
271     if (TT.f) s = ss = xreadfile(al->arg, 0, 0);
272     else s = ss = al->arg;
273
274     // Split lines at \n, add individual lines to new list.
275     do {
276       ss = strchr(s, '\n');
277       if (ss) *(ss++) = 0;
278       new = xmalloc(sizeof(struct arg_list));
279       new->next = list;
280       new->arg = s;
281       list = new;
282       s = ss;
283     } while (ss && *s);
284
285     // Advance, when we run out of -f switch to -e.
286     al = al->next;
287     if (!al && TT.f) {
288       TT.f = 0;
289       al = TT.e;
290     }
291   }
292   TT.e = list;
293
294   if (!(toys.optflags & FLAG_F)) {
295     char *regstr;
296     int i;
297
298     // Convert strings to one big regex
299     for (al = TT.e; al; al = al->next)
300       len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
301
302     regstr = s = xmalloc(len);
303     for (al = TT.e; al; al = al->next) {
304       s = stpcpy(s, al->arg);
305       if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
306       *(s++) = '|';
307     }
308     *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
309
310     i = regcomp((regex_t *)toybuf, regstr,
311                 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
312                 ((toys.optflags & FLAG_i) ? REG_ICASE    : 0));
313
314     if (i) {
315       regerror(i, (regex_t *)toybuf, toybuf+sizeof(regex_t),
316                sizeof(toybuf)-sizeof(regex_t));
317       error_exit("bad REGEX: %s", toybuf);
318     }
319   }
320 }
321
322 static int do_grep_r(struct dirtree *new)
323 {
324   char *name;
325
326   if (new->parent && !dirtree_notdotdot(new)) return 0;
327   if (S_ISDIR(new->st.st_mode)) return DIRTREE_RECURSE;
328
329   // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
330   if (new->parent && !(toys.optflags & FLAG_h)) toys.optflags |= FLAG_H;
331
332   name = dirtree_path(new, 0);
333   do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
334   free(name);
335
336   return 0;
337 }
338
339 void grep_main(void)
340 {
341   char **ss = toys.optargs;
342
343   if (!TT.a) TT.a = TT.c;
344   if (!TT.b) TT.b = TT.c;
345
346   TT.indelim = '\n' * !(toys.optflags&FLAG_z);
347   TT.outdelim = '\n' * !(toys.optflags&FLAG_Z);
348
349   // Handle egrep and fgrep
350   if (*toys.which->name == 'e') toys.optflags |= FLAG_E;
351   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
352
353   if (!TT.e && !TT.f) {
354     if (!*ss) error_exit("no REGEX");
355     TT.e = xzalloc(sizeof(struct arg_list));
356     TT.e->arg = *(ss++);
357     toys.optc--;
358   }
359
360   parse_regex();
361
362   if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
363
364   toys.exitval = 1;
365   if (toys.optflags & FLAG_s) {
366     close(2);
367     xopen("/dev/null", O_RDWR);
368   }
369
370   if (toys.optflags & FLAG_r) {
371     // Iterate through -r arguments. Use "." as default if none provided.
372     for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
373       if (!strcmp(*ss, "-")) do_grep(0, *ss);
374       else dirtree_read(*ss, do_grep_r);
375     }
376   } else loopfiles_rw(ss, O_RDONLY, 0, 1, do_grep);
377 }