Updates from both Vladimir and Larry
[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 ignore_case       = 0;
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 regex; /* storage space for compiled regular expression */
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 static void print_line(const char *line, int linenum, char decoration)
60 {
61 #ifdef BB_FEATURE_GREP_CONTEXT
62         /* possibly print the little '--' seperator */
63         if ((lines_before || lines_after) && last_line_printed &&
64                         last_line_printed < linenum - 1) {
65                 puts("--");
66         }
67         last_line_printed = linenum;
68 #endif
69         if (print_filename)
70                 printf("%s%c", cur_file, decoration);
71         if (print_line_num)
72                 printf("%i%c", linenum, decoration);
73         puts(line);
74 }
75
76 static void grep_file(FILE *file)
77 {
78         char *line = NULL;
79         int ret;
80         int linenum = 0;
81         int nmatches = 0;
82 #ifdef BB_FEATURE_GREP_CONTEXT
83         int print_n_lines_after = 0;
84         int curpos = 0; /* track where we are in the circular 'before' buffer */
85         int idx = 0; /* used for iteration through the circular buffer */
86 #endif /* BB_FEATURE_GREP_CONTEXT */ 
87
88         while ((line = get_line_from_file(file)) != NULL) {
89                 chomp(line);
90                 linenum++;
91
92                 /*
93                  * test for a postitive-assertion match (regexec returns success (0)
94                  * and the user did not specify invert search), or a negative-assertion
95                  * match (regexec returns failure (REG_NOMATCH) and the user specified
96                  * invert search)
97                  */
98                 ret = regexec(&regex, line, 0, NULL, 0);
99                 if ((ret == 0 && !invert_search) || (ret == REG_NOMATCH && invert_search)) {
100
101                         /* if we found a match but were told to be quiet, stop here and
102                          * return success */
103                         if (be_quiet) {
104                                 regfree(&regex);
105                                 exit(0);
106                         }
107
108                         /* keep track of matches */
109                         nmatches++;
110
111                         /* if we're just printing filenames, we stop after the first match */
112                         if (print_files_with_matches)
113                                 break;
114
115                         /* print the matched line */
116                         if (print_match_counts == 0) {
117 #ifdef BB_FEATURE_GREP_CONTEXT
118                                 int prevpos = (curpos == 0) ? lines_before - 1 : curpos - 1;
119
120                                 /* if we were told to print 'before' lines and there is at least
121                                  * one line in the circular buffer, print them */
122                                 if (lines_before && before_buf[prevpos] != NULL) {
123                                         int first_buf_entry_line_num = linenum - lines_before;
124
125                                         /* advance to the first entry in the circular buffer, and
126                                          * figure out the line number is of the first line in the
127                                          * buffer */
128                                         idx = curpos;
129                                         while (before_buf[idx] == NULL) {
130                                                 idx = (idx + 1) % lines_before;
131                                                 first_buf_entry_line_num++;
132                                         }
133
134                                         /* now print each line in the buffer, clearing them as we go */
135                                         while (before_buf[idx] != NULL) {
136                                                 print_line(before_buf[idx], first_buf_entry_line_num, '-');
137                                                 free(before_buf[idx]);
138                                                 before_buf[idx] = NULL;
139                                                 idx = (idx + 1) % lines_before;
140                                                 first_buf_entry_line_num++;
141                                         }
142                                 }
143
144                                 /* make a note that we need to print 'after' lines */
145                                 print_n_lines_after = lines_after;
146 #endif /* BB_FEATURE_GREP_CONTEXT */ 
147                                 print_line(line, linenum, ':');
148                         }
149                 }
150 #ifdef BB_FEATURE_GREP_CONTEXT
151                 else { /* no match */
152                         /* Add the line to the circular 'before' buffer */
153                         if(lines_before) {
154                                 if(before_buf[curpos])
155                                         free(before_buf[curpos]);
156                                 before_buf[curpos] = strdup(line);
157                                 curpos = (curpos + 1) % lines_before;
158                         }
159                 }
160
161                 /* if we need to print some context lines after the last match, do so */
162                 if (print_n_lines_after && (last_line_printed != linenum)) {
163                         print_line(line, linenum, '-');
164                         print_n_lines_after--;
165                 }
166 #endif /* BB_FEATURE_GREP_CONTEXT */ 
167                 free(line);
168         }
169
170
171         /* special-case file post-processing for options where we don't print line
172          * matches, just filenames and possibly match counts */
173
174         /* grep -c: print [filename:]count, even if count is zero */
175         if (print_match_counts) {
176                 if (print_filename)
177                         printf("%s:", cur_file);
178                 printf("%d\n", nmatches);
179         }
180
181         /* grep -l: print just the filename, but only if we grepped the line in the file  */
182         if (print_files_with_matches && nmatches > 0) {
183                 puts(cur_file);
184         }
185
186
187         /* remember if we matched */
188         if (nmatches != 0)
189                 matched = 1;
190 }
191
192 extern int grep_main(int argc, char **argv)
193 {
194         int opt;
195         int reflags;
196 #ifdef BB_FEATURE_GREP_CONTEXT
197         char *junk;
198 #endif
199
200         /* do normal option parsing */
201         while ((opt = getopt(argc, argv, "iHhlnqvsc"
202 #ifdef BB_FEATURE_GREP_CONTEXT
203 "A:B:C:"
204 #endif
205 )) > 0) {
206                 switch (opt) {
207                         case 'i':
208                                 ignore_case++;
209                                 break;
210                         case 'l':
211                                 print_files_with_matches++;
212                                 break;
213                         case 'H':
214                                 print_filename++;
215                                 break;
216                         case 'h':
217                                 print_filename--;
218                                 break;
219                         case 'n':
220                                 print_line_num++;
221                                 break;
222                         case 'q':
223                                 be_quiet++;
224                                 break;
225                         case 'v':
226                                 invert_search++;
227                                 break;
228                         case 's':
229                                 suppress_err_msgs++;
230                                 break;
231                         case 'c':
232                                 print_match_counts++;
233                                 break;
234 #ifdef BB_FEATURE_GREP_CONTEXT
235                         case 'A':
236                                 lines_after = strtoul(optarg, &junk, 10);
237                                 if(*junk != '\0')
238                                         error_msg_and_die("invalid context length argument");
239                                 break;
240                         case 'B':
241                                 lines_before = strtoul(optarg, &junk, 10);
242                                 if(*junk != '\0')
243                                         error_msg_and_die("invalid context length argument");
244                                 before_buf = (char **)calloc(lines_before, sizeof(char *));
245                                 break;
246                         case 'C':
247                                 lines_after = lines_before = strtoul(optarg, &junk, 10);
248                                 if(*junk != '\0')
249                                         error_msg_and_die("invalid context length argument");
250                                 before_buf = (char **)calloc(lines_before, sizeof(char *));
251                                 break;
252 #endif /* BB_FEATURE_GREP_CONTEXT */
253                         default:
254                                 show_usage();
255                 }
256         }
257
258         /* argv[optind] should be the regex pattern; no pattern, no worky */
259         if (argv[optind] == NULL)
260                 show_usage();
261
262         /* sanity check */
263         if (print_match_counts || be_quiet || print_files_with_matches) {
264                 print_line_num = 0;
265 #ifdef BB_FEATURE_GREP_CONTEXT
266                 lines_before = 0;
267                 lines_after = 0;
268 #endif
269         }
270
271         /* compile the regular expression
272          * we're not going to mess with sub-expressions, and we need to
273          * treat newlines right. */
274         reflags = REG_NOSUB; 
275         if (ignore_case)
276                 reflags |= REG_ICASE;
277         xregcomp(&regex, argv[optind], reflags);
278
279         /* argv[(optind+1)..(argc-1)] should be names of file to grep through. If
280          * there is more than one file to grep, we will print the filenames */
281         if ((argc-1) - (optind+1) > 0)
282                 print_filename++;
283
284         /* If no files were specified, or '-' was specified, take input from
285          * stdin. Otherwise, we grep through all the files specified. */
286         if (argv[optind+1] == NULL || (strcmp(argv[optind+1], "-") == 0)) {
287                 grep_file(stdin);
288         }
289         else {
290                 int i;
291                 FILE *file;
292                 for (i = optind + 1; i < argc; i++) {
293                         cur_file = argv[i];
294                         file = fopen(cur_file, "r");
295                         if (file == NULL) {
296                                 if (!suppress_err_msgs)
297                                         perror_msg("%s", cur_file);
298                         }
299                         else {
300                                 grep_file(file);
301                                 fclose(file);
302                         }
303                 }
304         }
305
306         regfree(&regex);
307
308         return !matched; /* invert return value 0 = success, 1 = failed */
309 }