builtin-grep.con commit Misc doc improvements (74237d6)
   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 <= namelen) &&
  33                    !strncmp(name, match, matchlen) &&
  34                    (match[matchlen-1] == '/' ||
  35                     name[matchlen] == '\0' || name[matchlen] == '/'))
  36                        return 1;
  37                if (!fnmatch(match, name, 0))
  38                        return 1;
  39                if (name[namelen-1] != '/')
  40                        continue;
  41
  42                /* We are being asked if the directory ("name") is worth
  43                 * descending into.
  44                 *
  45                 * Find the longest leading directory name that does
  46                 * not have metacharacter in the pathspec; the name
  47                 * we are looking at must overlap with that directory.
  48                 */
  49                for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
  50                        char ch = *cp;
  51                        if (ch == '*' || ch == '[' || ch == '?') {
  52                                meta = cp;
  53                                break;
  54                        }
  55                }
  56                if (!meta)
  57                        meta = cp; /* fully literal */
  58
  59                if (namelen <= meta - match) {
  60                        /* Looking at "Documentation/" and
  61                         * the pattern says "Documentation/howto/", or
  62                         * "Documentation/diff*.txt".  The name we
  63                         * have should match prefix.
  64                         */
  65                        if (!memcmp(match, name, namelen))
  66                                return 1;
  67                        continue;
  68                }
  69
  70                if (meta - match < namelen) {
  71                        /* Looking at "Documentation/howto/" and
  72                         * the pattern says "Documentation/h*";
  73                         * match up to "Do.../h"; this avoids descending
  74                         * into "Documentation/technical/".
  75                         */
  76                        if (!memcmp(match, name, meta - match))
  77                                return 1;
  78                        continue;
  79                }
  80        }
  81        return 0;
  82}
  83
  84struct grep_pat {
  85        struct grep_pat *next;
  86        const char *origin;
  87        int no;
  88        const char *pattern;
  89        regex_t regexp;
  90};
  91
  92struct grep_opt {
  93        struct grep_pat *pattern_list;
  94        struct grep_pat **pattern_tail;
  95        regex_t regexp;
  96        unsigned linenum:1;
  97        unsigned invert:1;
  98        unsigned name_only:1;
  99        unsigned unmatch_name_only:1;
 100        unsigned count:1;
 101        unsigned word_regexp:1;
 102        unsigned fixed:1;
 103#define GREP_BINARY_DEFAULT     0
 104#define GREP_BINARY_NOMATCH     1
 105#define GREP_BINARY_TEXT        2
 106        unsigned binary:2;
 107        int regflags;
 108        unsigned pre_context;
 109        unsigned post_context;
 110};
 111
 112static void add_pattern(struct grep_opt *opt, const char *pat,
 113                        const char *origin, int no)
 114{
 115        struct grep_pat *p = xcalloc(1, sizeof(*p));
 116        p->pattern = pat;
 117        p->origin = origin;
 118        p->no = no;
 119        *opt->pattern_tail = p;
 120        opt->pattern_tail = &p->next;
 121        p->next = NULL;
 122}
 123
 124static void compile_patterns(struct grep_opt *opt)
 125{
 126        struct grep_pat *p;
 127        for (p = opt->pattern_list; p; p = p->next) {
 128                int err = regcomp(&p->regexp, p->pattern, opt->regflags);
 129                if (err) {
 130                        char errbuf[1024];
 131                        char where[1024];
 132                        if (p->no)
 133                                sprintf(where, "In '%s' at %d, ",
 134                                        p->origin, p->no);
 135                        else if (p->origin)
 136                                sprintf(where, "%s, ", p->origin);
 137                        else
 138                                where[0] = 0;
 139                        regerror(err, &p->regexp, errbuf, 1024);
 140                        regfree(&p->regexp);
 141                        die("%s'%s': %s", where, p->pattern, errbuf);
 142                }
 143        }
 144}
 145
 146static char *end_of_line(char *cp, unsigned long *left)
 147{
 148        unsigned long l = *left;
 149        while (l && *cp != '\n') {
 150                l--;
 151                cp++;
 152        }
 153        *left = l;
 154        return cp;
 155}
 156
 157static int word_char(char ch)
 158{
 159        return isalnum(ch) || ch == '_';
 160}
 161
 162static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
 163                      const char *name, unsigned lno, char sign)
 164{
 165        printf("%s%c", name, sign);
 166        if (opt->linenum)
 167                printf("%d%c", lno, sign);
 168        printf("%.*s\n", (int)(eol-bol), bol);
 169}
 170
 171/*
 172 * NEEDSWORK: share code with diff.c
 173 */
 174#define FIRST_FEW_BYTES 8000
 175static int buffer_is_binary(const char *ptr, unsigned long size)
 176{
 177        if (FIRST_FEW_BYTES < size)
 178                size = FIRST_FEW_BYTES;
 179        if (memchr(ptr, 0, size))
 180                return 1;
 181        return 0;
 182}
 183
 184static int fixmatch(const char *pattern, char *line, regmatch_t *match)
 185{
 186        char *hit = strstr(line, pattern);
 187        if (!hit) {
 188                match->rm_so = match->rm_eo = -1;
 189                return REG_NOMATCH;
 190        }
 191        else {
 192                match->rm_so = hit - line;
 193                match->rm_eo = match->rm_so + strlen(pattern);
 194                return 0;
 195        }
 196}
 197
 198static int grep_buffer(struct grep_opt *opt, const char *name,
 199                       char *buf, unsigned long size)
 200{
 201        char *bol = buf;
 202        unsigned long left = size;
 203        unsigned lno = 1;
 204        struct pre_context_line {
 205                char *bol;
 206                char *eol;
 207        } *prev = NULL, *pcl;
 208        unsigned last_hit = 0;
 209        unsigned last_shown = 0;
 210        int binary_match_only = 0;
 211        const char *hunk_mark = "";
 212        unsigned count = 0;
 213
 214        if (buffer_is_binary(buf, size)) {
 215                switch (opt->binary) {
 216                case GREP_BINARY_DEFAULT:
 217                        binary_match_only = 1;
 218                        break;
 219                case GREP_BINARY_NOMATCH:
 220                        return 0; /* Assume unmatch */
 221                        break;
 222                default:
 223                        break;
 224                }
 225        }
 226
 227        if (opt->pre_context)
 228                prev = xcalloc(opt->pre_context, sizeof(*prev));
 229        if (opt->pre_context || opt->post_context)
 230                hunk_mark = "--\n";
 231
 232        while (left) {
 233                regmatch_t pmatch[10];
 234                char *eol, ch;
 235                int hit = 0;
 236                struct grep_pat *p;
 237
 238                eol = end_of_line(bol, &left);
 239                ch = *eol;
 240                *eol = 0;
 241
 242                for (p = opt->pattern_list; p; p = p->next) {
 243                        if (!opt->fixed) {
 244                                regex_t *exp = &p->regexp;
 245                                hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
 246                                               pmatch, 0);
 247                        }
 248                        else {
 249                                hit = !fixmatch(p->pattern, bol, pmatch);
 250                        }
 251
 252                        if (hit && opt->word_regexp) {
 253                                /* Match beginning must be either
 254                                 * beginning of the line, or at word
 255                                 * boundary (i.e. the last char must
 256                                 * not be alnum or underscore).
 257                                 */
 258                                if ((pmatch[0].rm_so < 0) ||
 259                                    (eol - bol) <= pmatch[0].rm_so ||
 260                                    (pmatch[0].rm_eo < 0) ||
 261                                    (eol - bol) < pmatch[0].rm_eo)
 262                                        die("regexp returned nonsense");
 263                                if (pmatch[0].rm_so != 0 &&
 264                                    word_char(bol[pmatch[0].rm_so-1]))
 265                                        hit = 0;
 266                                if (pmatch[0].rm_eo != (eol-bol) &&
 267                                    word_char(bol[pmatch[0].rm_eo]))
 268                                        hit = 0;
 269                        }
 270                        if (hit)
 271                                break;
 272                }
 273                /* "grep -v -e foo -e bla" should list lines
 274                 * that do not have either, so inversion should
 275                 * be done outside.
 276                 */
 277                if (opt->invert)
 278                        hit = !hit;
 279                if (opt->unmatch_name_only) {
 280                        if (hit)
 281                                return 0;
 282                        goto next_line;
 283                }
 284                if (hit) {
 285                        count++;
 286                        if (binary_match_only) {
 287                                printf("Binary file %s matches\n", name);
 288                                return 1;
 289                        }
 290                        if (opt->name_only) {
 291                                printf("%s\n", name);
 292                                return 1;
 293                        }
 294                        /* Hit at this line.  If we haven't shown the
 295                         * pre-context lines, we would need to show them.
 296                         * When asked to do "count", this still show
 297                         * the context which is nonsense, but the user
 298                         * deserves to get that ;-).
 299                         */
 300                        if (opt->pre_context) {
 301                                unsigned from;
 302                                if (opt->pre_context < lno)
 303                                        from = lno - opt->pre_context;
 304                                else
 305                                        from = 1;
 306                                if (from <= last_shown)
 307                                        from = last_shown + 1;
 308                                if (last_shown && from != last_shown + 1)
 309                                        printf(hunk_mark);
 310                                while (from < lno) {
 311                                        pcl = &prev[lno-from-1];
 312                                        show_line(opt, pcl->bol, pcl->eol,
 313                                                  name, from, '-');
 314                                        from++;
 315                                }
 316                                last_shown = lno-1;
 317                        }
 318                        if (last_shown && lno != last_shown + 1)
 319                                printf(hunk_mark);
 320                        if (!opt->count)
 321                                show_line(opt, bol, eol, name, lno, ':');
 322                        last_shown = last_hit = lno;
 323                }
 324                else if (last_hit &&
 325                         lno <= last_hit + opt->post_context) {
 326                        /* If the last hit is within the post context,
 327                         * we need to show this line.
 328                         */
 329                        if (last_shown && lno != last_shown + 1)
 330                                printf(hunk_mark);
 331                        show_line(opt, bol, eol, name, lno, '-');
 332                        last_shown = lno;
 333                }
 334                if (opt->pre_context) {
 335                        memmove(prev+1, prev,
 336                                (opt->pre_context-1) * sizeof(*prev));
 337                        prev->bol = bol;
 338                        prev->eol = eol;
 339                }
 340
 341        next_line:
 342                *eol = ch;
 343                bol = eol + 1;
 344                if (!left)
 345                        break;
 346                left--;
 347                lno++;
 348        }
 349
 350        if (opt->unmatch_name_only) {
 351                /* We did not see any hit, so we want to show this */
 352                printf("%s\n", name);
 353                return 1;
 354        }
 355
 356        /* NEEDSWORK:
 357         * The real "grep -c foo *.c" gives many "bar.c:0" lines,
 358         * which feels mostly useless but sometimes useful.  Maybe
 359         * make it another option?  For now suppress them.
 360         */
 361        if (opt->count && count)
 362                printf("%s:%u\n", name, count);
 363        return !!last_hit;
 364}
 365
 366static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
 367{
 368        unsigned long size;
 369        char *data;
 370        char type[20];
 371        int hit;
 372        data = read_sha1_file(sha1, type, &size);
 373        if (!data) {
 374                error("'%s': unable to read %s", name, sha1_to_hex(sha1));
 375                return 0;
 376        }
 377        hit = grep_buffer(opt, name, data, size);
 378        free(data);
 379        return hit;
 380}
 381
 382static int grep_file(struct grep_opt *opt, const char *filename)
 383{
 384        struct stat st;
 385        int i;
 386        char *data;
 387        if (lstat(filename, &st) < 0) {
 388        err_ret:
 389                if (errno != ENOENT)
 390                        error("'%s': %s", filename, strerror(errno));
 391                return 0;
 392        }
 393        if (!st.st_size)
 394                return 0; /* empty file -- no grep hit */
 395        if (!S_ISREG(st.st_mode))
 396                return 0;
 397        i = open(filename, O_RDONLY);
 398        if (i < 0)
 399                goto err_ret;
 400        data = xmalloc(st.st_size + 1);
 401        if (st.st_size != xread(i, data, st.st_size)) {
 402                error("'%s': short read %s", filename, strerror(errno));
 403                close(i);
 404                free(data);
 405                return 0;
 406        }
 407        close(i);
 408        i = grep_buffer(opt, filename, data, st.st_size);
 409        free(data);
 410        return i;
 411}
 412
 413static int exec_grep(int argc, const char **argv)
 414{
 415        pid_t pid;
 416        int status;
 417
 418        argv[argc] = NULL;
 419        pid = fork();
 420        if (pid < 0)
 421                return pid;
 422        if (!pid) {
 423                execvp("grep", (char **) argv);
 424                exit(255);
 425        }
 426        while (waitpid(pid, &status, 0) < 0) {
 427                if (errno == EINTR)
 428                        continue;
 429                return -1;
 430        }
 431        if (WIFEXITED(status)) {
 432                if (!WEXITSTATUS(status))
 433                        return 1;
 434                return 0;
 435        }
 436        return -1;
 437}
 438
 439#define MAXARGS 1000
 440#define ARGBUF 4096
 441#define push_arg(a) do { \
 442        if (nr < MAXARGS) argv[nr++] = (a); \
 443        else die("maximum number of args exceeded"); \
 444        } while (0)
 445
 446static int external_grep(struct grep_opt *opt, const char **paths, int cached)
 447{
 448        int i, nr, argc, hit, len;
 449        const char *argv[MAXARGS+1];
 450        char randarg[ARGBUF];
 451        char *argptr = randarg;
 452        struct grep_pat *p;
 453
 454        len = nr = 0;
 455        push_arg("grep");
 456        if (opt->fixed)
 457                push_arg("-F");
 458        if (opt->linenum)
 459                push_arg("-n");
 460        if (opt->regflags & REG_EXTENDED)
 461                push_arg("-E");
 462        if (opt->regflags & REG_ICASE)
 463                push_arg("-i");
 464        if (opt->word_regexp)
 465                push_arg("-w");
 466        if (opt->name_only)
 467                push_arg("-l");
 468        if (opt->unmatch_name_only)
 469                push_arg("-L");
 470        if (opt->count)
 471                push_arg("-c");
 472        if (opt->post_context || opt->pre_context) {
 473                if (opt->post_context != opt->pre_context) {
 474                        if (opt->pre_context) {
 475                                push_arg("-B");
 476                                len += snprintf(argptr, sizeof(randarg)-len,
 477                                                "%u", opt->pre_context);
 478                                if (sizeof(randarg) <= len)
 479                                        die("maximum length of args exceeded");
 480                                push_arg(argptr);
 481                                argptr += len;
 482                        }
 483                        if (opt->post_context) {
 484                                push_arg("-A");
 485                                len += snprintf(argptr, sizeof(randarg)-len,
 486                                                "%u", opt->post_context);
 487                                if (sizeof(randarg) <= len)
 488                                        die("maximum length of args exceeded");
 489                                push_arg(argptr);
 490                                argptr += len;
 491                        }
 492                }
 493                else {
 494                        push_arg("-C");
 495                        len += snprintf(argptr, sizeof(randarg)-len,
 496                                        "%u", opt->post_context);
 497                        if (sizeof(randarg) <= len)
 498                                die("maximum length of args exceeded");
 499                        push_arg(argptr);
 500                        argptr += len;
 501                }
 502        }
 503        for (p = opt->pattern_list; p; p = p->next) {
 504                push_arg("-e");
 505                push_arg(p->pattern);
 506        }
 507
 508        /*
 509         * To make sure we get the header printed out when we want it,
 510         * add /dev/null to the paths to grep.  This is unnecessary
 511         * (and wrong) with "-l" or "-L", which always print out the
 512         * name anyway.
 513         *
 514         * GNU grep has "-H", but this is portable.
 515         */
 516        if (!opt->name_only && !opt->unmatch_name_only)
 517                push_arg("/dev/null");
 518
 519        hit = 0;
 520        argc = nr;
 521        for (i = 0; i < active_nr; i++) {
 522                struct cache_entry *ce = active_cache[i];
 523                char *name;
 524                if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
 525                        continue;
 526                if (!pathspec_matches(paths, ce->name))
 527                        continue;
 528                name = ce->name;
 529                if (name[0] == '-') {
 530                        int len = ce_namelen(ce);
 531                        name = xmalloc(len + 3);
 532                        memcpy(name, "./", 2);
 533                        memcpy(name + 2, ce->name, len + 1);
 534                }
 535                argv[argc++] = name;
 536                if (argc < MAXARGS)
 537                        continue;
 538                hit += exec_grep(argc, argv);
 539                argc = nr;
 540        }
 541        if (argc > nr)
 542                hit += exec_grep(argc, argv);
 543        return 0;
 544}
 545
 546static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
 547{
 548        int hit = 0;
 549        int nr;
 550        read_cache();
 551
 552#ifdef __unix__
 553        /*
 554         * Use the external "grep" command for the case where
 555         * we grep through the checked-out files. It tends to
 556         * be a lot more optimized
 557         */
 558        if (!cached) {
 559                hit = external_grep(opt, paths, cached);
 560                if (hit >= 0)
 561                        return hit;
 562        }
 563#endif
 564
 565        for (nr = 0; nr < active_nr; nr++) {
 566                struct cache_entry *ce = active_cache[nr];
 567                if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
 568                        continue;
 569                if (!pathspec_matches(paths, ce->name))
 570                        continue;
 571                if (cached)
 572                        hit |= grep_sha1(opt, ce->sha1, ce->name);
 573                else
 574                        hit |= grep_file(opt, ce->name);
 575        }
 576        return hit;
 577}
 578
 579static int grep_tree(struct grep_opt *opt, const char **paths,
 580                     struct tree_desc *tree,
 581                     const char *tree_name, const char *base)
 582{
 583        int len;
 584        int hit = 0;
 585        struct name_entry entry;
 586        char *down;
 587        char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
 588
 589        if (tree_name[0]) {
 590                int offset = sprintf(path_buf, "%s:", tree_name);
 591                down = path_buf + offset;
 592                strcat(down, base);
 593        }
 594        else {
 595                down = path_buf;
 596                strcpy(down, base);
 597        }
 598        len = strlen(path_buf);
 599
 600        while (tree_entry(tree, &entry)) {
 601                strcpy(path_buf + len, entry.path);
 602
 603                if (S_ISDIR(entry.mode))
 604                        /* Match "abc/" against pathspec to
 605                         * decide if we want to descend into "abc"
 606                         * directory.
 607                         */
 608                        strcpy(path_buf + len + entry.pathlen, "/");
 609
 610                if (!pathspec_matches(paths, down))
 611                        ;
 612                else if (S_ISREG(entry.mode))
 613                        hit |= grep_sha1(opt, entry.sha1, path_buf);
 614                else if (S_ISDIR(entry.mode)) {
 615                        char type[20];
 616                        struct tree_desc sub;
 617                        void *data;
 618                        data = read_sha1_file(entry.sha1, type, &sub.size);
 619                        if (!data)
 620                                die("unable to read tree (%s)",
 621                                    sha1_to_hex(entry.sha1));
 622                        sub.buf = data;
 623                        hit |= grep_tree(opt, paths, &sub, tree_name, down);
 624                        free(data);
 625                }
 626        }
 627        return hit;
 628}
 629
 630static int grep_object(struct grep_opt *opt, const char **paths,
 631                       struct object *obj, const char *name)
 632{
 633        if (!strcmp(obj->type, blob_type))
 634                return grep_sha1(opt, obj->sha1, name);
 635        if (!strcmp(obj->type, commit_type) ||
 636            !strcmp(obj->type, tree_type)) {
 637                struct tree_desc tree;
 638                void *data;
 639                int hit;
 640                data = read_object_with_reference(obj->sha1, tree_type,
 641                                                  &tree.size, NULL);
 642                if (!data)
 643                        die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
 644                tree.buf = data;
 645                hit = grep_tree(opt, paths, &tree, name, "");
 646                free(data);
 647                return hit;
 648        }
 649        die("unable to grep from object of type %s", obj->type);
 650}
 651
 652static const char builtin_grep_usage[] =
 653"git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
 654
 655int cmd_grep(int argc, const char **argv, char **envp)
 656{
 657        int hit = 0;
 658        int cached = 0;
 659        int seen_dashdash = 0;
 660        struct grep_opt opt;
 661        struct object_list *list, **tail, *object_list = NULL;
 662        const char *prefix = setup_git_directory();
 663        const char **paths = NULL;
 664        int i;
 665
 666        memset(&opt, 0, sizeof(opt));
 667        opt.pattern_tail = &opt.pattern_list;
 668        opt.regflags = REG_NEWLINE;
 669
 670        /*
 671         * If there is no -- then the paths must exist in the working
 672         * tree.  If there is no explicit pattern specified with -e or
 673         * -f, we take the first unrecognized non option to be the
 674         * pattern, but then what follows it must be zero or more
 675         * valid refs up to the -- (if exists), and then existing
 676         * paths.  If there is an explicit pattern, then the first
 677         * unrecocnized non option is the beginning of the refs list
 678         * that continues up to the -- (if exists), and then paths.
 679         */
 680
 681        tail = &object_list;
 682        while (1 < argc) {
 683                const char *arg = argv[1];
 684                argc--; argv++;
 685                if (!strcmp("--cached", arg)) {
 686                        cached = 1;
 687                        continue;
 688                }
 689                if (!strcmp("-a", arg) ||
 690                    !strcmp("--text", arg)) {
 691                        opt.binary = GREP_BINARY_TEXT;
 692                        continue;
 693                }
 694                if (!strcmp("-i", arg) ||
 695                    !strcmp("--ignore-case", arg)) {
 696                        opt.regflags |= REG_ICASE;
 697                        continue;
 698                }
 699                if (!strcmp("-I", arg)) {
 700                        opt.binary = GREP_BINARY_NOMATCH;
 701                        continue;
 702                }
 703                if (!strcmp("-v", arg) ||
 704                    !strcmp("--invert-match", arg)) {
 705                        opt.invert = 1;
 706                        continue;
 707                }
 708                if (!strcmp("-E", arg) ||
 709                    !strcmp("--extended-regexp", arg)) {
 710                        opt.regflags |= REG_EXTENDED;
 711                        continue;
 712                }
 713                if (!strcmp("-F", arg) ||
 714                    !strcmp("--fixed-strings", arg)) {
 715                        opt.fixed = 1;
 716                        continue;
 717                }
 718                if (!strcmp("-G", arg) ||
 719                    !strcmp("--basic-regexp", arg)) {
 720                        opt.regflags &= ~REG_EXTENDED;
 721                        continue;
 722                }
 723                if (!strcmp("-n", arg)) {
 724                        opt.linenum = 1;
 725                        continue;
 726                }
 727                if (!strcmp("-H", arg)) {
 728                        /* We always show the pathname, so this
 729                         * is a noop.
 730                         */
 731                        continue;
 732                }
 733                if (!strcmp("-l", arg) ||
 734                    !strcmp("--files-with-matches", arg)) {
 735                        opt.name_only = 1;
 736                        continue;
 737                }
 738                if (!strcmp("-L", arg) ||
 739                    !strcmp("--files-without-match", arg)) {
 740                        opt.unmatch_name_only = 1;
 741                        continue;
 742                }
 743                if (!strcmp("-c", arg) ||
 744                    !strcmp("--count", arg)) {
 745                        opt.count = 1;
 746                        continue;
 747                }
 748                if (!strcmp("-w", arg) ||
 749                    !strcmp("--word-regexp", arg)) {
 750                        opt.word_regexp = 1;
 751                        continue;
 752                }
 753                if (!strncmp("-A", arg, 2) ||
 754                    !strncmp("-B", arg, 2) ||
 755                    !strncmp("-C", arg, 2) ||
 756                    (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
 757                        unsigned num;
 758                        const char *scan;
 759                        switch (arg[1]) {
 760                        case 'A': case 'B': case 'C':
 761                                if (!arg[2]) {
 762                                        if (argc <= 1)
 763                                                usage(builtin_grep_usage);
 764                                        scan = *++argv;
 765                                        argc--;
 766                                }
 767                                else
 768                                        scan = arg + 2;
 769                                break;
 770                        default:
 771                                scan = arg + 1;
 772                                break;
 773                        }
 774                        if (sscanf(scan, "%u", &num) != 1)
 775                                usage(builtin_grep_usage);
 776                        switch (arg[1]) {
 777                        case 'A':
 778                                opt.post_context = num;
 779                                break;
 780                        default:
 781                        case 'C':
 782                                opt.post_context = num;
 783                        case 'B':
 784                                opt.pre_context = num;
 785                                break;
 786                        }
 787                        continue;
 788                }
 789                if (!strcmp("-f", arg)) {
 790                        FILE *patterns;
 791                        int lno = 0;
 792                        char buf[1024];
 793                        if (argc <= 1)
 794                                usage(builtin_grep_usage);
 795                        patterns = fopen(argv[1], "r");
 796                        if (!patterns)
 797                                die("'%s': %s", argv[1], strerror(errno));
 798                        while (fgets(buf, sizeof(buf), patterns)) {
 799                                int len = strlen(buf);
 800                                if (buf[len-1] == '\n')
 801                                        buf[len-1] = 0;
 802                                /* ignore empty line like grep does */
 803                                if (!buf[0])
 804                                        continue;
 805                                add_pattern(&opt, strdup(buf), argv[1], ++lno);
 806                        }
 807                        fclose(patterns);
 808                        argv++;
 809                        argc--;
 810                        continue;
 811                }
 812                if (!strcmp("-e", arg)) {
 813                        if (1 < argc) {
 814                                add_pattern(&opt, argv[1], "-e option", 0);
 815                                argv++;
 816                                argc--;
 817                                continue;
 818                        }
 819                        usage(builtin_grep_usage);
 820                }
 821                if (!strcmp("--", arg))
 822                        break;
 823                if (*arg == '-')
 824                        usage(builtin_grep_usage);
 825
 826                /* First unrecognized non-option token */
 827                if (!opt.pattern_list) {
 828                        add_pattern(&opt, arg, "command line", 0);
 829                        break;
 830                }
 831                else {
 832                        /* We are looking at the first path or rev;
 833                         * it is found at argv[1] after leaving the
 834                         * loop.
 835                         */
 836                        argc++; argv--;
 837                        break;
 838                }
 839        }
 840
 841        if (!opt.pattern_list)
 842                die("no pattern given.");
 843        if ((opt.regflags != REG_NEWLINE) && opt.fixed)
 844                die("cannot mix --fixed-strings and regexp");
 845        if (!opt.fixed)
 846                compile_patterns(&opt);
 847
 848        /* Check revs and then paths */
 849        for (i = 1; i < argc; i++) {
 850                const char *arg = argv[i];
 851                unsigned char sha1[20];
 852                /* Is it a rev? */
 853                if (!get_sha1(arg, sha1)) {
 854                        struct object *object = parse_object(sha1);
 855                        struct object_list *elem;
 856                        if (!object)
 857                                die("bad object %s", arg);
 858                        elem = object_list_insert(object, tail);
 859                        elem->name = arg;
 860                        tail = &elem->next;
 861                        continue;
 862                }
 863                if (!strcmp(arg, "--")) {
 864                        i++;
 865                        seen_dashdash = 1;
 866                }
 867                break;
 868        }
 869
 870        /* The rest are paths */
 871        if (!seen_dashdash) {
 872                int j;
 873                for (j = i; j < argc; j++)
 874                        verify_filename(prefix, argv[j]);
 875        }
 876
 877        if (i < argc)
 878                paths = get_pathspec(prefix, argv + i);
 879        else if (prefix) {
 880                paths = xcalloc(2, sizeof(const char *));
 881                paths[0] = prefix;
 882                paths[1] = NULL;
 883        }
 884
 885        if (!object_list)
 886                return !grep_cache(&opt, paths, cached);
 887
 888        if (cached)
 889                die("both --cached and trees are given.");
 890
 891        for (list = object_list; list; list = list->next) {
 892                struct object *real_obj;
 893                real_obj = deref_tag(list->item, NULL, 0);
 894                if (grep_object(&opt, paths, real_obj, list->name))
 895                        hit = 1;
 896        }
 897        return !hit;
 898}