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