OSDN Git Service

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