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