25ee75d989d80382e370b5460f3d8f64ae086f6e
   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 "parse-options.h"
  14#include "userdiff.h"
  15#include "grep.h"
  16
  17#ifndef NO_EXTERNAL_GREP
  18#ifdef __unix__
  19#define NO_EXTERNAL_GREP 0
  20#else
  21#define NO_EXTERNAL_GREP 1
  22#endif
  23#endif
  24
  25static char const * const grep_usage[] = {
  26        "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
  27        NULL
  28};
  29
  30static int grep_config(const char *var, const char *value, void *cb)
  31{
  32        struct grep_opt *opt = cb;
  33
  34        switch (userdiff_config(var, value)) {
  35        case 0: break;
  36        case -1: return -1;
  37        default: return 0;
  38        }
  39
  40        if (!strcmp(var, "color.grep")) {
  41                opt->color = git_config_colorbool(var, value, -1);
  42                return 0;
  43        }
  44        if (!strcmp(var, "color.grep.external"))
  45                return git_config_string(&(opt->color_external), var, value);
  46        if (!strcmp(var, "color.grep.match")) {
  47                if (!value)
  48                        return config_error_nonbool(var);
  49                color_parse(value, var, opt->color_match);
  50                return 0;
  51        }
  52        return git_color_default_config(var, value, cb);
  53}
  54
  55/*
  56 * Return non-zero if max_depth is negative or path has no more then max_depth
  57 * slashes.
  58 */
  59static int accept_subdir(const char *path, int max_depth)
  60{
  61        if (max_depth < 0)
  62                return 1;
  63
  64        while ((path = strchr(path, '/')) != NULL) {
  65                max_depth--;
  66                if (max_depth < 0)
  67                        return 0;
  68                path++;
  69        }
  70        return 1;
  71}
  72
  73/*
  74 * Return non-zero if name is a subdirectory of match and is not too deep.
  75 */
  76static int is_subdir(const char *name, int namelen,
  77                const char *match, int matchlen, int max_depth)
  78{
  79        if (matchlen > namelen || strncmp(name, match, matchlen))
  80                return 0;
  81
  82        if (name[matchlen] == '\0') /* exact match */
  83                return 1;
  84
  85        if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
  86                return accept_subdir(name + matchlen + 1, max_depth);
  87
  88        return 0;
  89}
  90
  91/*
  92 * git grep pathspecs are somewhat different from diff-tree pathspecs;
  93 * pathname wildcards are allowed.
  94 */
  95static int pathspec_matches(const char **paths, const char *name, int max_depth)
  96{
  97        int namelen, i;
  98        if (!paths || !*paths)
  99                return accept_subdir(name, max_depth);
 100        namelen = strlen(name);
 101        for (i = 0; paths[i]; i++) {
 102                const char *match = paths[i];
 103                int matchlen = strlen(match);
 104                const char *cp, *meta;
 105
 106                if (is_subdir(name, namelen, match, matchlen, max_depth))
 107                        return 1;
 108                if (!fnmatch(match, name, 0))
 109                        return 1;
 110                if (name[namelen-1] != '/')
 111                        continue;
 112
 113                /* We are being asked if the directory ("name") is worth
 114                 * descending into.
 115                 *
 116                 * Find the longest leading directory name that does
 117                 * not have metacharacter in the pathspec; the name
 118                 * we are looking at must overlap with that directory.
 119                 */
 120                for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
 121                        char ch = *cp;
 122                        if (ch == '*' || ch == '[' || ch == '?') {
 123                                meta = cp;
 124                                break;
 125                        }
 126                }
 127                if (!meta)
 128                        meta = cp; /* fully literal */
 129
 130                if (namelen <= meta - match) {
 131                        /* Looking at "Documentation/" and
 132                         * the pattern says "Documentation/howto/", or
 133                         * "Documentation/diff*.txt".  The name we
 134                         * have should match prefix.
 135                         */
 136                        if (!memcmp(match, name, namelen))
 137                                return 1;
 138                        continue;
 139                }
 140
 141                if (meta - match < namelen) {
 142                        /* Looking at "Documentation/howto/" and
 143                         * the pattern says "Documentation/h*";
 144                         * match up to "Do.../h"; this avoids descending
 145                         * into "Documentation/technical/".
 146                         */
 147                        if (!memcmp(match, name, meta - match))
 148                                return 1;
 149                        continue;
 150                }
 151        }
 152        return 0;
 153}
 154
 155static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
 156{
 157        unsigned long size;
 158        char *data;
 159        enum object_type type;
 160        char *to_free = NULL;
 161        int hit;
 162
 163        data = read_sha1_file(sha1, &type, &size);
 164        if (!data) {
 165                error("'%s': unable to read %s", name, sha1_to_hex(sha1));
 166                return 0;
 167        }
 168        if (opt->relative && opt->prefix_length) {
 169                static char name_buf[PATH_MAX];
 170                char *cp;
 171                int name_len = strlen(name) - opt->prefix_length + 1;
 172
 173                if (!tree_name_len)
 174                        name += opt->prefix_length;
 175                else {
 176                        if (ARRAY_SIZE(name_buf) <= name_len)
 177                                cp = to_free = xmalloc(name_len);
 178                        else
 179                                cp = name_buf;
 180                        memcpy(cp, name, tree_name_len);
 181                        strcpy(cp + tree_name_len,
 182                               name + tree_name_len + opt->prefix_length);
 183                        name = cp;
 184                }
 185        }
 186        hit = grep_buffer(opt, name, data, size);
 187        free(data);
 188        free(to_free);
 189        return hit;
 190}
 191
 192static int grep_file(struct grep_opt *opt, const char *filename)
 193{
 194        struct stat st;
 195        int i;
 196        char *data;
 197        size_t sz;
 198
 199        if (lstat(filename, &st) < 0) {
 200        err_ret:
 201                if (errno != ENOENT)
 202                        error("'%s': %s", filename, strerror(errno));
 203                return 0;
 204        }
 205        if (!st.st_size)
 206                return 0; /* empty file -- no grep hit */
 207        if (!S_ISREG(st.st_mode))
 208                return 0;
 209        sz = xsize_t(st.st_size);
 210        i = open(filename, O_RDONLY);
 211        if (i < 0)
 212                goto err_ret;
 213        data = xmalloc(sz + 1);
 214        if (st.st_size != read_in_full(i, data, sz)) {
 215                error("'%s': short read %s", filename, strerror(errno));
 216                close(i);
 217                free(data);
 218                return 0;
 219        }
 220        close(i);
 221        if (opt->relative && opt->prefix_length)
 222                filename += opt->prefix_length;
 223        i = grep_buffer(opt, filename, data, sz);
 224        free(data);
 225        return i;
 226}
 227
 228#if !NO_EXTERNAL_GREP
 229static int exec_grep(int argc, const char **argv)
 230{
 231        pid_t pid;
 232        int status;
 233
 234        argv[argc] = NULL;
 235        pid = fork();
 236        if (pid < 0)
 237                return pid;
 238        if (!pid) {
 239                execvp("grep", (char **) argv);
 240                exit(255);
 241        }
 242        while (waitpid(pid, &status, 0) < 0) {
 243                if (errno == EINTR)
 244                        continue;
 245                return -1;
 246        }
 247        if (WIFEXITED(status)) {
 248                if (!WEXITSTATUS(status))
 249                        return 1;
 250                return 0;
 251        }
 252        return -1;
 253}
 254
 255#define MAXARGS 1000
 256#define ARGBUF 4096
 257#define push_arg(a) do { \
 258        if (nr < MAXARGS) argv[nr++] = (a); \
 259        else die("maximum number of args exceeded"); \
 260        } while (0)
 261
 262/*
 263 * If you send a singleton filename to grep, it does not give
 264 * the name of the file.  GNU grep has "-H" but we would want
 265 * that behaviour in a portable way.
 266 *
 267 * So we keep two pathnames in argv buffer unsent to grep in
 268 * the main loop if we need to do more than one grep.
 269 */
 270static int flush_grep(struct grep_opt *opt,
 271                      int argc, int arg0, const char **argv, int *kept)
 272{
 273        int status;
 274        int count = argc - arg0;
 275        const char *kept_0 = NULL;
 276
 277        if (count <= 2) {
 278                /*
 279                 * Because we keep at least 2 paths in the call from
 280                 * the main loop (i.e. kept != NULL), and MAXARGS is
 281                 * far greater than 2, this usually is a call to
 282                 * conclude the grep.  However, the user could attempt
 283                 * to overflow the argv buffer by giving too many
 284                 * options to leave very small number of real
 285                 * arguments even for the call in the main loop.
 286                 */
 287                if (kept)
 288                        die("insanely many options to grep");
 289
 290                /*
 291                 * If we have two or more paths, we do not have to do
 292                 * anything special, but we need to push /dev/null to
 293                 * get "-H" behaviour of GNU grep portably but when we
 294                 * are not doing "-l" nor "-L" nor "-c".
 295                 */
 296                if (count == 1 &&
 297                    !opt->name_only &&
 298                    !opt->unmatch_name_only &&
 299                    !opt->count) {
 300                        argv[argc++] = "/dev/null";
 301                        argv[argc] = NULL;
 302                }
 303        }
 304
 305        else if (kept) {
 306                /*
 307                 * Called because we found many paths and haven't finished
 308                 * iterating over the cache yet.  We keep two paths
 309                 * for the concluding call.  argv[argc-2] and argv[argc-1]
 310                 * has the last two paths, so save the first one away,
 311                 * replace it with NULL while sending the list to grep,
 312                 * and recover them after we are done.
 313                 */
 314                *kept = 2;
 315                kept_0 = argv[argc-2];
 316                argv[argc-2] = NULL;
 317                argc -= 2;
 318        }
 319
 320        if (opt->pre_context || opt->post_context) {
 321                /*
 322                 * grep handles hunk marks between files, but we need to
 323                 * do that ourselves between multiple calls.
 324                 */
 325                if (opt->show_hunk_mark)
 326                        write_or_die(1, "--\n", 3);
 327                else
 328                        opt->show_hunk_mark = 1;
 329        }
 330
 331        status = exec_grep(argc, argv);
 332
 333        if (kept_0) {
 334                /*
 335                 * Then recover them.  Now the last arg is beyond the
 336                 * terminating NULL which is at argc, and the second
 337                 * from the last is what we saved away in kept_0
 338                 */
 339                argv[arg0++] = kept_0;
 340                argv[arg0] = argv[argc+1];
 341        }
 342        return status;
 343}
 344
 345static void grep_add_color(struct strbuf *sb, const char *escape_seq)
 346{
 347        size_t orig_len = sb->len;
 348
 349        while (*escape_seq) {
 350                if (*escape_seq == 'm')
 351                        strbuf_addch(sb, ';');
 352                else if (*escape_seq != '\033' && *escape_seq  != '[')
 353                        strbuf_addch(sb, *escape_seq);
 354                escape_seq++;
 355        }
 356        if (sb->len > orig_len && sb->buf[sb->len - 1] == ';')
 357                strbuf_setlen(sb, sb->len - 1);
 358}
 359
 360static int has_skip_worktree_entry(struct grep_opt *opt, const char **paths)
 361{
 362        int nr;
 363        for (nr = 0; nr < active_nr; nr++) {
 364                struct cache_entry *ce = active_cache[nr];
 365                if (!S_ISREG(ce->ce_mode))
 366                        continue;
 367                if (!pathspec_matches(paths, ce->name, opt->max_depth))
 368                        continue;
 369                if (ce_skip_worktree(ce))
 370                        return 1;
 371        }
 372        return 0;
 373}
 374
 375static int external_grep(struct grep_opt *opt, const char **paths, int cached)
 376{
 377        int i, nr, argc, hit, len, status;
 378        const char *argv[MAXARGS+1];
 379        char randarg[ARGBUF];
 380        char *argptr = randarg;
 381        struct grep_pat *p;
 382
 383        if (opt->extended || (opt->relative && opt->prefix_length)
 384            || has_skip_worktree_entry(opt, paths))
 385                return -1;
 386        len = nr = 0;
 387        push_arg("grep");
 388        if (opt->fixed)
 389                push_arg("-F");
 390        if (opt->linenum)
 391                push_arg("-n");
 392        if (!opt->pathname)
 393                push_arg("-h");
 394        if (opt->regflags & REG_EXTENDED)
 395                push_arg("-E");
 396        if (opt->regflags & REG_ICASE)
 397                push_arg("-i");
 398        if (opt->binary == GREP_BINARY_NOMATCH)
 399                push_arg("-I");
 400        if (opt->word_regexp)
 401                push_arg("-w");
 402        if (opt->name_only)
 403                push_arg("-l");
 404        if (opt->unmatch_name_only)
 405                push_arg("-L");
 406        if (opt->null_following_name)
 407                /* in GNU grep git's "-z" translates to "-Z" */
 408                push_arg("-Z");
 409        if (opt->count)
 410                push_arg("-c");
 411        if (opt->post_context || opt->pre_context) {
 412                if (opt->post_context != opt->pre_context) {
 413                        if (opt->pre_context) {
 414                                push_arg("-B");
 415                                len += snprintf(argptr, sizeof(randarg)-len,
 416                                                "%u", opt->pre_context) + 1;
 417                                if (sizeof(randarg) <= len)
 418                                        die("maximum length of args exceeded");
 419                                push_arg(argptr);
 420                                argptr += len;
 421                        }
 422                        if (opt->post_context) {
 423                                push_arg("-A");
 424                                len += snprintf(argptr, sizeof(randarg)-len,
 425                                                "%u", opt->post_context) + 1;
 426                                if (sizeof(randarg) <= len)
 427                                        die("maximum length of args exceeded");
 428                                push_arg(argptr);
 429                                argptr += len;
 430                        }
 431                }
 432                else {
 433                        push_arg("-C");
 434                        len += snprintf(argptr, sizeof(randarg)-len,
 435                                        "%u", opt->post_context) + 1;
 436                        if (sizeof(randarg) <= len)
 437                                die("maximum length of args exceeded");
 438                        push_arg(argptr);
 439                        argptr += len;
 440                }
 441        }
 442        for (p = opt->pattern_list; p; p = p->next) {
 443                push_arg("-e");
 444                push_arg(p->pattern);
 445        }
 446        if (opt->color) {
 447                struct strbuf sb = STRBUF_INIT;
 448
 449                grep_add_color(&sb, opt->color_match);
 450                setenv("GREP_COLOR", sb.buf, 1);
 451
 452                strbuf_reset(&sb);
 453                strbuf_addstr(&sb, "mt=");
 454                grep_add_color(&sb, opt->color_match);
 455                strbuf_addstr(&sb, ":sl=:cx=:fn=:ln=:bn=:se=");
 456                setenv("GREP_COLORS", sb.buf, 1);
 457
 458                strbuf_release(&sb);
 459
 460                if (opt->color_external && strlen(opt->color_external) > 0)
 461                        push_arg(opt->color_external);
 462        }
 463
 464        hit = 0;
 465        argc = nr;
 466        for (i = 0; i < active_nr; i++) {
 467                struct cache_entry *ce = active_cache[i];
 468                char *name;
 469                int kept;
 470                if (!S_ISREG(ce->ce_mode))
 471                        continue;
 472                if (!pathspec_matches(paths, ce->name, opt->max_depth))
 473                        continue;
 474                name = ce->name;
 475                if (name[0] == '-') {
 476                        int len = ce_namelen(ce);
 477                        name = xmalloc(len + 3);
 478                        memcpy(name, "./", 2);
 479                        memcpy(name + 2, ce->name, len + 1);
 480                }
 481                argv[argc++] = name;
 482                if (MAXARGS <= argc) {
 483                        status = flush_grep(opt, argc, nr, argv, &kept);
 484                        if (0 < status)
 485                                hit = 1;
 486                        argc = nr + kept;
 487                }
 488                if (ce_stage(ce)) {
 489                        do {
 490                                i++;
 491                        } while (i < active_nr &&
 492                                 !strcmp(ce->name, active_cache[i]->name));
 493                        i--; /* compensate for loop control */
 494                }
 495        }
 496        if (argc > nr) {
 497                status = flush_grep(opt, argc, nr, argv, NULL);
 498                if (0 < status)
 499                        hit = 1;
 500        }
 501        return hit;
 502}
 503#endif
 504
 505static int grep_cache(struct grep_opt *opt, const char **paths, int cached,
 506                      int external_grep_allowed)
 507{
 508        int hit = 0;
 509        int nr;
 510        read_cache();
 511
 512#if !NO_EXTERNAL_GREP
 513        /*
 514         * Use the external "grep" command for the case where
 515         * we grep through the checked-out files. It tends to
 516         * be a lot more optimized
 517         */
 518        if (!cached && external_grep_allowed) {
 519                hit = external_grep(opt, paths, cached);
 520                if (hit >= 0)
 521                        return hit;
 522        }
 523#endif
 524
 525        for (nr = 0; nr < active_nr; nr++) {
 526                struct cache_entry *ce = active_cache[nr];
 527                if (!S_ISREG(ce->ce_mode))
 528                        continue;
 529                if (!pathspec_matches(paths, ce->name, opt->max_depth))
 530                        continue;
 531                /*
 532                 * If CE_VALID is on, we assume worktree file and its cache entry
 533                 * are identical, even if worktree file has been modified, so use
 534                 * cache version instead
 535                 */
 536                if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
 537                        if (ce_stage(ce))
 538                                continue;
 539                        hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
 540                }
 541                else
 542                        hit |= grep_file(opt, ce->name);
 543                if (ce_stage(ce)) {
 544                        do {
 545                                nr++;
 546                        } while (nr < active_nr &&
 547                                 !strcmp(ce->name, active_cache[nr]->name));
 548                        nr--; /* compensate for loop control */
 549                }
 550        }
 551        free_grep_patterns(opt);
 552        return hit;
 553}
 554
 555static int grep_tree(struct grep_opt *opt, const char **paths,
 556                     struct tree_desc *tree,
 557                     const char *tree_name, const char *base)
 558{
 559        int len;
 560        int hit = 0;
 561        struct name_entry entry;
 562        char *down;
 563        int tn_len = strlen(tree_name);
 564        struct strbuf pathbuf;
 565
 566        strbuf_init(&pathbuf, PATH_MAX + tn_len);
 567
 568        if (tn_len) {
 569                strbuf_add(&pathbuf, tree_name, tn_len);
 570                strbuf_addch(&pathbuf, ':');
 571                tn_len = pathbuf.len;
 572        }
 573        strbuf_addstr(&pathbuf, base);
 574        len = pathbuf.len;
 575
 576        while (tree_entry(tree, &entry)) {
 577                int te_len = tree_entry_len(entry.path, entry.sha1);
 578                pathbuf.len = len;
 579                strbuf_add(&pathbuf, entry.path, te_len);
 580
 581                if (S_ISDIR(entry.mode))
 582                        /* Match "abc/" against pathspec to
 583                         * decide if we want to descend into "abc"
 584                         * directory.
 585                         */
 586                        strbuf_addch(&pathbuf, '/');
 587
 588                down = pathbuf.buf + tn_len;
 589                if (!pathspec_matches(paths, down, opt->max_depth))
 590                        ;
 591                else if (S_ISREG(entry.mode))
 592                        hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
 593                else if (S_ISDIR(entry.mode)) {
 594                        enum object_type type;
 595                        struct tree_desc sub;
 596                        void *data;
 597                        unsigned long size;
 598
 599                        data = read_sha1_file(entry.sha1, &type, &size);
 600                        if (!data)
 601                                die("unable to read tree (%s)",
 602                                    sha1_to_hex(entry.sha1));
 603                        init_tree_desc(&sub, data, size);
 604                        hit |= grep_tree(opt, paths, &sub, tree_name, down);
 605                        free(data);
 606                }
 607        }
 608        strbuf_release(&pathbuf);
 609        return hit;
 610}
 611
 612static int grep_object(struct grep_opt *opt, const char **paths,
 613                       struct object *obj, const char *name)
 614{
 615        if (obj->type == OBJ_BLOB)
 616                return grep_sha1(opt, obj->sha1, name, 0);
 617        if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
 618                struct tree_desc tree;
 619                void *data;
 620                unsigned long size;
 621                int hit;
 622                data = read_object_with_reference(obj->sha1, tree_type,
 623                                                  &size, NULL);
 624                if (!data)
 625                        die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
 626                init_tree_desc(&tree, data, size);
 627                hit = grep_tree(opt, paths, &tree, name, "");
 628                free(data);
 629                return hit;
 630        }
 631        die("unable to grep from object of type %s", typename(obj->type));
 632}
 633
 634static int context_callback(const struct option *opt, const char *arg,
 635                            int unset)
 636{
 637        struct grep_opt *grep_opt = opt->value;
 638        int value;
 639        const char *endp;
 640
 641        if (unset) {
 642                grep_opt->pre_context = grep_opt->post_context = 0;
 643                return 0;
 644        }
 645        value = strtol(arg, (char **)&endp, 10);
 646        if (*endp) {
 647                return error("switch `%c' expects a numerical value",
 648                             opt->short_name);
 649        }
 650        grep_opt->pre_context = grep_opt->post_context = value;
 651        return 0;
 652}
 653
 654static int file_callback(const struct option *opt, const char *arg, int unset)
 655{
 656        struct grep_opt *grep_opt = opt->value;
 657        FILE *patterns;
 658        int lno = 0;
 659        struct strbuf sb;
 660
 661        patterns = fopen(arg, "r");
 662        if (!patterns)
 663                die_errno("cannot open '%s'", arg);
 664        while (strbuf_getline(&sb, patterns, '\n') == 0) {
 665                /* ignore empty line like grep does */
 666                if (sb.len == 0)
 667                        continue;
 668                append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
 669                                    ++lno, GREP_PATTERN);
 670        }
 671        fclose(patterns);
 672        strbuf_release(&sb);
 673        return 0;
 674}
 675
 676static int not_callback(const struct option *opt, const char *arg, int unset)
 677{
 678        struct grep_opt *grep_opt = opt->value;
 679        append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
 680        return 0;
 681}
 682
 683static int and_callback(const struct option *opt, const char *arg, int unset)
 684{
 685        struct grep_opt *grep_opt = opt->value;
 686        append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
 687        return 0;
 688}
 689
 690static int open_callback(const struct option *opt, const char *arg, int unset)
 691{
 692        struct grep_opt *grep_opt = opt->value;
 693        append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
 694        return 0;
 695}
 696
 697static int close_callback(const struct option *opt, const char *arg, int unset)
 698{
 699        struct grep_opt *grep_opt = opt->value;
 700        append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
 701        return 0;
 702}
 703
 704static int pattern_callback(const struct option *opt, const char *arg,
 705                            int unset)
 706{
 707        struct grep_opt *grep_opt = opt->value;
 708        append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
 709        return 0;
 710}
 711
 712static int help_callback(const struct option *opt, const char *arg, int unset)
 713{
 714        return -1;
 715}
 716
 717int cmd_grep(int argc, const char **argv, const char *prefix)
 718{
 719        int hit = 0;
 720        int cached = 0;
 721        int external_grep_allowed = 1;
 722        int seen_dashdash = 0;
 723        struct grep_opt opt;
 724        struct object_array list = { 0, 0, NULL };
 725        const char **paths = NULL;
 726        int i;
 727        int dummy;
 728        struct option options[] = {
 729                OPT_BOOLEAN(0, "cached", &cached,
 730                        "search in index instead of in the work tree"),
 731                OPT_GROUP(""),
 732                OPT_BOOLEAN('v', "invert-match", &opt.invert,
 733                        "show non-matching lines"),
 734                OPT_BIT('i', "ignore-case", &opt.regflags,
 735                        "case insensitive matching", REG_ICASE),
 736                OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
 737                        "match patterns only at word boundaries"),
 738                OPT_SET_INT('a', "text", &opt.binary,
 739                        "process binary files as text", GREP_BINARY_TEXT),
 740                OPT_SET_INT('I', NULL, &opt.binary,
 741                        "don't match patterns in binary files",
 742                        GREP_BINARY_NOMATCH),
 743                { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
 744                        "descend at most <depth> levels", PARSE_OPT_NONEG,
 745                        NULL, 1 },
 746                OPT_GROUP(""),
 747                OPT_BIT('E', "extended-regexp", &opt.regflags,
 748                        "use extended POSIX regular expressions", REG_EXTENDED),
 749                OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
 750                        "use basic POSIX regular expressions (default)",
 751                        REG_EXTENDED),
 752                OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
 753                        "interpret patterns as fixed strings"),
 754                OPT_GROUP(""),
 755                OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
 756                OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
 757                OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
 758                OPT_NEGBIT(0, "full-name", &opt.relative,
 759                        "show filenames relative to top directory", 1),
 760                OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
 761                        "show only filenames instead of matching lines"),
 762                OPT_BOOLEAN(0, "name-only", &opt.name_only,
 763                        "synonym for --files-with-matches"),
 764                OPT_BOOLEAN('L', "files-without-match",
 765                        &opt.unmatch_name_only,
 766                        "show only the names of files without match"),
 767                OPT_BOOLEAN('z', "null", &opt.null_following_name,
 768                        "print NUL after filenames"),
 769                OPT_BOOLEAN('c', "count", &opt.count,
 770                        "show the number of matches instead of matching lines"),
 771                OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
 772                OPT_GROUP(""),
 773                OPT_CALLBACK('C', NULL, &opt, "n",
 774                        "show <n> context lines before and after matches",
 775                        context_callback),
 776                OPT_INTEGER('B', NULL, &opt.pre_context,
 777                        "show <n> context lines before matches"),
 778                OPT_INTEGER('A', NULL, &opt.post_context,
 779                        "show <n> context lines after matches"),
 780                OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
 781                        context_callback),
 782                OPT_BOOLEAN('p', "show-function", &opt.funcname,
 783                        "show a line with the function name before matches"),
 784                OPT_GROUP(""),
 785                OPT_CALLBACK('f', NULL, &opt, "file",
 786                        "read patterns from file", file_callback),
 787                { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
 788                        "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
 789                { OPTION_CALLBACK, 0, "and", &opt, NULL,
 790                  "combine patterns specified with -e",
 791                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
 792                OPT_BOOLEAN(0, "or", &dummy, ""),
 793                { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
 794                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
 795                { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
 796                  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
 797                  open_callback },
 798                { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
 799                  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
 800                  close_callback },
 801                OPT_BOOLEAN(0, "all-match", &opt.all_match,
 802                        "show only matches from files that match all patterns"),
 803                OPT_GROUP(""),
 804#if NO_EXTERNAL_GREP
 805                OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
 806                        "allow calling of grep(1) (ignored by this build)"),
 807#else
 808                OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed,
 809                        "allow calling of grep(1) (default)"),
 810#endif
 811                { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
 812                  PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
 813                OPT_END()
 814        };
 815
 816        memset(&opt, 0, sizeof(opt));
 817        opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
 818        opt.relative = 1;
 819        opt.pathname = 1;
 820        opt.pattern_tail = &opt.pattern_list;
 821        opt.regflags = REG_NEWLINE;
 822        opt.max_depth = -1;
 823
 824        strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
 825        opt.color = -1;
 826        git_config(grep_config, &opt);
 827        if (opt.color == -1)
 828                opt.color = git_use_color_default;
 829
 830        /*
 831         * If there is no -- then the paths must exist in the working
 832         * tree.  If there is no explicit pattern specified with -e or
 833         * -f, we take the first unrecognized non option to be the
 834         * pattern, but then what follows it must be zero or more
 835         * valid refs up to the -- (if exists), and then existing
 836         * paths.  If there is an explicit pattern, then the first
 837         * unrecognized non option is the beginning of the refs list
 838         * that continues up to the -- (if exists), and then paths.
 839         */
 840        argc = parse_options(argc, argv, prefix, options, grep_usage,
 841                             PARSE_OPT_KEEP_DASHDASH |
 842                             PARSE_OPT_STOP_AT_NON_OPTION |
 843                             PARSE_OPT_NO_INTERNAL_HELP);
 844
 845        /* First unrecognized non-option token */
 846        if (argc > 0 && !opt.pattern_list) {
 847                append_grep_pattern(&opt, argv[0], "command line", 0,
 848                                    GREP_PATTERN);
 849                argv++;
 850                argc--;
 851        }
 852
 853        if ((opt.color && !opt.color_external) || opt.funcname)
 854                external_grep_allowed = 0;
 855        if (!opt.pattern_list)
 856                die("no pattern given.");
 857        if ((opt.regflags != REG_NEWLINE) && opt.fixed)
 858                die("cannot mix --fixed-strings and regexp");
 859        compile_grep_patterns(&opt);
 860
 861        /* Check revs and then paths */
 862        for (i = 0; i < argc; i++) {
 863                const char *arg = argv[i];
 864                unsigned char sha1[20];
 865                /* Is it a rev? */
 866                if (!get_sha1(arg, sha1)) {
 867                        struct object *object = parse_object(sha1);
 868                        if (!object)
 869                                die("bad object %s", arg);
 870                        add_object_array(object, arg, &list);
 871                        continue;
 872                }
 873                if (!strcmp(arg, "--")) {
 874                        i++;
 875                        seen_dashdash = 1;
 876                }
 877                break;
 878        }
 879
 880        /* The rest are paths */
 881        if (!seen_dashdash) {
 882                int j;
 883                for (j = i; j < argc; j++)
 884                        verify_filename(prefix, argv[j]);
 885        }
 886
 887        if (i < argc) {
 888                paths = get_pathspec(prefix, argv + i);
 889                if (opt.prefix_length && opt.relative) {
 890                        /* Make sure we do not get outside of paths */
 891                        for (i = 0; paths[i]; i++)
 892                                if (strncmp(prefix, paths[i], opt.prefix_length))
 893                                        die("git grep: cannot generate relative filenames containing '..'");
 894                }
 895        }
 896        else if (prefix) {
 897                paths = xcalloc(2, sizeof(const char *));
 898                paths[0] = prefix;
 899                paths[1] = NULL;
 900        }
 901
 902        if (!list.nr) {
 903                if (!cached)
 904                        setup_work_tree();
 905                return !grep_cache(&opt, paths, cached, external_grep_allowed);
 906        }
 907
 908        if (cached)
 909                die("both --cached and trees are given.");
 910
 911        for (i = 0; i < list.nr; i++) {
 912                struct object *real_obj;
 913                real_obj = deref_tag(list.objects[i].item, NULL, 0);
 914                if (grep_object(&opt, paths, real_obj, list.objects[i].name))
 915                        hit = 1;
 916        }
 917        free_grep_patterns(&opt);
 918        return !hit;
 919}