include busybox after libc includes
[oweals/busybox.git] / findutils / grep.c
1 /*
2  * Mini grep implementation for busybox using libc regex.
3  *
4  * Copyright (C) 1999,2000,2001 by Lineo, inc. and Mark Whitley
5  * Copyright (C) 1999,2000,2001 by Mark Whitley <markw@codepoet.org> 
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20  *
21  */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <getopt.h>
26 #include <regex.h>
27 #include <string.h> /* for strerror() */
28 #include <errno.h>
29 #include "busybox.h"
30
31
32 extern int optind; /* in unistd.h */
33 extern void xregcomp(regex_t *preg, const char *regex, int cflags); /* in busybox.h */
34
35 /* options */
36 static int reflags            = REG_NOSUB; 
37 static int print_filename     = 0;
38 static int print_line_num     = 0;
39 static int print_match_counts = 0;
40 static int be_quiet           = 0;
41 static int invert_search      = 0;
42 static int suppress_err_msgs  = 0;
43 static int print_files_with_matches  = 0;
44
45 #ifdef CONFIG_FEATURE_GREP_CONTEXT
46 extern char *optarg; /* in getopt.h */
47 static int lines_before      = 0;
48 static int lines_after       = 0;
49 static char **before_buf     = NULL;
50 static int last_line_printed = 0;
51 #endif /* CONFIG_FEATURE_GREP_CONTEXT */
52
53 /* globals used internally */
54 static regex_t *regexes = NULL; /* growable array of compiled regular expressions */
55 static int nregexes = 0; /* number of elements in above arrary */
56 static int matched; /* keeps track of whether we ever matched */
57 static char *cur_file = NULL; /* the current file we are reading */
58
59
60 static void print_line(const char *line, int linenum, char decoration)
61 {
62 #ifdef CONFIG_FEATURE_GREP_CONTEXT
63         /* possibly print the little '--' seperator */
64         if ((lines_before || lines_after) && last_line_printed &&
65                         last_line_printed < linenum - 1) {
66                 puts("--");
67         }
68         last_line_printed = linenum;
69 #endif
70         if (print_filename)
71                 printf("%s%c", cur_file, decoration);
72         if (print_line_num)
73                 printf("%i%c", linenum, decoration);
74         puts(line);
75 }
76
77
78 static void grep_file(FILE *file)
79 {
80         char *line = NULL;
81         int ret;
82         int linenum = 0;
83         int nmatches = 0;
84         int i;
85 #ifdef CONFIG_FEATURE_GREP_CONTEXT
86         int print_n_lines_after = 0;
87         int curpos = 0; /* track where we are in the circular 'before' buffer */
88         int idx = 0; /* used for iteration through the circular buffer */
89 #endif /* CONFIG_FEATURE_GREP_CONTEXT */ 
90
91         while ((line = get_line_from_file(file)) != NULL) {
92                 chomp(line);
93                 linenum++;
94
95                 for (i = 0; i < nregexes; i++) {
96                         /*
97                          * test for a postitive-assertion match (regexec returns success (0)
98                          * and the user did not specify invert search), or a negative-assertion
99                          * match (regexec returns failure (REG_NOMATCH) and the user specified
100                          * invert search)
101                          */
102                         ret = regexec(&regexes[i], line, 0, NULL, 0);
103                         if ((ret == 0 && !invert_search) || (ret == REG_NOMATCH && invert_search)) {
104
105                                 /* if we found a match but were told to be quiet, stop here and
106                                  * return success */
107                                 if (be_quiet)
108                                         exit(0);
109
110                                 /* keep track of matches */
111                                 nmatches++;
112
113                                 /* if we're just printing filenames, we stop after the first match */
114                                 if (print_files_with_matches)
115                                         break;
116
117                                 /* print the matched line */
118                                 if (print_match_counts == 0) {
119 #ifdef CONFIG_FEATURE_GREP_CONTEXT
120                                         int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
121
122                                         /* if we were told to print 'before' lines and there is at least
123                                          * one line in the circular buffer, print them */
124                                         if (lines_before && before_buf[prevpos] != NULL) {
125                                                 int first_buf_entry_line_num = linenum - lines_before;
126
127                                                 /* advance to the first entry in the circular buffer, and
128                                                  * figure out the line number is of the first line in the
129                                                  * buffer */
130                                                 idx = curpos;
131                                                 while (before_buf[idx] == NULL) {
132                                                         idx = (idx + 1) % lines_before;
133                                                         first_buf_entry_line_num++;
134                                                 }
135
136                                                 /* now print each line in the buffer, clearing them as we go */
137                                                 while (before_buf[idx] != NULL) {
138                                                         print_line(before_buf[idx], first_buf_entry_line_num, '-');
139                                                         free(before_buf[idx]);
140                                                         before_buf[idx] = NULL;
141                                                         idx = (idx + 1) % lines_before;
142                                                         first_buf_entry_line_num++;
143                                                 }
144                                         }
145
146                                         /* make a note that we need to print 'after' lines */
147                                         print_n_lines_after = lines_after;
148 #endif /* CONFIG_FEATURE_GREP_CONTEXT */ 
149                                         print_line(line, linenum, ':');
150                                 }
151                         }
152 #ifdef CONFIG_FEATURE_GREP_CONTEXT
153                         else { /* no match */
154                                 /* Add the line to the circular 'before' buffer */
155                                 if(lines_before) {
156                                         free(before_buf[curpos]);
157                                         before_buf[curpos] = xstrdup(line);
158                                         curpos = (curpos + 1) % lines_before;
159                                 }
160                         }
161
162                         /* if we need to print some context lines after the last match, do so */
163                         if (print_n_lines_after && (last_line_printed != linenum)) {
164                                 print_line(line, linenum, '-');
165                                 print_n_lines_after--;
166                         }
167 #endif /* CONFIG_FEATURE_GREP_CONTEXT */ 
168                 } /* for */
169                 free(line);
170         }
171
172
173         /* special-case file post-processing for options where we don't print line
174          * matches, just filenames and possibly match counts */
175
176         /* grep -c: print [filename:]count, even if count is zero */
177         if (print_match_counts) {
178                 if (print_filename)
179                         printf("%s:", cur_file);
180                 if (print_files_with_matches && nmatches > 0)
181                         printf("1\n");
182                 else
183                     printf("%d\n", nmatches);
184         }
185
186         /* grep -l: print just the filename, but only if we grepped the line in the file  */
187         if (print_files_with_matches && nmatches > 0) {
188                 puts(cur_file);
189         }
190
191
192         /* remember if we matched */
193         if (nmatches != 0)
194                 matched = 1;
195 }
196
197
198 static void add_regex(const char *restr)
199 {
200         regexes = xrealloc(regexes, sizeof(regex_t) * (++nregexes));
201         xregcomp(&regexes[nregexes-1], restr, reflags);
202 }
203
204
205 static void     load_regexes_from_file(const char *filename)
206 {
207         char *line;
208         FILE *f = xfopen(filename, "r");
209         while ((line = get_line_from_file(f)) != NULL) {
210                 chomp(line);
211                 add_regex(line);
212                 free(line);
213         }
214 }
215
216
217 #ifdef CONFIG_FEATURE_CLEAN_UP
218 static void destroy_regexes(void)
219 {
220         if (regexes == NULL)
221                 return;
222
223         /* destroy all the elments in the array */
224         while (--nregexes >= 0) {
225                 regfree(&(regexes[nregexes]));
226         }
227         free(regexes);
228 }
229 #endif
230
231
232 extern int grep_main(int argc, char **argv)
233 {
234         int opt;
235 #if defined (CONFIG_FEATURE_GREP_CONTEXT)
236         char *junk;
237 #endif
238
239 #ifdef CONFIG_FEATURE_CLEAN_UP
240         /* destroy command strings on exit */
241         atexit(destroy_regexes);
242 #endif
243
244 #ifdef CONFIG_FEATURE_GREP_EGREP_ALIAS
245         if (strcmp(get_last_path_component(argv[0]), "egrep") == 0)
246                 reflags |= REG_EXTENDED;
247 #endif
248
249         /* do normal option parsing */
250         while ((opt = getopt(argc, argv, "iHhlnqvsce:f:"
251 #ifdef CONFIG_FEATURE_GREP_CONTEXT
252 "A:B:C:"
253 #endif
254 #ifdef CONFIG_FEATURE_GREP_EGREP_ALIAS
255 "E"
256 #endif
257 )) > 0) {
258                 switch (opt) {
259                         case 'i':
260                                 reflags |= REG_ICASE;
261                                 break;
262                         case 'l':
263                                 print_files_with_matches++;
264                                 break;
265                         case 'H':
266                                 print_filename++;
267                                 break;
268                         case 'h':
269                                 print_filename--;
270                                 break;
271                         case 'n':
272                                 print_line_num++;
273                                 break;
274                         case 'q':
275                                 be_quiet++;
276                                 break;
277                         case 'v':
278                                 invert_search++;
279                                 break;
280                         case 's':
281                                 suppress_err_msgs++;
282                                 break;
283                         case 'c':
284                                 print_match_counts++;
285                                 break;
286                         case 'e':
287                                 add_regex(optarg);
288                                 break;
289 #ifdef CONFIG_FEATURE_GREP_EGREP_ALIAS
290                         case 'E':
291                                 reflags |= REG_EXTENDED;
292                                 break;
293 #endif
294                         case 'f':
295                                 load_regexes_from_file(optarg);
296                                 break;
297 #ifdef CONFIG_FEATURE_GREP_CONTEXT
298                         case 'A':
299                                 lines_after = strtoul(optarg, &junk, 10);
300                                 if(*junk != '\0')
301                                         error_msg_and_die("invalid context length argument");
302                                 break;
303                         case 'B':
304                                 lines_before = strtoul(optarg, &junk, 10);
305                                 if(*junk != '\0')
306                                         error_msg_and_die("invalid context length argument");
307                                 before_buf = (char **)xcalloc(lines_before, sizeof(char *));
308                                 break;
309                         case 'C':
310                                 lines_after = lines_before = strtoul(optarg, &junk, 10);
311                                 if(*junk != '\0')
312                                         error_msg_and_die("invalid context length argument");
313                                 before_buf = (char **)xcalloc(lines_before, sizeof(char *));
314                                 break;
315 #endif /* CONFIG_FEATURE_GREP_CONTEXT */
316                         default:
317                                 show_usage();
318                 }
319         }
320
321         /* if we didn't get a pattern from a -e and no command file was specified,
322          * argv[optind] should be the pattern. no pattern, no worky */
323         if (nregexes == 0) {
324                 if (argv[optind] == NULL)
325                         show_usage();
326                 else {
327                         add_regex(argv[optind]);
328                         optind++;
329                 }
330         }
331
332         /* sanity checks */
333         if (print_match_counts || be_quiet || print_files_with_matches) {
334                 print_line_num = 0;
335 #ifdef CONFIG_FEATURE_GREP_CONTEXT
336                 lines_before = 0;
337                 lines_after = 0;
338 #endif
339         }
340
341         /* argv[(optind)..(argc-1)] should be names of file to grep through. If
342          * there is more than one file to grep, we will print the filenames */
343         if ((argc-1) - (optind) > 0)
344                 print_filename++;
345
346         /* If no files were specified, or '-' was specified, take input from
347          * stdin. Otherwise, we grep through all the files specified. */
348         if (argv[optind] == NULL || (strcmp(argv[optind], "-") == 0)) {
349                 grep_file(stdin);
350         }
351         else {
352                 int i;
353                 FILE *file;
354                 for (i = optind; i < argc; i++) {
355                         cur_file = argv[i];
356                         file = fopen(cur_file, "r");
357                         if (file == NULL) {
358                                 if (!suppress_err_msgs)
359                                         perror_msg("%s", cur_file);
360                         }
361                         else {
362                                 grep_file(file);
363                                 fclose(file);
364                         }
365                 }
366         }
367
368         return !matched; /* invert return value 0 = success, 1 = failed */
369 }