OSDN Git Service

Merge remote-tracking branch 'toybox/master' into HEAD
[android-x86/external-toybox.git] / toys / posix / grep.c
index 2837cc2..9e50a7c 100644 (file)
@@ -3,16 +3,18 @@
  * Copyright 2013 CE Strake <strake888 at gmail.com>
  *
  * See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/grep.html
+ *
+ * TODO: -ABC
 
-USE_GREP(NEWTOY(grep, "A#B#C#ZzEFHabhinorsvwclqe*f*m#x[!wx][!EFw]", TOYFLAG_BIN))
-USE_GREP(OLDTOY(egrep, grep, OPTSTR_grep, TOYFLAG_BIN))
-USE_GREP(OLDTOY(fgrep, grep, OPTSTR_grep, TOYFLAG_BIN))
+USE_GREP(NEWTOY(grep, "C#B#A#ZzEFHabhinorsvwclqe*f*m#x[!wx][!EFw]", TOYFLAG_BIN))
+USE_EGREP(OLDTOY(egrep, grep, TOYFLAG_BIN))
+USE_FGREP(OLDTOY(fgrep, grep, TOYFLAG_BIN))
 
 config GREP
   bool "grep"
   default y
   help
-    usage: grep [-EFivwcloqsHbhn] [-m MAX] [-e REGEX]... [-f REGFILE] [FILE]...
+    usage: grep [-EFivwcloqsHbhn] [-A NUM] [-m MAX] [-e REGEX]... [-f REGFILE] [FILE]...
 
     Show lines matching regular expressions. If no -e, first argument is
     regular expression to match. With no files (or "-" filename) read stdin.
@@ -22,11 +24,12 @@ config GREP
     -f  File containing regular expressions to match.
 
     match type:
-    -E  extended regex syntax    -F  fixed (match literal string)
-    -i  case insensitive         -m  stop after this many lines matched
-    -r  recursive (on dir)       -v  invert match
-    -w  whole word (implies -E)  -x  whole line
-    -z  input NUL terminated
+    -A  Show NUM lines after     -B  Show NUM lines before match
+    -C  NUM lines context (A+B)  -E  extended regex syntax
+    -F  fixed (literal match)    -i  case insensitive
+    -m  match MAX many lines     -r  recursive (on dir)
+    -v  invert match             -w  whole word (implies -E)
+    -x  whole line               -z  input NUL terminated
 
     display modes: (default: matched line)
     -c  count of matching lines  -l  show matching filenames
@@ -36,6 +39,16 @@ config GREP
     output prefix (default: filename if checking more than 1 file)
     -H  force filename           -b  byte offset of match
     -h  hide filename            -n  line number of match
+
+config EGREP
+  bool
+  default y
+  depends on GREP
+
+config FGREP
+  bool
+  default y
+  depends on GREP
 */
 
 #define FOR_grep
@@ -46,69 +59,58 @@ GLOBALS(
   long m;
   struct arg_list *f;
   struct arg_list *e;
-  long C;
-  long B;
-  long A;
+  long a;
+  long b;
+  long c;
 
-  struct arg_list *regex;
-  struct double_list *blist;
+  char indelim, outdelim;
 )
 
-struct dlist_off {
-  char *next, *prev;
-  long offset;
-  char *data;
-};
+// Emit line with various potential prefixes and delimiter
+static void outline(char *line, char dash, char *name, long lcount, long bcount,
+  int trim)
+{
+  if (name && (toys.optflags&FLAG_H)) printf("%s%c", name, dash);
+  if (!line || (lcount && (toys.optflags&FLAG_n)))
+    printf("%ld%c", lcount, line ? dash : TT.outdelim);
+  if (bcount && (toys.optflags&FLAG_b)) printf("%ld%c", bcount-1, dash);
+  if (line) xprintf("%.*s%c", trim, line, TT.outdelim);
+}
 
+// Show matches in one file
 static void do_grep(int fd, char *name)
 {
+  struct double_list *dlb = 0;
   FILE *file = fdopen(fd, "r");
-  long offset = 0;
-  int lcount = 0, mcount = 0, which = toys.optflags & FLAG_w ? 2 : 0,
-      blines = 0, alines = 0, dash = 0;
-  char indelim = '\n' * !(toys.optflags&FLAG_z),
-       outdelim = '\n' * !(toys.optflags&FLAG_Z);
+  long lcount = 0, mcount = 0, offset = 0, after = 0, before = 0;
+  char *bars = 0;
 
   if (!fd) name = "(standard input)";
 
-fprintf(stderr, "boo\n");
   if (!file) {
-    perror_msg("%s", name);
+    perror_msg_raw(name);
     return;
   }
 
   // Loop through lines of input
   for (;;) {
-    char *oline = 0, *line = 0, *start;
-    regmatch_t matches[3];
+    char *line = 0, *start;
+    regmatch_t matches;
     size_t unused;
     long len;
     int mmatch = 0;
 
-    // Read next line of input
     lcount++;
-    if (0 > (len = getdelim(&line, &unused, indelim, file))) break;
-    if (line[len-1] == indelim) line[len-1] = 0;
-fprintf(stderr, "line=%s\n", line);
-    // Unconditionally add line to blist so output can always just dump blist.
-    dlist_add(&TT.blist, line);
-fprintf(stderr, "added=%s\n", TT.blist->data);
-fprintf(stderr, "prev=%s\n", TT.blist->prev->data);
-    if (blines <= TT.B) blines++;
-    else {
-      struct double_list *temp = dlist_pop(&TT.blist);
-fprintf(stderr, "bird=%s\n", temp->data);
-      free(temp->data);
-      free(temp);
-    }
+    if (0 > (len = getdelim(&line, &unused, TT.indelim, file))) break;
+    if (line[len-1] == TT.indelim) line[len-1] = 0;
 
     start = line;
 
-    // Loop to match multiple times within the same line (if necessary)
-    for (;;) {
-fprintf(stderr, "match?\n");
+    // Loop through matches in this line
+    do {
       int rc = 0, skip = 0;
 
+      // Handle non-regex matches
       if (toys.optflags & FLAG_F) {
         struct arg_list *seek, fseek;
         char *s = 0;
@@ -123,114 +125,130 @@ fprintf(stderr, "match?\n");
             fseek.arg = s = line;
             break;
           }
-          if (toys.optflags & FLAG_i) {
-            long ll = strlen(seek->arg);;
-
-            // Alas, posix hasn't got strcasestr()
-            for (s = line; *s; s++) if (!strncasecmp(s, seek->arg, ll)) break;
-            if (!*s) s = 0;
-          } else s = strstr(line, seek->arg);
+          if (toys.optflags & FLAG_i) s = strnstr(line, seek->arg);
+          else s = strstr(line, seek->arg);
           if (s) break;
         }
 
         if (s) {
-          matches[which].rm_so = (s-line);
-          skip = matches[which].rm_eo = (s-line)+strlen(seek->arg);
+          matches.rm_so = (s-line);
+          skip = matches.rm_eo = (s-line)+strlen(seek->arg);
         } else rc = 1;
       } else {
-        rc = regexec((regex_t *)toybuf, start, 3, matches,
+        rc = regexec((regex_t *)toybuf, start, 1, &matches,
                      start==line ? 0 : REG_NOTBOL);
-        skip = matches[which].rm_eo;
+        skip = matches.rm_eo;
       }
 
       if (toys.optflags & FLAG_x)
-        if (matches[which].rm_so || line[matches[which].rm_eo]) rc = 1;
+        if (matches.rm_so || line[matches.rm_eo]) rc = 1;
+
+      if (!rc && (toys.optflags & FLAG_w)) {
+        char c = 0;
+
+        if ((start+matches.rm_so)!=line) {
+          c = start[matches.rm_so-1];
+          if (!isalnum(c) && c != '_') c = 0;
+        }
+        if (!c) {
+          c = start[matches.rm_eo];
+          if (!isalnum(c) && c != '_') c = 0;
+        }
+        if (c) {
+          start += matches.rm_so+1;
+
+          continue;
+        }
+      }
 
       if (toys.optflags & FLAG_v) {
         if (toys.optflags & FLAG_o) {
-          if (rc) skip = matches[which].rm_eo = strlen(start);
-          else if (!matches[which].rm_so) {
+          if (rc) skip = matches.rm_eo = strlen(start);
+          else if (!matches.rm_so) {
             start += skip;
             continue;
-          } else matches[which].rm_eo = matches[which].rm_so;
+          } else matches.rm_eo = matches.rm_so;
         } else {
           if (!rc) break;
-          matches[which].rm_eo = strlen(start);
+          matches.rm_eo = strlen(start);
         }
-        matches[which].rm_so = 0;
+        matches.rm_so = 0;
       } else if (rc) break;
-fprintf(stderr, "got match %s\n", line);
-      // We got a match, figure out how to display it
+
+      // At least one line we didn't print since match while -ABC active
+      if (bars) {
+        xputs(bars);
+        bars = 0;
+      }
       mmatch++;
       toys.exitval = 0;
       if (toys.optflags & FLAG_q) xexit();
       if (toys.optflags & FLAG_l) {
-        printf("%s%c", name, outdelim);
-        goto finish;
+        xprintf("%s%c", name, TT.outdelim);
+        free(line);
+        fclose(file);
+        return;
       }
-
-      line = 0;
-fprintf(stderr, "here=%s\n", TT.blist->prev->data);
-      // Yes, -o sometimes counts things as a match (-c) but doesn't display it
       if (toys.optflags & FLAG_o)
-        if (matches[which].rm_eo == matches[which].rm_so)
+        if (matches.rm_eo == matches.rm_so)
           break;
 
-// List of lines that DIDN'T match, print backlog?
-// Except this includes the one we just matched...?
-      while (TT.blist) {
-        struct double_list *dlist = dlist_pop(&TT.blist);
-        char *ll = dlist->data;
-fprintf(stderr, "popped %s\n", ll);
-        if (dash) printf("--%c", outdelim);
-        dash = 0;
-
-        if (!(toys.optflags & FLAG_c)) {
-          if (toys.optflags & FLAG_H) printf("%s:", name);
-          if (toys.optflags & FLAG_n) printf("%d:", lcount);
-          if (toys.optflags & FLAG_b)
-            printf("%ld:", offset + (start - dlist->data) +
-                ((toys.optflags & FLAG_o) ? matches[which].rm_so : 0));
-          if (!(toys.optflags & FLAG_o)) xprintf("%s%c", dlist->data, outdelim);
-          else if (!TT.blist) {
-
-// TODO: FLAG_o prints multiple times, can't free it yet?
-            xprintf("%.*s%c", matches[which].rm_eo - matches[which].rm_so,
-                    start + matches[which].rm_so, outdelim);
-            line = dlist->data;
+      if (!(toys.optflags & FLAG_c)) {
+        long bcount = 1 + offset + (start-line) +
+          ((toys.optflags & FLAG_o) ? matches.rm_so : 0);
+        if (!(toys.optflags & FLAG_o)) {
+          while (dlb) {
+            struct double_list *dl = dlist_pop(&dlb);
+
+            outline(dl->data, '-', name, lcount-before, 0, -1);
+            free(dl->data);
+            free(dl);
+            before--;
           }
-        }
-        if (oline && !TT.blist) TT.blist = dlist;
-        else {
-          free(dlist->data);
-          free(dlist);
-        }
+
+          outline(line, ':', name, lcount, bcount, -1);
+          if (TT.a) after = TT.a+1;
+        } else outline(start+matches.rm_so, ':', name, lcount, bcount,
+                       matches.rm_eo-matches.rm_so);
       }
 
       start += skip;
-      if (!(toys.optflags & FLAG_o) || !*start) break;
-    }
+      if (!(toys.optflags & FLAG_o)) break;
+    } while (*start);
     offset += len;
-fprintf(stderr, "Spacious skies\n");
-    free(line);
 
     if (mmatch) mcount++;
-    if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
-  }
-
-  if (toys.optflags & FLAG_c) {
-    if (toys.optflags & FLAG_H) printf("%s:", name);
-    xprintf("%d%c", mcount, outdelim);
-  }
+    else {
+      int discard = (after || TT.b);
 
-finish:
-  while (CFG_TOYBOX_FREE && TT.blist) {
-    struct double_list *dlist = dlist_pop(&TT.blist);
+      if (after && --after) {
+        outline(line, '-', name, lcount, 0, -1);
+        discard = 0;
+      }
+      if (discard && TT.b) {
+        dlist_add(&dlb, line);
+        line = 0;
+        if (++before>TT.b) {
+          struct double_list *dl;
+
+          dl = dlist_pop(&dlb);
+          free(dl->data);
+          free(dl);
+          before--;
+        } else discard = 0;
+      }
+      // If we discarded a line while displaying context, show bars before next
+      // line (but don't show them now in case that was last match in file)
+      if (discard && mcount) bars = "--";
+    }
+    free(line);
 
-    free(dlist->data);
-    free(dlist);
+    if ((toys.optflags & FLAG_m) && mcount >= TT.m) break;
   }
 
+  if (toys.optflags & FLAG_c) outline(0, ':', name, mcount, 0, -1);
+
   // loopfiles will also close the fd, but this frees an (opaque) struct.
   fclose(file);
 }
@@ -248,6 +266,7 @@ static void parse_regex(void)
     if (TT.f) s = ss = xreadfile(al->arg, 0, 0);
     else s = ss = al->arg;
 
+    // Split lines at \n, add individual lines to new list.
     do {
       ss = strchr(s, '\n');
       if (ss) *(ss++) = 0;
@@ -257,6 +276,8 @@ static void parse_regex(void)
       list = new;
       s = ss;
     } while (ss && *s);
+
+    // Advance, when we run out of -f switch to -e.
     al = al->next;
     if (!al && TT.f) {
       TT.f = 0;
@@ -266,30 +287,27 @@ static void parse_regex(void)
   TT.e = list;
 
   if (!(toys.optflags & FLAG_F)) {
-    int w = toys.optflags & FLAG_w;
     char *regstr;
+    int i;
 
     // Convert strings to one big regex
-    if (w) len = 36;
     for (al = TT.e; al; al = al->next)
       len += strlen(al->arg)+1+!(toys.optflags & FLAG_E);
 
     regstr = s = xmalloc(len);
-    if (w) s = stpcpy(s, "(^|[^_[:alnum:]])(");
     for (al = TT.e; al; al = al->next) {
       s = stpcpy(s, al->arg);
       if (!(toys.optflags & FLAG_E)) *(s++) = '\\';
       *(s++) = '|';
     }
     *(s-=(1+!(toys.optflags & FLAG_E))) = 0;
-    if (w) strcpy(s, ")($|[^_[:alnum:]])");
 
-    w = regcomp((regex_t *)toybuf, regstr,
+    i = regcomp((regex_t *)toybuf, regstr,
                 ((toys.optflags & FLAG_E) ? REG_EXTENDED : 0) |
                 ((toys.optflags & FLAG_i) ? REG_ICASE    : 0));
 
-    if (w) {
-      regerror(w, (regex_t *)toybuf, toybuf+sizeof(regex_t),
+    if (i) {
+      regerror(i, (regex_t *)toybuf, toybuf+sizeof(regex_t),
                sizeof(toybuf)-sizeof(regex_t));
       error_exit("bad REGEX: %s", toybuf);
     }
@@ -315,24 +333,25 @@ static int do_grep_r(struct dirtree *new)
 
 void grep_main(void)
 {
-  char **ss;
+  char **ss = toys.optargs;
+
+  if (!TT.a) TT.a = TT.c;
+  if (!TT.b) TT.b = TT.c;
+
+  TT.indelim = '\n' * !(toys.optflags&FLAG_z);
+  TT.outdelim = '\n' * !(toys.optflags&FLAG_Z);
 
   // Handle egrep and fgrep
-  if (*toys.which->name == 'e' || (toys.optflags & FLAG_w))
-    toys.optflags |= FLAG_E;
+  if (*toys.which->name == 'e') toys.optflags |= FLAG_E;
   if (*toys.which->name == 'f') toys.optflags |= FLAG_F;
 
   if (!TT.e && !TT.f) {
-    if (!*toys.optargs) error_exit("no REGEX");
+    if (!*ss) error_exit("no REGEX");
     TT.e = xzalloc(sizeof(struct arg_list));
-    TT.e->arg = *(toys.optargs++);
+    TT.e->arg = *(ss++);
     toys.optc--;
   }
 
-  if (!TT.A) TT.A = TT.C;
-  if (!TT.B) TT.B = TT.C;
-  if (toys.optflags & (FLAG_l|FLAG_o)) TT.B = 0; // avoid memory leak
-
   parse_regex();
 
   if (!(toys.optflags & FLAG_h) && toys.optc>1) toys.optflags |= FLAG_H;
@@ -344,9 +363,10 @@ void grep_main(void)
   }
 
   if (toys.optflags & FLAG_r) {
-    for (ss=toys.optargs; *ss; ss++) {
+    // Iterate through -r arguments. Use "." as default if none provided.
+    for (ss = *ss ? ss : (char *[]){".", 0}; *ss; ss++) {
       if (!strcmp(*ss, "-")) do_grep(0, *ss);
       else dirtree_read(*ss, do_grep_r);
     }
-  } else loopfiles_rw(toys.optargs, O_RDONLY, 0, 1, do_grep);
+  } else loopfiles_rw(ss, O_RDONLY, 0, 1, do_grep);
 }