builtin-grep.con commit grep: Fix race condition in delta_base_cache (8cb5775)
   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#include "quote.h"
  17#include "dir.h"
  18
  19#ifndef NO_PTHREADS
  20#include "thread-utils.h"
  21#include <pthread.h>
  22#endif
  23
  24static char const * const grep_usage[] = {
  25        "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
  26        NULL
  27};
  28
  29static int use_threads = 1;
  30
  31#ifndef NO_PTHREADS
  32#define THREADS 8
  33static pthread_t threads[THREADS];
  34
  35static void *load_sha1(const unsigned char *sha1, unsigned long *size,
  36                       const char *name);
  37static void *load_file(const char *filename, size_t *sz);
  38
  39enum work_type {WORK_SHA1, WORK_FILE};
  40
  41/* We use one producer thread and THREADS consumer
  42 * threads. The producer adds struct work_items to 'todo' and the
  43 * consumers pick work items from the same array.
  44 */
  45struct work_item
  46{
  47        enum work_type type;
  48        char *name;
  49
  50        /* if type == WORK_SHA1, then 'identifier' is a SHA1,
  51         * otherwise type == WORK_FILE, and 'identifier' is a NUL
  52         * terminated filename.
  53         */
  54        void *identifier;
  55        char done;
  56        struct strbuf out;
  57};
  58
  59/* In the range [todo_done, todo_start) in 'todo' we have work_items
  60 * that have been or are processed by a consumer thread. We haven't
  61 * written the result for these to stdout yet.
  62 *
  63 * The work_items in [todo_start, todo_end) are waiting to be picked
  64 * up by a consumer thread.
  65 *
  66 * The ranges are modulo TODO_SIZE.
  67 */
  68#define TODO_SIZE 128
  69static struct work_item todo[TODO_SIZE];
  70static int todo_start;
  71static int todo_end;
  72static int todo_done;
  73
  74/* Has all work items been added? */
  75static int all_work_added;
  76
  77/* This lock protects all the variables above. */
  78static pthread_mutex_t grep_mutex;
  79
  80/* Used to serialize calls to read_sha1_file. */
  81static pthread_mutex_t read_sha1_mutex;
  82
  83#define grep_lock() pthread_mutex_lock(&grep_mutex)
  84#define grep_unlock() pthread_mutex_unlock(&grep_mutex)
  85#define read_sha1_lock() pthread_mutex_lock(&read_sha1_mutex)
  86#define read_sha1_unlock() pthread_mutex_unlock(&read_sha1_mutex)
  87
  88/* Signalled when a new work_item is added to todo. */
  89static pthread_cond_t cond_add;
  90
  91/* Signalled when the result from one work_item is written to
  92 * stdout.
  93 */
  94static pthread_cond_t cond_write;
  95
  96/* Signalled when we are finished with everything. */
  97static pthread_cond_t cond_result;
  98
  99static void add_work(enum work_type type, char *name, void *id)
 100{
 101        grep_lock();
 102
 103        while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
 104                pthread_cond_wait(&cond_write, &grep_mutex);
 105        }
 106
 107        todo[todo_end].type = type;
 108        todo[todo_end].name = name;
 109        todo[todo_end].identifier = id;
 110        todo[todo_end].done = 0;
 111        strbuf_reset(&todo[todo_end].out);
 112        todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
 113
 114        pthread_cond_signal(&cond_add);
 115        grep_unlock();
 116}
 117
 118static struct work_item *get_work(void)
 119{
 120        struct work_item *ret;
 121
 122        grep_lock();
 123        while (todo_start == todo_end && !all_work_added) {
 124                pthread_cond_wait(&cond_add, &grep_mutex);
 125        }
 126
 127        if (todo_start == todo_end && all_work_added) {
 128                ret = NULL;
 129        } else {
 130                ret = &todo[todo_start];
 131                todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
 132        }
 133        grep_unlock();
 134        return ret;
 135}
 136
 137static void grep_sha1_async(struct grep_opt *opt, char *name,
 138                            const unsigned char *sha1)
 139{
 140        unsigned char *s;
 141        s = xmalloc(20);
 142        memcpy(s, sha1, 20);
 143        add_work(WORK_SHA1, name, s);
 144}
 145
 146static void grep_file_async(struct grep_opt *opt, char *name,
 147                            const char *filename)
 148{
 149        add_work(WORK_FILE, name, xstrdup(filename));
 150}
 151
 152static void work_done(struct work_item *w)
 153{
 154        int old_done;
 155
 156        grep_lock();
 157        w->done = 1;
 158        old_done = todo_done;
 159        for(; todo[todo_done].done && todo_done != todo_start;
 160            todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
 161                w = &todo[todo_done];
 162                write_or_die(1, w->out.buf, w->out.len);
 163                free(w->name);
 164                free(w->identifier);
 165        }
 166
 167        if (old_done != todo_done)
 168                pthread_cond_signal(&cond_write);
 169
 170        if (all_work_added && todo_done == todo_end)
 171                pthread_cond_signal(&cond_result);
 172
 173        grep_unlock();
 174}
 175
 176static void *run(void *arg)
 177{
 178        int hit = 0;
 179        struct grep_opt *opt = arg;
 180
 181        while (1) {
 182                struct work_item *w = get_work();
 183                if (!w)
 184                        break;
 185
 186                opt->output_priv = w;
 187                if (w->type == WORK_SHA1) {
 188                        unsigned long sz;
 189                        void* data = load_sha1(w->identifier, &sz, w->name);
 190
 191                        if (data) {
 192                                hit |= grep_buffer(opt, w->name, data, sz);
 193                                free(data);
 194                        }
 195                } else if (w->type == WORK_FILE) {
 196                        size_t sz;
 197                        void* data = load_file(w->identifier, &sz);
 198                        if (data) {
 199                                hit |= grep_buffer(opt, w->name, data, sz);
 200                                free(data);
 201                        }
 202                } else {
 203                        assert(0);
 204                }
 205
 206                work_done(w);
 207        }
 208
 209        return (void*) (intptr_t) hit;
 210}
 211
 212static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
 213{
 214        struct work_item *w = opt->output_priv;
 215        strbuf_add(&w->out, buf, size);
 216}
 217
 218static void start_threads(struct grep_opt *opt)
 219{
 220        int i;
 221
 222        pthread_mutex_init(&grep_mutex, NULL);
 223        pthread_mutex_init(&read_sha1_mutex, NULL);
 224        pthread_cond_init(&cond_add, NULL);
 225        pthread_cond_init(&cond_write, NULL);
 226        pthread_cond_init(&cond_result, NULL);
 227
 228        for (i = 0; i < ARRAY_SIZE(todo); i++) {
 229                strbuf_init(&todo[i].out, 0);
 230        }
 231
 232        for (i = 0; i < ARRAY_SIZE(threads); i++) {
 233                int err;
 234                struct grep_opt *o = grep_opt_dup(opt);
 235                o->output = strbuf_out;
 236                compile_grep_patterns(o);
 237                err = pthread_create(&threads[i], NULL, run, o);
 238
 239                if (err)
 240                        die("grep: failed to create thread: %s",
 241                            strerror(err));
 242        }
 243}
 244
 245static int wait_all(void)
 246{
 247        int hit = 0;
 248        int i;
 249
 250        grep_lock();
 251        all_work_added = 1;
 252
 253        /* Wait until all work is done. */
 254        while (todo_done != todo_end)
 255                pthread_cond_wait(&cond_result, &grep_mutex);
 256
 257        /* Wake up all the consumer threads so they can see that there
 258         * is no more work to do.
 259         */
 260        pthread_cond_broadcast(&cond_add);
 261        grep_unlock();
 262
 263        for (i = 0; i < ARRAY_SIZE(threads); i++) {
 264                void *h;
 265                pthread_join(threads[i], &h);
 266                hit |= (int) (intptr_t) h;
 267        }
 268
 269        pthread_mutex_destroy(&grep_mutex);
 270        pthread_mutex_destroy(&read_sha1_mutex);
 271        pthread_cond_destroy(&cond_add);
 272        pthread_cond_destroy(&cond_write);
 273        pthread_cond_destroy(&cond_result);
 274
 275        return hit;
 276}
 277#else /* !NO_PTHREADS */
 278#define read_sha1_lock()
 279#define read_sha1_unlock()
 280
 281static int wait_all(void)
 282{
 283        return 0;
 284}
 285#endif
 286
 287static int grep_config(const char *var, const char *value, void *cb)
 288{
 289        struct grep_opt *opt = cb;
 290
 291        switch (userdiff_config(var, value)) {
 292        case 0: break;
 293        case -1: return -1;
 294        default: return 0;
 295        }
 296
 297        if (!strcmp(var, "color.grep")) {
 298                opt->color = git_config_colorbool(var, value, -1);
 299                return 0;
 300        }
 301        if (!strcmp(var, "color.grep.match")) {
 302                if (!value)
 303                        return config_error_nonbool(var);
 304                color_parse(value, var, opt->color_match);
 305                return 0;
 306        }
 307        return git_color_default_config(var, value, cb);
 308}
 309
 310/*
 311 * Return non-zero if max_depth is negative or path has no more then max_depth
 312 * slashes.
 313 */
 314static int accept_subdir(const char *path, int max_depth)
 315{
 316        if (max_depth < 0)
 317                return 1;
 318
 319        while ((path = strchr(path, '/')) != NULL) {
 320                max_depth--;
 321                if (max_depth < 0)
 322                        return 0;
 323                path++;
 324        }
 325        return 1;
 326}
 327
 328/*
 329 * Return non-zero if name is a subdirectory of match and is not too deep.
 330 */
 331static int is_subdir(const char *name, int namelen,
 332                const char *match, int matchlen, int max_depth)
 333{
 334        if (matchlen > namelen || strncmp(name, match, matchlen))
 335                return 0;
 336
 337        if (name[matchlen] == '\0') /* exact match */
 338                return 1;
 339
 340        if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
 341                return accept_subdir(name + matchlen + 1, max_depth);
 342
 343        return 0;
 344}
 345
 346/*
 347 * git grep pathspecs are somewhat different from diff-tree pathspecs;
 348 * pathname wildcards are allowed.
 349 */
 350static int pathspec_matches(const char **paths, const char *name, int max_depth)
 351{
 352        int namelen, i;
 353        if (!paths || !*paths)
 354                return accept_subdir(name, max_depth);
 355        namelen = strlen(name);
 356        for (i = 0; paths[i]; i++) {
 357                const char *match = paths[i];
 358                int matchlen = strlen(match);
 359                const char *cp, *meta;
 360
 361                if (is_subdir(name, namelen, match, matchlen, max_depth))
 362                        return 1;
 363                if (!fnmatch(match, name, 0))
 364                        return 1;
 365                if (name[namelen-1] != '/')
 366                        continue;
 367
 368                /* We are being asked if the directory ("name") is worth
 369                 * descending into.
 370                 *
 371                 * Find the longest leading directory name that does
 372                 * not have metacharacter in the pathspec; the name
 373                 * we are looking at must overlap with that directory.
 374                 */
 375                for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
 376                        char ch = *cp;
 377                        if (ch == '*' || ch == '[' || ch == '?') {
 378                                meta = cp;
 379                                break;
 380                        }
 381                }
 382                if (!meta)
 383                        meta = cp; /* fully literal */
 384
 385                if (namelen <= meta - match) {
 386                        /* Looking at "Documentation/" and
 387                         * the pattern says "Documentation/howto/", or
 388                         * "Documentation/diff*.txt".  The name we
 389                         * have should match prefix.
 390                         */
 391                        if (!memcmp(match, name, namelen))
 392                                return 1;
 393                        continue;
 394                }
 395
 396                if (meta - match < namelen) {
 397                        /* Looking at "Documentation/howto/" and
 398                         * the pattern says "Documentation/h*";
 399                         * match up to "Do.../h"; this avoids descending
 400                         * into "Documentation/technical/".
 401                         */
 402                        if (!memcmp(match, name, meta - match))
 403                                return 1;
 404                        continue;
 405                }
 406        }
 407        return 0;
 408}
 409
 410static void *load_sha1(const unsigned char *sha1, unsigned long *size,
 411                       const char *name)
 412{
 413        enum object_type type;
 414        char *data;
 415
 416        read_sha1_lock();
 417        data = read_sha1_file(sha1, &type, size);
 418        read_sha1_unlock();
 419
 420        if (!data)
 421                error("'%s': unable to read %s", name, sha1_to_hex(sha1));
 422
 423        return data;
 424}
 425
 426static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
 427                     const char *filename, int tree_name_len)
 428{
 429        struct strbuf pathbuf = STRBUF_INIT;
 430        char *name;
 431
 432        if (opt->relative && opt->prefix_length) {
 433                quote_path_relative(filename + tree_name_len, -1, &pathbuf,
 434                                    opt->prefix);
 435                strbuf_insert(&pathbuf, 0, filename, tree_name_len);
 436        } else {
 437                strbuf_addstr(&pathbuf, filename);
 438        }
 439
 440        name = strbuf_detach(&pathbuf, NULL);
 441
 442#ifndef NO_PTHREADS
 443        if (use_threads) {
 444                grep_sha1_async(opt, name, sha1);
 445                return 0;
 446        } else
 447#endif
 448        {
 449                int hit;
 450                unsigned long sz;
 451                void *data = load_sha1(sha1, &sz, name);
 452                if (!data)
 453                        hit = 0;
 454                else
 455                        hit = grep_buffer(opt, name, data, sz);
 456
 457                free(data);
 458                free(name);
 459                return hit;
 460        }
 461}
 462
 463static void *load_file(const char *filename, size_t *sz)
 464{
 465        struct stat st;
 466        char *data;
 467        int i;
 468
 469        if (lstat(filename, &st) < 0) {
 470        err_ret:
 471                if (errno != ENOENT)
 472                        error("'%s': %s", filename, strerror(errno));
 473                return 0;
 474        }
 475        if (!S_ISREG(st.st_mode))
 476                return 0;
 477        *sz = xsize_t(st.st_size);
 478        i = open(filename, O_RDONLY);
 479        if (i < 0)
 480                goto err_ret;
 481        data = xmalloc(*sz + 1);
 482        if (st.st_size != read_in_full(i, data, *sz)) {
 483                error("'%s': short read %s", filename, strerror(errno));
 484                close(i);
 485                free(data);
 486                return 0;
 487        }
 488        close(i);
 489        data[*sz] = 0;
 490        return data;
 491}
 492
 493static int grep_file(struct grep_opt *opt, const char *filename)
 494{
 495        struct strbuf buf = STRBUF_INIT;
 496        char *name;
 497
 498        if (opt->relative && opt->prefix_length)
 499                quote_path_relative(filename, -1, &buf, opt->prefix);
 500        else
 501                strbuf_addstr(&buf, filename);
 502        name = strbuf_detach(&buf, NULL);
 503
 504#ifndef NO_PTHREADS
 505        if (use_threads) {
 506                grep_file_async(opt, name, filename);
 507                return 0;
 508        } else
 509#endif
 510        {
 511                int hit;
 512                size_t sz;
 513                void *data = load_file(filename, &sz);
 514                if (!data)
 515                        hit = 0;
 516                else
 517                        hit = grep_buffer(opt, name, data, sz);
 518
 519                free(data);
 520                free(name);
 521                return hit;
 522        }
 523}
 524
 525static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
 526{
 527        int hit = 0;
 528        int nr;
 529        read_cache();
 530
 531        for (nr = 0; nr < active_nr; nr++) {
 532                struct cache_entry *ce = active_cache[nr];
 533                if (!S_ISREG(ce->ce_mode))
 534                        continue;
 535                if (!pathspec_matches(paths, ce->name, opt->max_depth))
 536                        continue;
 537                /*
 538                 * If CE_VALID is on, we assume worktree file and its cache entry
 539                 * are identical, even if worktree file has been modified, so use
 540                 * cache version instead
 541                 */
 542                if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
 543                        if (ce_stage(ce))
 544                                continue;
 545                        hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
 546                }
 547                else
 548                        hit |= grep_file(opt, ce->name);
 549                if (ce_stage(ce)) {
 550                        do {
 551                                nr++;
 552                        } while (nr < active_nr &&
 553                                 !strcmp(ce->name, active_cache[nr]->name));
 554                        nr--; /* compensate for loop control */
 555                }
 556                if (hit && opt->status_only)
 557                        break;
 558        }
 559        free_grep_patterns(opt);
 560        return hit;
 561}
 562
 563static int grep_tree(struct grep_opt *opt, const char **paths,
 564                     struct tree_desc *tree,
 565                     const char *tree_name, const char *base)
 566{
 567        int len;
 568        int hit = 0;
 569        struct name_entry entry;
 570        char *down;
 571        int tn_len = strlen(tree_name);
 572        struct strbuf pathbuf;
 573
 574        strbuf_init(&pathbuf, PATH_MAX + tn_len);
 575
 576        if (tn_len) {
 577                strbuf_add(&pathbuf, tree_name, tn_len);
 578                strbuf_addch(&pathbuf, ':');
 579                tn_len = pathbuf.len;
 580        }
 581        strbuf_addstr(&pathbuf, base);
 582        len = pathbuf.len;
 583
 584        while (tree_entry(tree, &entry)) {
 585                int te_len = tree_entry_len(entry.path, entry.sha1);
 586                pathbuf.len = len;
 587                strbuf_add(&pathbuf, entry.path, te_len);
 588
 589                if (S_ISDIR(entry.mode))
 590                        /* Match "abc/" against pathspec to
 591                         * decide if we want to descend into "abc"
 592                         * directory.
 593                         */
 594                        strbuf_addch(&pathbuf, '/');
 595
 596                down = pathbuf.buf + tn_len;
 597                if (!pathspec_matches(paths, down, opt->max_depth))
 598                        ;
 599                else if (S_ISREG(entry.mode))
 600                        hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
 601                else if (S_ISDIR(entry.mode)) {
 602                        enum object_type type;
 603                        struct tree_desc sub;
 604                        void *data;
 605                        unsigned long size;
 606
 607                        read_sha1_lock();
 608                        data = read_sha1_file(entry.sha1, &type, &size);
 609                        read_sha1_unlock();
 610
 611                        if (!data)
 612                                die("unable to read tree (%s)",
 613                                    sha1_to_hex(entry.sha1));
 614                        init_tree_desc(&sub, data, size);
 615                        hit |= grep_tree(opt, paths, &sub, tree_name, down);
 616                        free(data);
 617                }
 618                if (hit && opt->status_only)
 619                        break;
 620        }
 621        strbuf_release(&pathbuf);
 622        return hit;
 623}
 624
 625static int grep_object(struct grep_opt *opt, const char **paths,
 626                       struct object *obj, const char *name)
 627{
 628        if (obj->type == OBJ_BLOB)
 629                return grep_sha1(opt, obj->sha1, name, 0);
 630        if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
 631                struct tree_desc tree;
 632                void *data;
 633                unsigned long size;
 634                int hit;
 635
 636                read_sha1_lock();
 637                data = read_object_with_reference(obj->sha1, tree_type,
 638                                                  &size, NULL);
 639                read_sha1_unlock();
 640
 641                if (!data)
 642                        die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
 643                init_tree_desc(&tree, data, size);
 644                hit = grep_tree(opt, paths, &tree, name, "");
 645                free(data);
 646                return hit;
 647        }
 648        die("unable to grep from object of type %s", typename(obj->type));
 649}
 650
 651static int grep_directory(struct grep_opt *opt, const char **paths)
 652{
 653        struct dir_struct dir;
 654        int i, hit = 0;
 655
 656        memset(&dir, 0, sizeof(dir));
 657        setup_standard_excludes(&dir);
 658
 659        fill_directory(&dir, paths);
 660        for (i = 0; i < dir.nr; i++) {
 661                hit |= grep_file(opt, dir.entries[i]->name);
 662                if (hit && opt->status_only)
 663                        break;
 664        }
 665        free_grep_patterns(opt);
 666        return hit;
 667}
 668
 669static int context_callback(const struct option *opt, const char *arg,
 670                            int unset)
 671{
 672        struct grep_opt *grep_opt = opt->value;
 673        int value;
 674        const char *endp;
 675
 676        if (unset) {
 677                grep_opt->pre_context = grep_opt->post_context = 0;
 678                return 0;
 679        }
 680        value = strtol(arg, (char **)&endp, 10);
 681        if (*endp) {
 682                return error("switch `%c' expects a numerical value",
 683                             opt->short_name);
 684        }
 685        grep_opt->pre_context = grep_opt->post_context = value;
 686        return 0;
 687}
 688
 689static int file_callback(const struct option *opt, const char *arg, int unset)
 690{
 691        struct grep_opt *grep_opt = opt->value;
 692        FILE *patterns;
 693        int lno = 0;
 694        struct strbuf sb = STRBUF_INIT;
 695
 696        patterns = fopen(arg, "r");
 697        if (!patterns)
 698                die_errno("cannot open '%s'", arg);
 699        while (strbuf_getline(&sb, patterns, '\n') == 0) {
 700                /* ignore empty line like grep does */
 701                if (sb.len == 0)
 702                        continue;
 703                append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
 704                                    ++lno, GREP_PATTERN);
 705        }
 706        fclose(patterns);
 707        strbuf_release(&sb);
 708        return 0;
 709}
 710
 711static int not_callback(const struct option *opt, const char *arg, int unset)
 712{
 713        struct grep_opt *grep_opt = opt->value;
 714        append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
 715        return 0;
 716}
 717
 718static int and_callback(const struct option *opt, const char *arg, int unset)
 719{
 720        struct grep_opt *grep_opt = opt->value;
 721        append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
 722        return 0;
 723}
 724
 725static int open_callback(const struct option *opt, const char *arg, int unset)
 726{
 727        struct grep_opt *grep_opt = opt->value;
 728        append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
 729        return 0;
 730}
 731
 732static int close_callback(const struct option *opt, const char *arg, int unset)
 733{
 734        struct grep_opt *grep_opt = opt->value;
 735        append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
 736        return 0;
 737}
 738
 739static int pattern_callback(const struct option *opt, const char *arg,
 740                            int unset)
 741{
 742        struct grep_opt *grep_opt = opt->value;
 743        append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
 744        return 0;
 745}
 746
 747static int help_callback(const struct option *opt, const char *arg, int unset)
 748{
 749        return -1;
 750}
 751
 752int cmd_grep(int argc, const char **argv, const char *prefix)
 753{
 754        int hit = 0;
 755        int cached = 0;
 756        int seen_dashdash = 0;
 757        int external_grep_allowed__ignored;
 758        struct grep_opt opt;
 759        struct object_array list = { 0, 0, NULL };
 760        const char **paths = NULL;
 761        int i;
 762        int dummy;
 763        int nongit = 0, use_index = 1;
 764        struct option options[] = {
 765                OPT_BOOLEAN(0, "cached", &cached,
 766                        "search in index instead of in the work tree"),
 767                OPT_BOOLEAN(0, "index", &use_index,
 768                        "--no-index finds in contents not managed by git"),
 769                OPT_GROUP(""),
 770                OPT_BOOLEAN('v', "invert-match", &opt.invert,
 771                        "show non-matching lines"),
 772                OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
 773                        "case insensitive matching"),
 774                OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
 775                        "match patterns only at word boundaries"),
 776                OPT_SET_INT('a', "text", &opt.binary,
 777                        "process binary files as text", GREP_BINARY_TEXT),
 778                OPT_SET_INT('I', NULL, &opt.binary,
 779                        "don't match patterns in binary files",
 780                        GREP_BINARY_NOMATCH),
 781                { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
 782                        "descend at most <depth> levels", PARSE_OPT_NONEG,
 783                        NULL, 1 },
 784                OPT_GROUP(""),
 785                OPT_BIT('E', "extended-regexp", &opt.regflags,
 786                        "use extended POSIX regular expressions", REG_EXTENDED),
 787                OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
 788                        "use basic POSIX regular expressions (default)",
 789                        REG_EXTENDED),
 790                OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
 791                        "interpret patterns as fixed strings"),
 792                OPT_GROUP(""),
 793                OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
 794                OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
 795                OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
 796                OPT_NEGBIT(0, "full-name", &opt.relative,
 797                        "show filenames relative to top directory", 1),
 798                OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
 799                        "show only filenames instead of matching lines"),
 800                OPT_BOOLEAN(0, "name-only", &opt.name_only,
 801                        "synonym for --files-with-matches"),
 802                OPT_BOOLEAN('L', "files-without-match",
 803                        &opt.unmatch_name_only,
 804                        "show only the names of files without match"),
 805                OPT_BOOLEAN('z', "null", &opt.null_following_name,
 806                        "print NUL after filenames"),
 807                OPT_BOOLEAN('c', "count", &opt.count,
 808                        "show the number of matches instead of matching lines"),
 809                OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
 810                OPT_GROUP(""),
 811                OPT_CALLBACK('C', NULL, &opt, "n",
 812                        "show <n> context lines before and after matches",
 813                        context_callback),
 814                OPT_INTEGER('B', NULL, &opt.pre_context,
 815                        "show <n> context lines before matches"),
 816                OPT_INTEGER('A', NULL, &opt.post_context,
 817                        "show <n> context lines after matches"),
 818                OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
 819                        context_callback),
 820                OPT_BOOLEAN('p', "show-function", &opt.funcname,
 821                        "show a line with the function name before matches"),
 822                OPT_GROUP(""),
 823                OPT_CALLBACK('f', NULL, &opt, "file",
 824                        "read patterns from file", file_callback),
 825                { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
 826                        "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
 827                { OPTION_CALLBACK, 0, "and", &opt, NULL,
 828                  "combine patterns specified with -e",
 829                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
 830                OPT_BOOLEAN(0, "or", &dummy, ""),
 831                { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
 832                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
 833                { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
 834                  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
 835                  open_callback },
 836                { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
 837                  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
 838                  close_callback },
 839                OPT_BOOLEAN('q', "quick", &opt.status_only,
 840                            "indicate hit with exit status without output"),
 841                OPT_BOOLEAN(0, "all-match", &opt.all_match,
 842                        "show only matches from files that match all patterns"),
 843                OPT_GROUP(""),
 844                OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
 845                            "allow calling of grep(1) (ignored by this build)"),
 846                { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
 847                  PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
 848                OPT_END()
 849        };
 850
 851        prefix = setup_git_directory_gently(&nongit);
 852
 853        /*
 854         * 'git grep -h', unlike 'git grep -h <pattern>', is a request
 855         * to show usage information and exit.
 856         */
 857        if (argc == 2 && !strcmp(argv[1], "-h"))
 858                usage_with_options(grep_usage, options);
 859
 860        memset(&opt, 0, sizeof(opt));
 861        opt.prefix = prefix;
 862        opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
 863        opt.relative = 1;
 864        opt.pathname = 1;
 865        opt.pattern_tail = &opt.pattern_list;
 866        opt.regflags = REG_NEWLINE;
 867        opt.max_depth = -1;
 868
 869        strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
 870        opt.color = -1;
 871        git_config(grep_config, &opt);
 872        if (opt.color == -1)
 873                opt.color = git_use_color_default;
 874
 875        /*
 876         * If there is no -- then the paths must exist in the working
 877         * tree.  If there is no explicit pattern specified with -e or
 878         * -f, we take the first unrecognized non option to be the
 879         * pattern, but then what follows it must be zero or more
 880         * valid refs up to the -- (if exists), and then existing
 881         * paths.  If there is an explicit pattern, then the first
 882         * unrecognized non option is the beginning of the refs list
 883         * that continues up to the -- (if exists), and then paths.
 884         */
 885        argc = parse_options(argc, argv, prefix, options, grep_usage,
 886                             PARSE_OPT_KEEP_DASHDASH |
 887                             PARSE_OPT_STOP_AT_NON_OPTION |
 888                             PARSE_OPT_NO_INTERNAL_HELP);
 889
 890        if (use_index && nongit)
 891                /* die the same way as if we did it at the beginning */
 892                setup_git_directory();
 893
 894        /* First unrecognized non-option token */
 895        if (argc > 0 && !opt.pattern_list) {
 896                append_grep_pattern(&opt, argv[0], "command line", 0,
 897                                    GREP_PATTERN);
 898                argv++;
 899                argc--;
 900        }
 901
 902        if (!opt.pattern_list)
 903                die("no pattern given.");
 904        if (!opt.fixed && opt.ignore_case)
 905                opt.regflags |= REG_ICASE;
 906        if ((opt.regflags != REG_NEWLINE) && opt.fixed)
 907                die("cannot mix --fixed-strings and regexp");
 908
 909#ifndef NO_PTHREADS
 910        if (online_cpus() == 1 || !grep_threads_ok(&opt))
 911                use_threads = 0;
 912
 913        if (use_threads)
 914                start_threads(&opt);
 915#else
 916        use_threads = 0;
 917#endif
 918
 919        compile_grep_patterns(&opt);
 920
 921        /* Check revs and then paths */
 922        for (i = 0; i < argc; i++) {
 923                const char *arg = argv[i];
 924                unsigned char sha1[20];
 925                /* Is it a rev? */
 926                if (!get_sha1(arg, sha1)) {
 927                        struct object *object = parse_object(sha1);
 928                        if (!object)
 929                                die("bad object %s", arg);
 930                        add_object_array(object, arg, &list);
 931                        continue;
 932                }
 933                if (!strcmp(arg, "--")) {
 934                        i++;
 935                        seen_dashdash = 1;
 936                }
 937                break;
 938        }
 939
 940        /* The rest are paths */
 941        if (!seen_dashdash) {
 942                int j;
 943                for (j = i; j < argc; j++)
 944                        verify_filename(prefix, argv[j]);
 945        }
 946
 947        if (i < argc)
 948                paths = get_pathspec(prefix, argv + i);
 949        else if (prefix) {
 950                paths = xcalloc(2, sizeof(const char *));
 951                paths[0] = prefix;
 952                paths[1] = NULL;
 953        }
 954
 955        if (!use_index) {
 956                int hit;
 957                if (cached)
 958                        die("--cached cannot be used with --no-index.");
 959                if (list.nr)
 960                        die("--no-index cannot be used with revs.");
 961                hit = grep_directory(&opt, paths);
 962                if (use_threads)
 963                        hit |= wait_all();
 964                return !hit;
 965        }
 966
 967        if (!list.nr) {
 968                int hit;
 969                if (!cached)
 970                        setup_work_tree();
 971
 972                hit = grep_cache(&opt, paths, cached);
 973                if (use_threads)
 974                        hit |= wait_all();
 975                return !hit;
 976        }
 977
 978        if (cached)
 979                die("both --cached and trees are given.");
 980
 981        for (i = 0; i < list.nr; i++) {
 982                struct object *real_obj;
 983                real_obj = deref_tag(list.objects[i].item, NULL, 0);
 984                if (grep_object(&opt, paths, real_obj, list.objects[i].name)) {
 985                        hit = 1;
 986                        if (opt.status_only)
 987                                break;
 988                }
 989        }
 990
 991        if (use_threads)
 992                hit |= wait_all();
 993        free_grep_patterns(&opt);
 994        return !hit;
 995}