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