builtin-grep.con commit upload-pack: minor clean-up in multi-ack logic (c04c4e5)
   1/*
   2 * Builtin "git grep"
   3 *
   4 * Copyright (c) 2006 Junio C Hamano
   5 */
   6#include "cache.h"
   7#include "blob.h"
   8#include "tree.h"
   9#include "commit.h"
  10#include "tag.h"
  11#include "tree-walk.h"
  12#include "builtin.h"
  13#include <regex.h>
  14#include <fnmatch.h>
  15#include <sys/wait.h>
  16
  17/*
  18 * git grep pathspecs are somewhat different from diff-tree pathspecs;
  19 * pathname wildcards are allowed.
  20 */
  21static int pathspec_matches(const char **paths, const char *name)
  22{
  23        int namelen, i;
  24        if (!paths || !*paths)
  25                return 1;
  26        namelen = strlen(name);
  27        for (i = 0; paths[i]; i++) {
  28                const char *match = paths[i];
  29                int matchlen = strlen(match);
  30                const char *cp, *meta;
  31
  32                if (!matchlen ||
  33                    ((matchlen <= namelen) &&
  34                     !strncmp(name, match, matchlen) &&
  35                     (match[matchlen-1] == '/' ||
  36                      name[matchlen] == '\0' || name[matchlen] == '/')))
  37                        return 1;
  38                if (!fnmatch(match, name, 0))
  39                        return 1;
  40                if (name[namelen-1] != '/')
  41                        continue;
  42
  43                /* We are being asked if the directory ("name") is worth
  44                 * descending into.
  45                 *
  46                 * Find the longest leading directory name that does
  47                 * not have metacharacter in the pathspec; the name
  48                 * we are looking at must overlap with that directory.
  49                 */
  50                for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
  51                        char ch = *cp;
  52                        if (ch == '*' || ch == '[' || ch == '?') {
  53                                meta = cp;
  54                                break;
  55                        }
  56                }
  57                if (!meta)
  58                        meta = cp; /* fully literal */
  59
  60                if (namelen <= meta - match) {
  61                        /* Looking at "Documentation/" and
  62                         * the pattern says "Documentation/howto/", or
  63                         * "Documentation/diff*.txt".  The name we
  64                         * have should match prefix.
  65                         */
  66                        if (!memcmp(match, name, namelen))
  67                                return 1;
  68                        continue;
  69                }
  70
  71                if (meta - match < namelen) {
  72                        /* Looking at "Documentation/howto/" and
  73                         * the pattern says "Documentation/h*";
  74                         * match up to "Do.../h"; this avoids descending
  75                         * into "Documentation/technical/".
  76                         */
  77                        if (!memcmp(match, name, meta - match))
  78                                return 1;
  79                        continue;
  80                }
  81        }
  82        return 0;
  83}
  84
  85enum grep_pat_token {
  86        GREP_PATTERN,
  87        GREP_AND,
  88        GREP_OPEN_PAREN,
  89        GREP_CLOSE_PAREN,
  90        GREP_NOT,
  91        GREP_OR,
  92};
  93
  94struct grep_pat {
  95        struct grep_pat *next;
  96        const char *origin;
  97        int no;
  98        enum grep_pat_token token;
  99        const char *pattern;
 100        regex_t regexp;
 101};
 102
 103enum grep_expr_node {
 104        GREP_NODE_ATOM,
 105        GREP_NODE_NOT,
 106        GREP_NODE_AND,
 107        GREP_NODE_OR,
 108};
 109
 110struct grep_expr {
 111        enum grep_expr_node node;
 112        union {
 113                struct grep_pat *atom;
 114                struct grep_expr *unary;
 115                struct {
 116                        struct grep_expr *left;
 117                        struct grep_expr *right;
 118                } binary;
 119        } u;
 120};
 121
 122struct grep_opt {
 123        struct grep_pat *pattern_list;
 124        struct grep_pat **pattern_tail;
 125        struct grep_expr *pattern_expression;
 126        int prefix_length;
 127        regex_t regexp;
 128        unsigned linenum:1;
 129        unsigned invert:1;
 130        unsigned name_only:1;
 131        unsigned unmatch_name_only:1;
 132        unsigned count:1;
 133        unsigned word_regexp:1;
 134        unsigned fixed:1;
 135#define GREP_BINARY_DEFAULT     0
 136#define GREP_BINARY_NOMATCH     1
 137#define GREP_BINARY_TEXT        2
 138        unsigned binary:2;
 139        unsigned extended:1;
 140        unsigned relative:1;
 141        int regflags;
 142        unsigned pre_context;
 143        unsigned post_context;
 144};
 145
 146static void add_pattern(struct grep_opt *opt, const char *pat,
 147                        const char *origin, int no, enum grep_pat_token t)
 148{
 149        struct grep_pat *p = xcalloc(1, sizeof(*p));
 150        p->pattern = pat;
 151        p->origin = origin;
 152        p->no = no;
 153        p->token = t;
 154        *opt->pattern_tail = p;
 155        opt->pattern_tail = &p->next;
 156        p->next = NULL;
 157}
 158
 159static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
 160{
 161        int err = regcomp(&p->regexp, p->pattern, opt->regflags);
 162        if (err) {
 163                char errbuf[1024];
 164                char where[1024];
 165                if (p->no)
 166                        sprintf(where, "In '%s' at %d, ",
 167                                p->origin, p->no);
 168                else if (p->origin)
 169                        sprintf(where, "%s, ", p->origin);
 170                else
 171                        where[0] = 0;
 172                regerror(err, &p->regexp, errbuf, 1024);
 173                regfree(&p->regexp);
 174                die("%s'%s': %s", where, p->pattern, errbuf);
 175        }
 176}
 177
 178#if DEBUG
 179static inline void indent(int in)
 180{
 181        int i;
 182        for (i = 0; i < in; i++) putchar(' ');
 183}
 184
 185static void dump_pattern_exp(struct grep_expr *x, int in)
 186{
 187        switch (x->node) {
 188        case GREP_NODE_ATOM:
 189                indent(in);
 190                puts(x->u.atom->pattern);
 191                break;
 192        case GREP_NODE_NOT:
 193                indent(in);
 194                puts("--not");
 195                dump_pattern_exp(x->u.unary, in+1);
 196                break;
 197        case GREP_NODE_AND:
 198                dump_pattern_exp(x->u.binary.left, in+1);
 199                indent(in);
 200                puts("--and");
 201                dump_pattern_exp(x->u.binary.right, in+1);
 202                break;
 203        case GREP_NODE_OR:
 204                dump_pattern_exp(x->u.binary.left, in+1);
 205                indent(in);
 206                puts("--or");
 207                dump_pattern_exp(x->u.binary.right, in+1);
 208                break;
 209        }
 210}
 211
 212static void looking_at(const char *msg, struct grep_pat **list)
 213{
 214        struct grep_pat *p = *list;
 215        fprintf(stderr, "%s: looking at ", msg);
 216        if (!p)
 217                fprintf(stderr, "empty\n");
 218        else
 219                fprintf(stderr, "<%s>\n", p->pattern);
 220}
 221#else
 222#define looking_at(a,b) do {} while(0)
 223#endif
 224
 225static struct grep_expr *compile_pattern_expr(struct grep_pat **);
 226static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
 227{
 228        struct grep_pat *p;
 229        struct grep_expr *x;
 230
 231        looking_at("atom", list);
 232
 233        p = *list;
 234        switch (p->token) {
 235        case GREP_PATTERN: /* atom */
 236                x = xcalloc(1, sizeof (struct grep_expr));
 237                x->node = GREP_NODE_ATOM;
 238                x->u.atom = p;
 239                *list = p->next;
 240                return x;
 241        case GREP_OPEN_PAREN:
 242                *list = p->next;
 243                x = compile_pattern_expr(list);
 244                if (!x)
 245                        return NULL;
 246                if (!*list || (*list)->token != GREP_CLOSE_PAREN)
 247                        die("unmatched parenthesis");
 248                *list = (*list)->next;
 249                return x;
 250        default:
 251                return NULL;
 252        }
 253}
 254
 255static struct grep_expr *compile_pattern_not(struct grep_pat **list)
 256{
 257        struct grep_pat *p;
 258        struct grep_expr *x;
 259
 260        looking_at("not", list);
 261
 262        p = *list;
 263        switch (p->token) {
 264        case GREP_NOT:
 265                if (!p->next)
 266                        die("--not not followed by pattern expression");
 267                *list = p->next;
 268                x = xcalloc(1, sizeof (struct grep_expr));
 269                x->node = GREP_NODE_NOT;
 270                x->u.unary = compile_pattern_not(list);
 271                if (!x->u.unary)
 272                        die("--not followed by non pattern expression");
 273                return x;
 274        default:
 275                return compile_pattern_atom(list);
 276        }
 277}
 278
 279static struct grep_expr *compile_pattern_and(struct grep_pat **list)
 280{
 281        struct grep_pat *p;
 282        struct grep_expr *x, *y, *z;
 283
 284        looking_at("and", list);
 285
 286        x = compile_pattern_not(list);
 287        p = *list;
 288        if (p && p->token == GREP_AND) {
 289                if (!p->next)
 290                        die("--and not followed by pattern expression");
 291                *list = p->next;
 292                y = compile_pattern_and(list);
 293                if (!y)
 294                        die("--and not followed by pattern expression");
 295                z = xcalloc(1, sizeof (struct grep_expr));
 296                z->node = GREP_NODE_AND;
 297                z->u.binary.left = x;
 298                z->u.binary.right = y;
 299                return z;
 300        }
 301        return x;
 302}
 303
 304static struct grep_expr *compile_pattern_or(struct grep_pat **list)
 305{
 306        struct grep_pat *p;
 307        struct grep_expr *x, *y, *z;
 308
 309        looking_at("or", list);
 310
 311        x = compile_pattern_and(list);
 312        p = *list;
 313        if (x && p && p->token != GREP_CLOSE_PAREN) {
 314                y = compile_pattern_or(list);
 315                if (!y)
 316                        die("not a pattern expression %s", p->pattern);
 317                z = xcalloc(1, sizeof (struct grep_expr));
 318                z->node = GREP_NODE_OR;
 319                z->u.binary.left = x;
 320                z->u.binary.right = y;
 321                return z;
 322        }
 323        return x;
 324}
 325
 326static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
 327{
 328        looking_at("expr", list);
 329
 330        return compile_pattern_or(list);
 331}
 332
 333static void compile_patterns(struct grep_opt *opt)
 334{
 335        struct grep_pat *p;
 336
 337        /* First compile regexps */
 338        for (p = opt->pattern_list; p; p = p->next) {
 339                if (p->token == GREP_PATTERN)
 340                        compile_regexp(p, opt);
 341                else
 342                        opt->extended = 1;
 343        }
 344
 345        if (!opt->extended)
 346                return;
 347
 348        /* Then bundle them up in an expression.
 349         * A classic recursive descent parser would do.
 350         */
 351        p = opt->pattern_list;
 352        opt->pattern_expression = compile_pattern_expr(&p);
 353#if DEBUG
 354        dump_pattern_exp(opt->pattern_expression, 0);
 355#endif
 356        if (p)
 357                die("incomplete pattern expression: %s", p->pattern);
 358}
 359
 360static char *end_of_line(char *cp, unsigned long *left)
 361{
 362        unsigned long l = *left;
 363        while (l && *cp != '\n') {
 364                l--;
 365                cp++;
 366        }
 367        *left = l;
 368        return cp;
 369}
 370
 371static int word_char(char ch)
 372{
 373        return isalnum(ch) || ch == '_';
 374}
 375
 376static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
 377                      const char *name, unsigned lno, char sign)
 378{
 379        printf("%s%c", name, sign);
 380        if (opt->linenum)
 381                printf("%d%c", lno, sign);
 382        printf("%.*s\n", (int)(eol-bol), bol);
 383}
 384
 385/*
 386 * NEEDSWORK: share code with diff.c
 387 */
 388#define FIRST_FEW_BYTES 8000
 389static int buffer_is_binary(const char *ptr, unsigned long size)
 390{
 391        if (FIRST_FEW_BYTES < size)
 392                size = FIRST_FEW_BYTES;
 393        if (memchr(ptr, 0, size))
 394                return 1;
 395        return 0;
 396}
 397
 398static int fixmatch(const char *pattern, char *line, regmatch_t *match)
 399{
 400        char *hit = strstr(line, pattern);
 401        if (!hit) {
 402                match->rm_so = match->rm_eo = -1;
 403                return REG_NOMATCH;
 404        }
 405        else {
 406                match->rm_so = hit - line;
 407                match->rm_eo = match->rm_so + strlen(pattern);
 408                return 0;
 409        }
 410}
 411
 412static int match_one_pattern(struct grep_opt *opt, struct grep_pat *p, char *bol, char *eol)
 413{
 414        int hit = 0;
 415        int at_true_bol = 1;
 416        regmatch_t pmatch[10];
 417
 418 again:
 419        if (!opt->fixed) {
 420                regex_t *exp = &p->regexp;
 421                hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
 422                               pmatch, 0);
 423        }
 424        else {
 425                hit = !fixmatch(p->pattern, bol, pmatch);
 426        }
 427
 428        if (hit && opt->word_regexp) {
 429                if ((pmatch[0].rm_so < 0) ||
 430                    (eol - bol) <= pmatch[0].rm_so ||
 431                    (pmatch[0].rm_eo < 0) ||
 432                    (eol - bol) < pmatch[0].rm_eo)
 433                        die("regexp returned nonsense");
 434
 435                /* Match beginning must be either beginning of the
 436                 * line, or at word boundary (i.e. the last char must
 437                 * not be a word char).  Similarly, match end must be
 438                 * either end of the line, or at word boundary
 439                 * (i.e. the next char must not be a word char).
 440                 */
 441                if ( ((pmatch[0].rm_so == 0 && at_true_bol) ||
 442                      !word_char(bol[pmatch[0].rm_so-1])) &&
 443                     ((pmatch[0].rm_eo == (eol-bol)) ||
 444                      !word_char(bol[pmatch[0].rm_eo])) )
 445                        ;
 446                else
 447                        hit = 0;
 448
 449                if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
 450                        /* There could be more than one match on the
 451                         * line, and the first match might not be
 452                         * strict word match.  But later ones could be!
 453                         */
 454                        bol = pmatch[0].rm_so + bol + 1;
 455                        at_true_bol = 0;
 456                        goto again;
 457                }
 458        }
 459        return hit;
 460}
 461
 462static int match_expr_eval(struct grep_opt *opt,
 463                           struct grep_expr *x,
 464                           char *bol, char *eol)
 465{
 466        switch (x->node) {
 467        case GREP_NODE_ATOM:
 468                return match_one_pattern(opt, x->u.atom, bol, eol);
 469                break;
 470        case GREP_NODE_NOT:
 471                return !match_expr_eval(opt, x->u.unary, bol, eol);
 472        case GREP_NODE_AND:
 473                return (match_expr_eval(opt, x->u.binary.left, bol, eol) &&
 474                        match_expr_eval(opt, x->u.binary.right, bol, eol));
 475        case GREP_NODE_OR:
 476                return (match_expr_eval(opt, x->u.binary.left, bol, eol) ||
 477                        match_expr_eval(opt, x->u.binary.right, bol, eol));
 478        }
 479        die("Unexpected node type (internal error) %d\n", x->node);
 480}
 481
 482static int match_expr(struct grep_opt *opt, char *bol, char *eol)
 483{
 484        struct grep_expr *x = opt->pattern_expression;
 485        return match_expr_eval(opt, x, bol, eol);
 486}
 487
 488static int match_line(struct grep_opt *opt, char *bol, char *eol)
 489{
 490        struct grep_pat *p;
 491        if (opt->extended)
 492                return match_expr(opt, bol, eol);
 493        for (p = opt->pattern_list; p; p = p->next) {
 494                if (match_one_pattern(opt, p, bol, eol))
 495                        return 1;
 496        }
 497        return 0;
 498}
 499
 500static int grep_buffer(struct grep_opt *opt, const char *name,
 501                       char *buf, unsigned long size)
 502{
 503        char *bol = buf;
 504        unsigned long left = size;
 505        unsigned lno = 1;
 506        struct pre_context_line {
 507                char *bol;
 508                char *eol;
 509        } *prev = NULL, *pcl;
 510        unsigned last_hit = 0;
 511        unsigned last_shown = 0;
 512        int binary_match_only = 0;
 513        const char *hunk_mark = "";
 514        unsigned count = 0;
 515
 516        if (buffer_is_binary(buf, size)) {
 517                switch (opt->binary) {
 518                case GREP_BINARY_DEFAULT:
 519                        binary_match_only = 1;
 520                        break;
 521                case GREP_BINARY_NOMATCH:
 522                        return 0; /* Assume unmatch */
 523                        break;
 524                default:
 525                        break;
 526                }
 527        }
 528
 529        if (opt->pre_context)
 530                prev = xcalloc(opt->pre_context, sizeof(*prev));
 531        if (opt->pre_context || opt->post_context)
 532                hunk_mark = "--\n";
 533
 534        while (left) {
 535                char *eol, ch;
 536                int hit = 0;
 537
 538                eol = end_of_line(bol, &left);
 539                ch = *eol;
 540                *eol = 0;
 541
 542                hit = match_line(opt, bol, eol);
 543
 544                /* "grep -v -e foo -e bla" should list lines
 545                 * that do not have either, so inversion should
 546                 * be done outside.
 547                 */
 548                if (opt->invert)
 549                        hit = !hit;
 550                if (opt->unmatch_name_only) {
 551                        if (hit)
 552                                return 0;
 553                        goto next_line;
 554                }
 555                if (hit) {
 556                        count++;
 557                        if (binary_match_only) {
 558                                printf("Binary file %s matches\n", name);
 559                                return 1;
 560                        }
 561                        if (opt->name_only) {
 562                                printf("%s\n", name);
 563                                return 1;
 564                        }
 565                        /* Hit at this line.  If we haven't shown the
 566                         * pre-context lines, we would need to show them.
 567                         * When asked to do "count", this still show
 568                         * the context which is nonsense, but the user
 569                         * deserves to get that ;-).
 570                         */
 571                        if (opt->pre_context) {
 572                                unsigned from;
 573                                if (opt->pre_context < lno)
 574                                        from = lno - opt->pre_context;
 575                                else
 576                                        from = 1;
 577                                if (from <= last_shown)
 578                                        from = last_shown + 1;
 579                                if (last_shown && from != last_shown + 1)
 580                                        printf(hunk_mark);
 581                                while (from < lno) {
 582                                        pcl = &prev[lno-from-1];
 583                                        show_line(opt, pcl->bol, pcl->eol,
 584                                                  name, from, '-');
 585                                        from++;
 586                                }
 587                                last_shown = lno-1;
 588                        }
 589                        if (last_shown && lno != last_shown + 1)
 590                                printf(hunk_mark);
 591                        if (!opt->count)
 592                                show_line(opt, bol, eol, name, lno, ':');
 593                        last_shown = last_hit = lno;
 594                }
 595                else if (last_hit &&
 596                         lno <= last_hit + opt->post_context) {
 597                        /* If the last hit is within the post context,
 598                         * we need to show this line.
 599                         */
 600                        if (last_shown && lno != last_shown + 1)
 601                                printf(hunk_mark);
 602                        show_line(opt, bol, eol, name, lno, '-');
 603                        last_shown = lno;
 604                }
 605                if (opt->pre_context) {
 606                        memmove(prev+1, prev,
 607                                (opt->pre_context-1) * sizeof(*prev));
 608                        prev->bol = bol;
 609                        prev->eol = eol;
 610                }
 611
 612        next_line:
 613                *eol = ch;
 614                bol = eol + 1;
 615                if (!left)
 616                        break;
 617                left--;
 618                lno++;
 619        }
 620
 621        if (opt->unmatch_name_only) {
 622                /* We did not see any hit, so we want to show this */
 623                printf("%s\n", name);
 624                return 1;
 625        }
 626
 627        /* NEEDSWORK:
 628         * The real "grep -c foo *.c" gives many "bar.c:0" lines,
 629         * which feels mostly useless but sometimes useful.  Maybe
 630         * make it another option?  For now suppress them.
 631         */
 632        if (opt->count && count)
 633                printf("%s:%u\n", name, count);
 634        return !!last_hit;
 635}
 636
 637static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
 638{
 639        unsigned long size;
 640        char *data;
 641        char type[20];
 642        char *to_free = NULL;
 643        int hit;
 644
 645        data = read_sha1_file(sha1, type, &size);
 646        if (!data) {
 647                error("'%s': unable to read %s", name, sha1_to_hex(sha1));
 648                return 0;
 649        }
 650        if (opt->relative && opt->prefix_length) {
 651                static char name_buf[PATH_MAX];
 652                char *cp;
 653                int name_len = strlen(name) - opt->prefix_length + 1;
 654
 655                if (!tree_name_len)
 656                        name += opt->prefix_length;
 657                else {
 658                        if (ARRAY_SIZE(name_buf) <= name_len)
 659                                cp = to_free = xmalloc(name_len);
 660                        else
 661                                cp = name_buf;
 662                        memcpy(cp, name, tree_name_len);
 663                        strcpy(cp + tree_name_len,
 664                               name + tree_name_len + opt->prefix_length);
 665                        name = cp;
 666                }
 667        }
 668        hit = grep_buffer(opt, name, data, size);
 669        free(data);
 670        free(to_free);
 671        return hit;
 672}
 673
 674static int grep_file(struct grep_opt *opt, const char *filename)
 675{
 676        struct stat st;
 677        int i;
 678        char *data;
 679        if (lstat(filename, &st) < 0) {
 680        err_ret:
 681                if (errno != ENOENT)
 682                        error("'%s': %s", filename, strerror(errno));
 683                return 0;
 684        }
 685        if (!st.st_size)
 686                return 0; /* empty file -- no grep hit */
 687        if (!S_ISREG(st.st_mode))
 688                return 0;
 689        i = open(filename, O_RDONLY);
 690        if (i < 0)
 691                goto err_ret;
 692        data = xmalloc(st.st_size + 1);
 693        if (st.st_size != xread(i, data, st.st_size)) {
 694                error("'%s': short read %s", filename, strerror(errno));
 695                close(i);
 696                free(data);
 697                return 0;
 698        }
 699        close(i);
 700        if (opt->relative && opt->prefix_length)
 701                filename += opt->prefix_length;
 702        i = grep_buffer(opt, filename, data, st.st_size);
 703        free(data);
 704        return i;
 705}
 706
 707static int exec_grep(int argc, const char **argv)
 708{
 709        pid_t pid;
 710        int status;
 711
 712        argv[argc] = NULL;
 713        pid = fork();
 714        if (pid < 0)
 715                return pid;
 716        if (!pid) {
 717                execvp("grep", (char **) argv);
 718                exit(255);
 719        }
 720        while (waitpid(pid, &status, 0) < 0) {
 721                if (errno == EINTR)
 722                        continue;
 723                return -1;
 724        }
 725        if (WIFEXITED(status)) {
 726                if (!WEXITSTATUS(status))
 727                        return 1;
 728                return 0;
 729        }
 730        return -1;
 731}
 732
 733#define MAXARGS 1000
 734#define ARGBUF 4096
 735#define push_arg(a) do { \
 736        if (nr < MAXARGS) argv[nr++] = (a); \
 737        else die("maximum number of args exceeded"); \
 738        } while (0)
 739
 740static int external_grep(struct grep_opt *opt, const char **paths, int cached)
 741{
 742        int i, nr, argc, hit, len, status;
 743        const char *argv[MAXARGS+1];
 744        char randarg[ARGBUF];
 745        char *argptr = randarg;
 746        struct grep_pat *p;
 747
 748        if (opt->extended || (opt->relative && opt->prefix_length))
 749                return -1;
 750        len = nr = 0;
 751        push_arg("grep");
 752        if (opt->fixed)
 753                push_arg("-F");
 754        if (opt->linenum)
 755                push_arg("-n");
 756        if (opt->regflags & REG_EXTENDED)
 757                push_arg("-E");
 758        if (opt->regflags & REG_ICASE)
 759                push_arg("-i");
 760        if (opt->word_regexp)
 761                push_arg("-w");
 762        if (opt->name_only)
 763                push_arg("-l");
 764        if (opt->unmatch_name_only)
 765                push_arg("-L");
 766        if (opt->count)
 767                push_arg("-c");
 768        if (opt->post_context || opt->pre_context) {
 769                if (opt->post_context != opt->pre_context) {
 770                        if (opt->pre_context) {
 771                                push_arg("-B");
 772                                len += snprintf(argptr, sizeof(randarg)-len,
 773                                                "%u", opt->pre_context);
 774                                if (sizeof(randarg) <= len)
 775                                        die("maximum length of args exceeded");
 776                                push_arg(argptr);
 777                                argptr += len;
 778                        }
 779                        if (opt->post_context) {
 780                                push_arg("-A");
 781                                len += snprintf(argptr, sizeof(randarg)-len,
 782                                                "%u", opt->post_context);
 783                                if (sizeof(randarg) <= len)
 784                                        die("maximum length of args exceeded");
 785                                push_arg(argptr);
 786                                argptr += len;
 787                        }
 788                }
 789                else {
 790                        push_arg("-C");
 791                        len += snprintf(argptr, sizeof(randarg)-len,
 792                                        "%u", opt->post_context);
 793                        if (sizeof(randarg) <= len)
 794                                die("maximum length of args exceeded");
 795                        push_arg(argptr);
 796                        argptr += len;
 797                }
 798        }
 799        for (p = opt->pattern_list; p; p = p->next) {
 800                push_arg("-e");
 801                push_arg(p->pattern);
 802        }
 803
 804        /*
 805         * To make sure we get the header printed out when we want it,
 806         * add /dev/null to the paths to grep.  This is unnecessary
 807         * (and wrong) with "-l" or "-L", which always print out the
 808         * name anyway.
 809         *
 810         * GNU grep has "-H", but this is portable.
 811         */
 812        if (!opt->name_only && !opt->unmatch_name_only)
 813                push_arg("/dev/null");
 814
 815        hit = 0;
 816        argc = nr;
 817        for (i = 0; i < active_nr; i++) {
 818                struct cache_entry *ce = active_cache[i];
 819                char *name;
 820                if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
 821                        continue;
 822                if (!pathspec_matches(paths, ce->name))
 823                        continue;
 824                name = ce->name;
 825                if (name[0] == '-') {
 826                        int len = ce_namelen(ce);
 827                        name = xmalloc(len + 3);
 828                        memcpy(name, "./", 2);
 829                        memcpy(name + 2, ce->name, len + 1);
 830                }
 831                argv[argc++] = name;
 832                if (argc < MAXARGS)
 833                        continue;
 834                status = exec_grep(argc, argv);
 835                if (0 < status)
 836                        hit = 1;
 837                argc = nr;
 838        }
 839        if (argc > nr) {
 840                status = exec_grep(argc, argv);
 841                if (0 < status)
 842                        hit = 1;
 843        }
 844        return hit;
 845}
 846
 847static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
 848{
 849        int hit = 0;
 850        int nr;
 851        read_cache();
 852
 853#ifdef __unix__
 854        /*
 855         * Use the external "grep" command for the case where
 856         * we grep through the checked-out files. It tends to
 857         * be a lot more optimized
 858         */
 859        if (!cached) {
 860                hit = external_grep(opt, paths, cached);
 861                if (hit >= 0)
 862                        return hit;
 863        }
 864#endif
 865
 866        for (nr = 0; nr < active_nr; nr++) {
 867                struct cache_entry *ce = active_cache[nr];
 868                if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
 869                        continue;
 870                if (!pathspec_matches(paths, ce->name))
 871                        continue;
 872                if (cached)
 873                        hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
 874                else
 875                        hit |= grep_file(opt, ce->name);
 876        }
 877        return hit;
 878}
 879
 880static int grep_tree(struct grep_opt *opt, const char **paths,
 881                     struct tree_desc *tree,
 882                     const char *tree_name, const char *base)
 883{
 884        int len;
 885        int hit = 0;
 886        struct name_entry entry;
 887        char *down;
 888        int tn_len = strlen(tree_name);
 889        char *path_buf = xmalloc(PATH_MAX + tn_len + 100);
 890
 891        if (tn_len) {
 892                tn_len = sprintf(path_buf, "%s:", tree_name);
 893                down = path_buf + tn_len;
 894                strcat(down, base);
 895        }
 896        else {
 897                down = path_buf;
 898                strcpy(down, base);
 899        }
 900        len = strlen(path_buf);
 901
 902        while (tree_entry(tree, &entry)) {
 903                strcpy(path_buf + len, entry.path);
 904
 905                if (S_ISDIR(entry.mode))
 906                        /* Match "abc/" against pathspec to
 907                         * decide if we want to descend into "abc"
 908                         * directory.
 909                         */
 910                        strcpy(path_buf + len + entry.pathlen, "/");
 911
 912                if (!pathspec_matches(paths, down))
 913                        ;
 914                else if (S_ISREG(entry.mode))
 915                        hit |= grep_sha1(opt, entry.sha1, path_buf, tn_len);
 916                else if (S_ISDIR(entry.mode)) {
 917                        char type[20];
 918                        struct tree_desc sub;
 919                        void *data;
 920                        data = read_sha1_file(entry.sha1, type, &sub.size);
 921                        if (!data)
 922                                die("unable to read tree (%s)",
 923                                    sha1_to_hex(entry.sha1));
 924                        sub.buf = data;
 925                        hit |= grep_tree(opt, paths, &sub, tree_name, down);
 926                        free(data);
 927                }
 928        }
 929        return hit;
 930}
 931
 932static int grep_object(struct grep_opt *opt, const char **paths,
 933                       struct object *obj, const char *name)
 934{
 935        if (obj->type == OBJ_BLOB)
 936                return grep_sha1(opt, obj->sha1, name, 0);
 937        if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
 938                struct tree_desc tree;
 939                void *data;
 940                int hit;
 941                data = read_object_with_reference(obj->sha1, tree_type,
 942                                                  &tree.size, NULL);
 943                if (!data)
 944                        die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
 945                tree.buf = data;
 946                hit = grep_tree(opt, paths, &tree, name, "");
 947                free(data);
 948                return hit;
 949        }
 950        die("unable to grep from object of type %s", typename(obj->type));
 951}
 952
 953static const char builtin_grep_usage[] =
 954"git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
 955
 956static const char emsg_invalid_context_len[] =
 957"%s: invalid context length argument";
 958static const char emsg_missing_context_len[] =
 959"missing context length argument";
 960static const char emsg_missing_argument[] =
 961"option requires an argument -%s";
 962
 963int cmd_grep(int argc, const char **argv, const char *prefix)
 964{
 965        int hit = 0;
 966        int cached = 0;
 967        int seen_dashdash = 0;
 968        struct grep_opt opt;
 969        struct object_array list = { 0, 0, NULL };
 970        const char **paths = NULL;
 971        int i;
 972
 973        memset(&opt, 0, sizeof(opt));
 974        opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
 975        opt.relative = 1;
 976        opt.pattern_tail = &opt.pattern_list;
 977        opt.regflags = REG_NEWLINE;
 978
 979        /*
 980         * If there is no -- then the paths must exist in the working
 981         * tree.  If there is no explicit pattern specified with -e or
 982         * -f, we take the first unrecognized non option to be the
 983         * pattern, but then what follows it must be zero or more
 984         * valid refs up to the -- (if exists), and then existing
 985         * paths.  If there is an explicit pattern, then the first
 986         * unrecognized non option is the beginning of the refs list
 987         * that continues up to the -- (if exists), and then paths.
 988         */
 989
 990        while (1 < argc) {
 991                const char *arg = argv[1];
 992                argc--; argv++;
 993                if (!strcmp("--cached", arg)) {
 994                        cached = 1;
 995                        continue;
 996                }
 997                if (!strcmp("-a", arg) ||
 998                    !strcmp("--text", arg)) {
 999                        opt.binary = GREP_BINARY_TEXT;
1000                        continue;
1001                }
1002                if (!strcmp("-i", arg) ||
1003                    !strcmp("--ignore-case", arg)) {
1004                        opt.regflags |= REG_ICASE;
1005                        continue;
1006                }
1007                if (!strcmp("-I", arg)) {
1008                        opt.binary = GREP_BINARY_NOMATCH;
1009                        continue;
1010                }
1011                if (!strcmp("-v", arg) ||
1012                    !strcmp("--invert-match", arg)) {
1013                        opt.invert = 1;
1014                        continue;
1015                }
1016                if (!strcmp("-E", arg) ||
1017                    !strcmp("--extended-regexp", arg)) {
1018                        opt.regflags |= REG_EXTENDED;
1019                        continue;
1020                }
1021                if (!strcmp("-F", arg) ||
1022                    !strcmp("--fixed-strings", arg)) {
1023                        opt.fixed = 1;
1024                        continue;
1025                }
1026                if (!strcmp("-G", arg) ||
1027                    !strcmp("--basic-regexp", arg)) {
1028                        opt.regflags &= ~REG_EXTENDED;
1029                        continue;
1030                }
1031                if (!strcmp("-n", arg)) {
1032                        opt.linenum = 1;
1033                        continue;
1034                }
1035                if (!strcmp("-H", arg)) {
1036                        /* We always show the pathname, so this
1037                         * is a noop.
1038                         */
1039                        continue;
1040                }
1041                if (!strcmp("-l", arg) ||
1042                    !strcmp("--files-with-matches", arg)) {
1043                        opt.name_only = 1;
1044                        continue;
1045                }
1046                if (!strcmp("-L", arg) ||
1047                    !strcmp("--files-without-match", arg)) {
1048                        opt.unmatch_name_only = 1;
1049                        continue;
1050                }
1051                if (!strcmp("-c", arg) ||
1052                    !strcmp("--count", arg)) {
1053                        opt.count = 1;
1054                        continue;
1055                }
1056                if (!strcmp("-w", arg) ||
1057                    !strcmp("--word-regexp", arg)) {
1058                        opt.word_regexp = 1;
1059                        continue;
1060                }
1061                if (!strncmp("-A", arg, 2) ||
1062                    !strncmp("-B", arg, 2) ||
1063                    !strncmp("-C", arg, 2) ||
1064                    (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
1065                        unsigned num;
1066                        const char *scan;
1067                        switch (arg[1]) {
1068                        case 'A': case 'B': case 'C':
1069                                if (!arg[2]) {
1070                                        if (argc <= 1)
1071                                                die(emsg_missing_context_len);
1072                                        scan = *++argv;
1073                                        argc--;
1074                                }
1075                                else
1076                                        scan = arg + 2;
1077                                break;
1078                        default:
1079                                scan = arg + 1;
1080                                break;
1081                        }
1082                        if (sscanf(scan, "%u", &num) != 1)
1083                                die(emsg_invalid_context_len, scan);
1084                        switch (arg[1]) {
1085                        case 'A':
1086                                opt.post_context = num;
1087                                break;
1088                        default:
1089                        case 'C':
1090                                opt.post_context = num;
1091                        case 'B':
1092                                opt.pre_context = num;
1093                                break;
1094                        }
1095                        continue;
1096                }
1097                if (!strcmp("-f", arg)) {
1098                        FILE *patterns;
1099                        int lno = 0;
1100                        char buf[1024];
1101                        if (argc <= 1)
1102                                die(emsg_missing_argument, arg);
1103                        patterns = fopen(argv[1], "r");
1104                        if (!patterns)
1105                                die("'%s': %s", argv[1], strerror(errno));
1106                        while (fgets(buf, sizeof(buf), patterns)) {
1107                                int len = strlen(buf);
1108                                if (buf[len-1] == '\n')
1109                                        buf[len-1] = 0;
1110                                /* ignore empty line like grep does */
1111                                if (!buf[0])
1112                                        continue;
1113                                add_pattern(&opt, strdup(buf), argv[1], ++lno,
1114                                            GREP_PATTERN);
1115                        }
1116                        fclose(patterns);
1117                        argv++;
1118                        argc--;
1119                        continue;
1120                }
1121                if (!strcmp("--not", arg)) {
1122                        add_pattern(&opt, arg, "command line", 0, GREP_NOT);
1123                        continue;
1124                }
1125                if (!strcmp("--and", arg)) {
1126                        add_pattern(&opt, arg, "command line", 0, GREP_AND);
1127                        continue;
1128                }
1129                if (!strcmp("--or", arg))
1130                        continue; /* no-op */
1131                if (!strcmp("(", arg)) {
1132                        add_pattern(&opt, arg, "command line", 0, GREP_OPEN_PAREN);
1133                        continue;
1134                }
1135                if (!strcmp(")", arg)) {
1136                        add_pattern(&opt, arg, "command line", 0, GREP_CLOSE_PAREN);
1137                        continue;
1138                }
1139                if (!strcmp("-e", arg)) {
1140                        if (1 < argc) {
1141                                add_pattern(&opt, argv[1], "-e option", 0,
1142                                            GREP_PATTERN);
1143                                argv++;
1144                                argc--;
1145                                continue;
1146                        }
1147                        die(emsg_missing_argument, arg);
1148                }
1149                if (!strcmp("--full-name", arg)) {
1150                        opt.relative = 0;
1151                        continue;
1152                }
1153                if (!strcmp("--", arg)) {
1154                        /* later processing wants to have this at argv[1] */
1155                        argv--;
1156                        argc++;
1157                        break;
1158                }
1159                if (*arg == '-')
1160                        usage(builtin_grep_usage);
1161
1162                /* First unrecognized non-option token */
1163                if (!opt.pattern_list) {
1164                        add_pattern(&opt, arg, "command line", 0,
1165                                    GREP_PATTERN);
1166                        break;
1167                }
1168                else {
1169                        /* We are looking at the first path or rev;
1170                         * it is found at argv[1] after leaving the
1171                         * loop.
1172                         */
1173                        argc++; argv--;
1174                        break;
1175                }
1176        }
1177
1178        if (!opt.pattern_list)
1179                die("no pattern given.");
1180        if ((opt.regflags != REG_NEWLINE) && opt.fixed)
1181                die("cannot mix --fixed-strings and regexp");
1182        if (!opt.fixed)
1183                compile_patterns(&opt);
1184
1185        /* Check revs and then paths */
1186        for (i = 1; i < argc; i++) {
1187                const char *arg = argv[i];
1188                unsigned char sha1[20];
1189                /* Is it a rev? */
1190                if (!get_sha1(arg, sha1)) {
1191                        struct object *object = parse_object(sha1);
1192                        if (!object)
1193                                die("bad object %s", arg);
1194                        add_object_array(object, arg, &list);
1195                        continue;
1196                }
1197                if (!strcmp(arg, "--")) {
1198                        i++;
1199                        seen_dashdash = 1;
1200                }
1201                break;
1202        }
1203
1204        /* The rest are paths */
1205        if (!seen_dashdash) {
1206                int j;
1207                for (j = i; j < argc; j++)
1208                        verify_filename(prefix, argv[j]);
1209        }
1210
1211        if (i < argc) {
1212                paths = get_pathspec(prefix, argv + i);
1213                if (opt.prefix_length && opt.relative) {
1214                        /* Make sure we do not get outside of paths */
1215                        for (i = 0; paths[i]; i++)
1216                                if (strncmp(prefix, paths[i], opt.prefix_length))
1217                                        die("git-grep: cannot generate relative filenames containing '..'");
1218                }
1219        }
1220        else if (prefix) {
1221                paths = xcalloc(2, sizeof(const char *));
1222                paths[0] = prefix;
1223                paths[1] = NULL;
1224        }
1225
1226        if (!list.nr)
1227                return !grep_cache(&opt, paths, cached);
1228
1229        if (cached)
1230                die("both --cached and trees are given.");
1231
1232        for (i = 0; i < list.nr; i++) {
1233                struct object *real_obj;
1234                real_obj = deref_tag(list.objects[i].item, NULL, 0);
1235                if (grep_object(&opt, paths, real_obj, list.objects[i].name))
1236                        hit = 1;
1237        }
1238        return !hit;
1239}