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