OSDN Git Service

Redo option parsing infrastructure so #define FORCE_FLAGS can unzero flag macros...
[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, "ZzEFHabhinorsvwclqe*f*m#x[!wx][!EFw]", TOYFLAG_BIN))
8 USE_GREP(OLDTOY(egrep, grep, TOYFLAG_BIN))
9 USE_GREP(OLDTOY(fgrep, 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
50   struct arg_list *regex;
51 )
52
53 static void do_grep(int fd, char *name)
54 {
55   FILE *file = fdopen(fd, "r");
56   long offset = 0;
57   int lcount = 0, mcount = 0, which = toys.optflags & FLAG_w ? 2 : 0;
58   char indelim = '\n' * !(toys.optflags&FLAG_z),
59        outdelim = '\n' * !(toys.optflags&FLAG_Z);
60
61   if (!fd) name = "(standard input)";
62
63   if (!file) {
64     perror_msg("%s", name);
65     return;
66   }
67
68   for (;;) {
69     char *line = 0, *start;
70     regmatch_t matches[3];
71     size_t unused;
72     long len;
73     int mmatch = 0;
74
75     lcount++;
76     if (0 > (len = getdelim(&line, &unused, indelim, file))) break;
77     if (line[len-1] == indelim) line[len-1] = 0;
78
79     start = line;
80
81     for (;;)
82     {
83       int rc = 0, skip = 0;
84
85       if (toys.optflags & FLAG_F) {
86         struct arg_list *seek, fseek;
87         char *s = 0;
88
89         for (seek = TT.e; seek; seek = seek->next) {
90           if (toys.optflags & FLAG_x) {
91             int i = (toys.optflags & FLAG_i);
92
93             if ((i ? strcasecmp : strcmp)(seek->arg, line)) s = line;
94           } else if (!*seek->arg) {
95             seek = &fseek;
96             fseek.arg = s = line;
97             break;
98           }
99           if (toys.optflags & FLAG_i) {
100             long ll = strlen(seek->arg);;
101
102             // Alas, posix hasn't got strcasestr()
103             for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
104             if (!*s) s = 0;
105           } else s = strstr(line, seek->arg);
106           if (s) break;
107         }
108
109         if (s) {
110           matches[which].rm_so = (s-line);
111           skip = matches[which].rm_eo = (s-line)+strlen(seek->arg);
112         } else rc = 1;
113       } else {
114         rc = regexec((regex_t *)toybuf, start, 3, matches,
115                      start==line ? 0 : REG_NOTBOL);
116         skip = matches[which].rm_eo;
117       }
118
119       if (toys.optflags & FLAG_x)
120         if (matches[which].rm_so || line[matches[which].rm_eo]) rc = 1;
121
122       if (toys.optflags & FLAG_v) {
123         if (toys.optflags & FLAG_o) {
124           if (rc) skip = matches[which].rm_eo = strlen(start);
125           else if (!matches[which].rm_so) {
126             start += skip;
127             continue;
128           } else matches[which].rm_eo = matches[which].rm_so;
129         } else {
130           if (!rc) break;
131           matches[which].rm_eo = strlen(start);
132         }
133         matches[which].rm_so = 0;
134       } else if (rc) break;
135
136       mmatch++;
137       toys.exitval = 0;
138       if (toys.optflags & FLAG_q) xexit();
139       if (toys.optflags & FLAG_l) {
140         printf("%s%c", name, outdelim);
141         free(line);
142         fclose(file);
143         return;
144       }
145       if (toys.optflags & FLAG_o)
146         if (matches[which].rm_eo == matches[which].rm_so)
147           break;
148
149       if (!(toys.optflags & FLAG_c)) {
150         if (toys.optflags & FLAG_H) printf("%s:", name);
151         if (toys.optflags & FLAG_n) printf("%d:", lcount);
152         if (toys.optflags & FLAG_b)
153           printf("%ld:", offset + (start-line) +
154               ((toys.optflags & FLAG_o) ? matches[which].rm_so : 0));
155         if (!(toys.optflags & FLAG_o)) xprintf("%s%c", line, outdelim);
156         else {
157           xprintf("%.*s%c", matches[which].rm_eo - matches[which].rm_so,
158                   start + matches[which].rm_so, outdelim);
159         }
160       }
161
162       start += skip;
163       if (!(toys.optflags & FLAG_o) || !*start) break;
164     }
165     offset += len;
166
167     free(line);
168
169     if (mmatch) mcount++;
170     if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
171   }
172
173   if (toys.optflags & FLAG_c) {
174     if (toys.optflags & FLAG_H) printf("%s:", name);
175     xprintf("%d%c", mcount, outdelim);
176   }
177
178   // loopfiles will also close the fd, but this frees an (opaque) struct.
179   fclose(file);
180 }
181
182 static void parse_regex(void)
183 {
184   struct arg_list *al, *new, *list = NULL;
185   long len = 0;
186   char *s, *ss;
187
188   // Add all -f lines to -e list. (Yes, this is leaking allocation context for
189   // exit to free. Not supporting nofork for this command any time soon.)
190   al = TT.f ? TT.f : TT.e;
191   while (al) {
192     if (TT.f) s = ss = xreadfile(al->arg, 0, 0);
193     else s = ss = al->arg;
194
195     do {
196       ss = strchr(s, '\n');
197       if (ss) *(ss++) = 0;
198       new = xmalloc(sizeof(struct arg_list));
199       new->next = list;
200       new->arg = s;
201       list = new;
202       s = ss;
203     } while (ss && *s);
204     al = al->next;
205     if (!al && TT.f) {
206       TT.f = 0;
207       al = TT.e;
208     }
209   }
210   TT.e = list;
211
212   if (!(toys.optflags & FLAG_F)) {
213     int w = toys.optflags & FLAG_w;
214     char *regstr;
215
216     // Convert strings to one big regex
217     if (w) len = 36;
218     for (al = TT.e; al; al = al->next)
219       len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
220
221     regstr = s = xmalloc(len);
222     if (w) s = stpcpy(s, "(^|[^_[:alnum:]])(");
223     for (al = TT.e; al; al = al->next) {
224       s = stpcpy(s, al->arg);
225       if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
226       *(s++) = '|';
227     }
228     *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
229     if (w) strcpy(s, ")($|[^_[:alnum:]])");
230
231     w = regcomp((regex_t *)toybuf, regstr,
232                 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
233                 ((toys.optflags & FLAG_i) ? REG_ICASE    : 0));
234
235     if (w) {
236       regerror(w, (regex_t *)toybuf, toybuf+sizeof(regex_t),
237                sizeof(toybuf)-sizeof(regex_t));
238       error_exit("bad REGEX: %s", toybuf);
239     }
240   }
241 }
242
243 static int do_grep_r(struct dirtree *new)
244 {
245   char *name;
246
247   if (new->parent && !dirtree_notdotdot(new)) return 0;
248   if (S_ISDIR(new->st.st_mode)) return DIRTREE_RECURSE;
249
250   // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
251   if (new->parent && !(toys.optflags & FLAG_h)) toys.optflags |= FLAG_H;
252
253   name = dirtree_path(new, 0);
254   do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
255   free(name);
256
257   return 0;
258 }
259
260 void grep_main(void)
261 {
262   char **ss;
263
264   // Handle egrep and fgrep
265   if (*toys.which->name == 'e' || (toys.optflags & FLAG_w))
266     toys.optflags |= FLAG_E;
267   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
268
269   if (!TT.e && !TT.f) {
270     if (!*toys.optargs) error_exit("no REGEX");
271     TT.e = xzalloc(sizeof(struct arg_list));
272     TT.e->arg = *(toys.optargs++);
273     toys.optc--;
274   }
275
276   parse_regex();
277
278   if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
279
280   toys.exitval = 1;
281   if (toys.optflags & FLAG_s) {
282     close(2);
283     xopen("/dev/null", O_RDWR);
284   }
285
286   if (toys.optflags & FLAG_r) {
287     for (ss=toys.optargs; *ss; ss++) {
288       if (!strcmp(*ss, "-")) do_grep(0, *ss);
289       else dirtree_read(*ss, do_grep_r);
290     }
291   } else loopfiles_rw(toys.optargs, O_RDONLY, 0, 1, do_grep);
292 }