OSDN Git Service

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