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