OSDN Git Service

Change grep -w to checking matches after the fact rather than modifing regex.
[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, "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] [-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     -E  extended regex syntax    -F  fixed (match literal string)
28     -i  case insensitive         -m  stop after this many lines matched
29     -r  recursive (on dir)       -v  invert match
30     -w  whole word (implies -E)  -x  whole line
31     -z  input NUL terminated
32
33     display modes: (default: matched line)
34     -c  count of matching lines  -l  show matching filenames
35     -o  only matching part       -q  quiet (errors only)
36     -s  silent (no error msg)    -Z  output NUL terminated
37
38     output prefix (default: filename if checking more than 1 file)
39     -H  force filename           -b  byte offset of match
40     -h  hide filename            -n  line number of match
41
42 config EGREP
43   bool
44   default y
45   depends on GREP
46
47 config FGREP
48   bool
49   default y
50   depends on GREP
51 */
52
53 #define FOR_grep
54 #include "toys.h"
55 #include <regex.h>
56
57 GLOBALS(
58   long m;
59   struct arg_list *f;
60   struct arg_list *e;
61 )
62
63 // Show matches in one file
64 static void do_grep(int fd, char *name)
65 {
66   FILE *file = fdopen(fd, "r");
67   long offset = 0;
68   int lcount = 0, mcount = 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   if (!file) {
75     perror_msg("%s", name);
76     return;
77   }
78
79   // Loop through lines of input
80   for (;;) {
81     char *line = 0, *start;
82     regmatch_t matches;
83     size_t unused;
84     long len;
85     int mmatch = 0;
86
87     lcount++;
88     if (0 > (len = getdelim(&line, &unused, indelim, file))) break;
89     if (line[len-1] == indelim) line[len-1] = 0;
90
91     start = line;
92
93     // Loop through matches in this line
94     do {
95       int rc = 0, skip = 0;
96
97       // Handle non-regex matches
98       if (toys.optflags & FLAG_F) {
99         struct arg_list *seek, fseek;
100         char *s = 0;
101
102         for (seek = TT.e; seek; seek = seek->next) {
103           if (toys.optflags & FLAG_x) {
104             int i = (toys.optflags & FLAG_i);
105
106             if ((i ? strcasecmp : strcmp)(seek->arg, line)) s = line;
107           } else if (!*seek->arg) {
108             seek = &fseek;
109             fseek.arg = s = line;
110             break;
111           }
112           if (toys.optflags & FLAG_i) {
113             long ll = strlen(seek->arg);;
114
115             // Alas, posix hasn't got strcasestr()
116             for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
117             if (!*s) s = 0;
118           } else s = strstr(line, seek->arg);
119           if (s) break;
120         }
121
122         if (s) {
123           matches.rm_so = (s-line);
124           skip = matches.rm_eo = (s-line)+strlen(seek->arg);
125         } else rc = 1;
126       } else {
127         rc = regexec((regex_t *)toybuf, start, 1, &matches,
128                      start==line ? 0 : REG_NOTBOL);
129         skip = matches.rm_eo;
130       }
131
132       if (toys.optflags & FLAG_x)
133         if (matches.rm_so || line[matches.rm_eo]) rc = 1;
134
135       if (!rc && (toys.optflags & FLAG_w)) {
136         char c = 0;
137
138         if ((start+matches.rm_so)!=line) {
139           c = start[matches.rm_so-1];
140           if (!isalnum(c) && c != '_') c = 0;
141         }
142         if (!c) {
143           c = start[matches.rm_eo];
144           if (!isalnum(c) && c != '_') c = 0;
145         }
146         if (c) {
147           start += matches.rm_so+1;
148
149           continue;
150         }
151       }
152
153       if (toys.optflags & FLAG_v) {
154         if (toys.optflags & FLAG_o) {
155           if (rc) skip = matches.rm_eo = strlen(start);
156           else if (!matches.rm_so) {
157             start += skip;
158             continue;
159           } else matches.rm_eo = matches.rm_so;
160         } else {
161           if (!rc) break;
162           matches.rm_eo = strlen(start);
163         }
164         matches.rm_so = 0;
165       } else if (rc) break;
166
167       mmatch++;
168       toys.exitval = 0;
169       if (toys.optflags & FLAG_q) xexit();
170       if (toys.optflags & FLAG_l) {
171         printf("%s%c", name, outdelim);
172         free(line);
173         fclose(file);
174         return;
175       }
176       if (toys.optflags & FLAG_o)
177         if (matches.rm_eo == matches.rm_so)
178           break;
179
180       if (!(toys.optflags & FLAG_c)) {
181         if (toys.optflags & FLAG_H) printf("%s:", name);
182         if (toys.optflags & FLAG_n) printf("%d:", lcount);
183         if (toys.optflags & FLAG_b)
184           printf("%ld:", offset + (start-line) +
185               ((toys.optflags & FLAG_o) ? matches.rm_so : 0));
186         if (!(toys.optflags & FLAG_o)) xprintf("%s%c", line, outdelim);
187         else {
188           xprintf("%.*s%c", matches.rm_eo - matches.rm_so,
189                   start + matches.rm_so, outdelim);
190         }
191       }
192
193       start += skip;
194       if (!(toys.optflags & FLAG_o)) break;
195     } while (*start);
196     offset += len;
197
198     free(line);
199
200     if (mmatch) mcount++;
201     if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
202   }
203
204   if (toys.optflags & FLAG_c) {
205     if (toys.optflags & FLAG_H) printf("%s:", name);
206     xprintf("%d%c", mcount, outdelim);
207   }
208
209   // loopfiles will also close the fd, but this frees an (opaque) struct.
210   fclose(file);
211 }
212
213 static void parse_regex(void)
214 {
215   struct arg_list *al, *new, *list = NULL;
216   long len = 0;
217   char *s, *ss;
218
219   // Add all -f lines to -e list. (Yes, this is leaking allocation context for
220   // exit to free. Not supporting nofork for this command any time soon.)
221   al = TT.f ? TT.f : TT.e;
222   while (al) {
223     if (TT.f) s = ss = xreadfile(al->arg, 0, 0);
224     else s = ss = al->arg;
225
226     // Split lines at \n, add individual lines to new list.
227     do {
228       ss = strchr(s, '\n');
229       if (ss) *(ss++) = 0;
230       new = xmalloc(sizeof(struct arg_list));
231       new->next = list;
232       new->arg = s;
233       list = new;
234       s = ss;
235     } while (ss && *s);
236
237     // Advance, when we run out of -f switch to -e.
238     al = al->next;
239     if (!al && TT.f) {
240       TT.f = 0;
241       al = TT.e;
242     }
243   }
244   TT.e = list;
245
246   if (!(toys.optflags & FLAG_F)) {
247     char *regstr;
248     int i;
249
250     // Convert strings to one big regex
251     for (al = TT.e; al; al = al->next)
252       len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
253
254     regstr = s = xmalloc(len);
255     for (al = TT.e; al; al = al->next) {
256       s = stpcpy(s, al->arg);
257       if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
258       *(s++) = '|';
259     }
260     *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
261
262     i = regcomp((regex_t *)toybuf, regstr,
263                 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
264                 ((toys.optflags & FLAG_i) ? REG_ICASE    : 0));
265
266     if (i) {
267       regerror(i, (regex_t *)toybuf, toybuf+sizeof(regex_t),
268                sizeof(toybuf)-sizeof(regex_t));
269       error_exit("bad REGEX: %s", toybuf);
270     }
271   }
272 }
273
274 static int do_grep_r(struct dirtree *new)
275 {
276   char *name;
277
278   if (new->parent && !dirtree_notdotdot(new)) return 0;
279   if (S_ISDIR(new->st.st_mode)) return DIRTREE_RECURSE;
280
281   // "grep -r onefile" doesn't show filenames, but "grep -r onedir" should.
282   if (new->parent && !(toys.optflags & FLAG_h)) toys.optflags |= FLAG_H;
283
284   name = dirtree_path(new, 0);
285   do_grep(openat(dirtree_parentfd(new), new->name, 0), name);
286   free(name);
287
288   return 0;
289 }
290
291 void grep_main(void)
292 {
293   char **ss = toys.optargs;
294
295   // Handle egrep and fgrep
296   if (*toys.which->name == 'e') toys.optflags |= FLAG_E;
297   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
298
299   if (!TT.e && !TT.f) {
300     if (!*ss) error_exit("no REGEX");
301     TT.e = xzalloc(sizeof(struct arg_list));
302     TT.e->arg = *(ss++);
303     toys.optc--;
304   }
305
306   parse_regex();
307
308   if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
309
310   toys.exitval = 1;
311   if (toys.optflags & FLAG_s) {
312     close(2);
313     xopen("/dev/null", O_RDWR);
314   }
315
316   if (toys.optflags & FLAG_r) {
317     // Iterate through -r arguments. Use "." as default if none provided.
318     for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
319       if (!strcmp(*ss, "-")) do_grep(0, *ss);
320       else dirtree_read(*ss, do_grep_r);
321     }
322   } else loopfiles_rw(ss, O_RDONLY, 0, 1, do_grep);
323 }