builtin / grep.con commit grep: optionally recurse into submodules (0281e48)
   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 "string-list.h"
  15#include "run-command.h"
  16#include "userdiff.h"
  17#include "grep.h"
  18#include "quote.h"
  19#include "dir.h"
  20#include "pathspec.h"
  21#include "submodule.h"
  22
  23static char const * const grep_usage[] = {
  24        N_("git grep [<options>] [-e] <pattern> [<rev>...] [[--] <path>...]"),
  25        NULL
  26};
  27
  28static const char *super_prefix;
  29static int recurse_submodules;
  30static struct argv_array submodule_options = ARGV_ARRAY_INIT;
  31
  32static int grep_submodule_launch(struct grep_opt *opt,
  33                                 const struct grep_source *gs);
  34
  35#define GREP_NUM_THREADS_DEFAULT 8
  36static int num_threads;
  37
  38#ifndef NO_PTHREADS
  39static pthread_t *threads;
  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        struct grep_source source;
  47        char done;
  48        struct strbuf out;
  49};
  50
  51/* In the range [todo_done, todo_start) in 'todo' we have work_items
  52 * that have been or are processed by a consumer thread. We haven't
  53 * written the result for these to stdout yet.
  54 *
  55 * The work_items in [todo_start, todo_end) are waiting to be picked
  56 * up by a consumer thread.
  57 *
  58 * The ranges are modulo TODO_SIZE.
  59 */
  60#define TODO_SIZE 128
  61static struct work_item todo[TODO_SIZE];
  62static int todo_start;
  63static int todo_end;
  64static int todo_done;
  65
  66/* Has all work items been added? */
  67static int all_work_added;
  68
  69/* This lock protects all the variables above. */
  70static pthread_mutex_t grep_mutex;
  71
  72static inline void grep_lock(void)
  73{
  74        if (num_threads)
  75                pthread_mutex_lock(&grep_mutex);
  76}
  77
  78static inline void grep_unlock(void)
  79{
  80        if (num_threads)
  81                pthread_mutex_unlock(&grep_mutex);
  82}
  83
  84/* Signalled when a new work_item is added to todo. */
  85static pthread_cond_t cond_add;
  86
  87/* Signalled when the result from one work_item is written to
  88 * stdout.
  89 */
  90static pthread_cond_t cond_write;
  91
  92/* Signalled when we are finished with everything. */
  93static pthread_cond_t cond_result;
  94
  95static int skip_first_line;
  96
  97static void add_work(struct grep_opt *opt, enum grep_source_type type,
  98                     const char *name, const char *path, const void *id)
  99{
 100        grep_lock();
 101
 102        while ((todo_end+1) % ARRAY_SIZE(todo) == todo_done) {
 103                pthread_cond_wait(&cond_write, &grep_mutex);
 104        }
 105
 106        grep_source_init(&todo[todo_end].source, type, name, path, id);
 107        if (opt->binary != GREP_BINARY_TEXT)
 108                grep_source_load_driver(&todo[todo_end].source);
 109        todo[todo_end].done = 0;
 110        strbuf_reset(&todo[todo_end].out);
 111        todo_end = (todo_end + 1) % ARRAY_SIZE(todo);
 112
 113        pthread_cond_signal(&cond_add);
 114        grep_unlock();
 115}
 116
 117static struct work_item *get_work(void)
 118{
 119        struct work_item *ret;
 120
 121        grep_lock();
 122        while (todo_start == todo_end && !all_work_added) {
 123                pthread_cond_wait(&cond_add, &grep_mutex);
 124        }
 125
 126        if (todo_start == todo_end && all_work_added) {
 127                ret = NULL;
 128        } else {
 129                ret = &todo[todo_start];
 130                todo_start = (todo_start + 1) % ARRAY_SIZE(todo);
 131        }
 132        grep_unlock();
 133        return ret;
 134}
 135
 136static void work_done(struct work_item *w)
 137{
 138        int old_done;
 139
 140        grep_lock();
 141        w->done = 1;
 142        old_done = todo_done;
 143        for(; todo[todo_done].done && todo_done != todo_start;
 144            todo_done = (todo_done+1) % ARRAY_SIZE(todo)) {
 145                w = &todo[todo_done];
 146                if (w->out.len) {
 147                        const char *p = w->out.buf;
 148                        size_t len = w->out.len;
 149
 150                        /* Skip the leading hunk mark of the first file. */
 151                        if (skip_first_line) {
 152                                while (len) {
 153                                        len--;
 154                                        if (*p++ == '\n')
 155                                                break;
 156                                }
 157                                skip_first_line = 0;
 158                        }
 159
 160                        write_or_die(1, p, len);
 161                }
 162                grep_source_clear(&w->source);
 163        }
 164
 165        if (old_done != todo_done)
 166                pthread_cond_signal(&cond_write);
 167
 168        if (all_work_added && todo_done == todo_end)
 169                pthread_cond_signal(&cond_result);
 170
 171        grep_unlock();
 172}
 173
 174static void *run(void *arg)
 175{
 176        int hit = 0;
 177        struct grep_opt *opt = arg;
 178
 179        while (1) {
 180                struct work_item *w = get_work();
 181                if (!w)
 182                        break;
 183
 184                opt->output_priv = w;
 185                if (w->source.type == GREP_SOURCE_SUBMODULE)
 186                        hit |= grep_submodule_launch(opt, &w->source);
 187                else
 188                        hit |= grep_source(opt, &w->source);
 189                grep_source_clear_data(&w->source);
 190                work_done(w);
 191        }
 192        free_grep_patterns(arg);
 193        free(arg);
 194
 195        return (void*) (intptr_t) hit;
 196}
 197
 198static void strbuf_out(struct grep_opt *opt, const void *buf, size_t size)
 199{
 200        struct work_item *w = opt->output_priv;
 201        strbuf_add(&w->out, buf, size);
 202}
 203
 204static void start_threads(struct grep_opt *opt)
 205{
 206        int i;
 207
 208        pthread_mutex_init(&grep_mutex, NULL);
 209        pthread_mutex_init(&grep_read_mutex, NULL);
 210        pthread_mutex_init(&grep_attr_mutex, NULL);
 211        pthread_cond_init(&cond_add, NULL);
 212        pthread_cond_init(&cond_write, NULL);
 213        pthread_cond_init(&cond_result, NULL);
 214        grep_use_locks = 1;
 215
 216        for (i = 0; i < ARRAY_SIZE(todo); i++) {
 217                strbuf_init(&todo[i].out, 0);
 218        }
 219
 220        threads = xcalloc(num_threads, sizeof(*threads));
 221        for (i = 0; i < num_threads; i++) {
 222                int err;
 223                struct grep_opt *o = grep_opt_dup(opt);
 224                o->output = strbuf_out;
 225                o->debug = 0;
 226                compile_grep_patterns(o);
 227                err = pthread_create(&threads[i], NULL, run, o);
 228
 229                if (err)
 230                        die(_("grep: failed to create thread: %s"),
 231                            strerror(err));
 232        }
 233}
 234
 235static int wait_all(void)
 236{
 237        int hit = 0;
 238        int i;
 239
 240        grep_lock();
 241        all_work_added = 1;
 242
 243        /* Wait until all work is done. */
 244        while (todo_done != todo_end)
 245                pthread_cond_wait(&cond_result, &grep_mutex);
 246
 247        /* Wake up all the consumer threads so they can see that there
 248         * is no more work to do.
 249         */
 250        pthread_cond_broadcast(&cond_add);
 251        grep_unlock();
 252
 253        for (i = 0; i < num_threads; i++) {
 254                void *h;
 255                pthread_join(threads[i], &h);
 256                hit |= (int) (intptr_t) h;
 257        }
 258
 259        free(threads);
 260
 261        pthread_mutex_destroy(&grep_mutex);
 262        pthread_mutex_destroy(&grep_read_mutex);
 263        pthread_mutex_destroy(&grep_attr_mutex);
 264        pthread_cond_destroy(&cond_add);
 265        pthread_cond_destroy(&cond_write);
 266        pthread_cond_destroy(&cond_result);
 267        grep_use_locks = 0;
 268
 269        return hit;
 270}
 271#else /* !NO_PTHREADS */
 272
 273static int wait_all(void)
 274{
 275        return 0;
 276}
 277#endif
 278
 279static int grep_cmd_config(const char *var, const char *value, void *cb)
 280{
 281        int st = grep_config(var, value, cb);
 282        if (git_color_default_config(var, value, cb) < 0)
 283                st = -1;
 284
 285        if (!strcmp(var, "grep.threads")) {
 286                num_threads = git_config_int(var, value);
 287                if (num_threads < 0)
 288                        die(_("invalid number of threads specified (%d) for %s"),
 289                            num_threads, var);
 290        }
 291
 292        return st;
 293}
 294
 295static void *lock_and_read_sha1_file(const unsigned char *sha1, enum object_type *type, unsigned long *size)
 296{
 297        void *data;
 298
 299        grep_read_lock();
 300        data = read_sha1_file(sha1, type, size);
 301        grep_read_unlock();
 302        return data;
 303}
 304
 305static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1,
 306                     const char *filename, int tree_name_len,
 307                     const char *path)
 308{
 309        struct strbuf pathbuf = STRBUF_INIT;
 310
 311        if (opt->relative && opt->prefix_length) {
 312                quote_path_relative(filename + tree_name_len, opt->prefix, &pathbuf);
 313                strbuf_insert(&pathbuf, 0, filename, tree_name_len);
 314        } else if (super_prefix) {
 315                strbuf_add(&pathbuf, filename, tree_name_len);
 316                strbuf_addstr(&pathbuf, super_prefix);
 317                strbuf_addstr(&pathbuf, filename + tree_name_len);
 318        } else {
 319                strbuf_addstr(&pathbuf, filename);
 320        }
 321
 322#ifndef NO_PTHREADS
 323        if (num_threads) {
 324                add_work(opt, GREP_SOURCE_SHA1, pathbuf.buf, path, sha1);
 325                strbuf_release(&pathbuf);
 326                return 0;
 327        } else
 328#endif
 329        {
 330                struct grep_source gs;
 331                int hit;
 332
 333                grep_source_init(&gs, GREP_SOURCE_SHA1, pathbuf.buf, path, sha1);
 334                strbuf_release(&pathbuf);
 335                hit = grep_source(opt, &gs);
 336
 337                grep_source_clear(&gs);
 338                return hit;
 339        }
 340}
 341
 342static int grep_file(struct grep_opt *opt, const char *filename)
 343{
 344        struct strbuf buf = STRBUF_INIT;
 345
 346        if (opt->relative && opt->prefix_length) {
 347                quote_path_relative(filename, opt->prefix, &buf);
 348        } else {
 349                if (super_prefix)
 350                        strbuf_addstr(&buf, super_prefix);
 351                strbuf_addstr(&buf, filename);
 352        }
 353
 354#ifndef NO_PTHREADS
 355        if (num_threads) {
 356                add_work(opt, GREP_SOURCE_FILE, buf.buf, filename, filename);
 357                strbuf_release(&buf);
 358                return 0;
 359        } else
 360#endif
 361        {
 362                struct grep_source gs;
 363                int hit;
 364
 365                grep_source_init(&gs, GREP_SOURCE_FILE, buf.buf, filename, filename);
 366                strbuf_release(&buf);
 367                hit = grep_source(opt, &gs);
 368
 369                grep_source_clear(&gs);
 370                return hit;
 371        }
 372}
 373
 374static void append_path(struct grep_opt *opt, const void *data, size_t len)
 375{
 376        struct string_list *path_list = opt->output_priv;
 377
 378        if (len == 1 && *(const char *)data == '\0')
 379                return;
 380        string_list_append(path_list, xstrndup(data, len));
 381}
 382
 383static void run_pager(struct grep_opt *opt, const char *prefix)
 384{
 385        struct string_list *path_list = opt->output_priv;
 386        struct child_process child = CHILD_PROCESS_INIT;
 387        int i, status;
 388
 389        for (i = 0; i < path_list->nr; i++)
 390                argv_array_push(&child.args, path_list->items[i].string);
 391        child.dir = prefix;
 392        child.use_shell = 1;
 393
 394        status = run_command(&child);
 395        if (status)
 396                exit(status);
 397}
 398
 399static void compile_submodule_options(const struct grep_opt *opt,
 400                                      const struct pathspec *pathspec,
 401                                      int cached, int untracked,
 402                                      int opt_exclude, int use_index,
 403                                      int pattern_type_arg)
 404{
 405        struct grep_pat *pattern;
 406        int i;
 407
 408        if (recurse_submodules)
 409                argv_array_push(&submodule_options, "--recurse-submodules");
 410
 411        if (cached)
 412                argv_array_push(&submodule_options, "--cached");
 413        if (!use_index)
 414                argv_array_push(&submodule_options, "--no-index");
 415        if (untracked)
 416                argv_array_push(&submodule_options, "--untracked");
 417        if (opt_exclude > 0)
 418                argv_array_push(&submodule_options, "--exclude-standard");
 419
 420        if (opt->invert)
 421                argv_array_push(&submodule_options, "-v");
 422        if (opt->ignore_case)
 423                argv_array_push(&submodule_options, "-i");
 424        if (opt->word_regexp)
 425                argv_array_push(&submodule_options, "-w");
 426        switch (opt->binary) {
 427        case GREP_BINARY_NOMATCH:
 428                argv_array_push(&submodule_options, "-I");
 429                break;
 430        case GREP_BINARY_TEXT:
 431                argv_array_push(&submodule_options, "-a");
 432                break;
 433        default:
 434                break;
 435        }
 436        if (opt->allow_textconv)
 437                argv_array_push(&submodule_options, "--textconv");
 438        if (opt->max_depth != -1)
 439                argv_array_pushf(&submodule_options, "--max-depth=%d",
 440                                 opt->max_depth);
 441        if (opt->linenum)
 442                argv_array_push(&submodule_options, "-n");
 443        if (!opt->pathname)
 444                argv_array_push(&submodule_options, "-h");
 445        if (!opt->relative)
 446                argv_array_push(&submodule_options, "--full-name");
 447        if (opt->name_only)
 448                argv_array_push(&submodule_options, "-l");
 449        if (opt->unmatch_name_only)
 450                argv_array_push(&submodule_options, "-L");
 451        if (opt->null_following_name)
 452                argv_array_push(&submodule_options, "-z");
 453        if (opt->count)
 454                argv_array_push(&submodule_options, "-c");
 455        if (opt->file_break)
 456                argv_array_push(&submodule_options, "--break");
 457        if (opt->heading)
 458                argv_array_push(&submodule_options, "--heading");
 459        if (opt->pre_context)
 460                argv_array_pushf(&submodule_options, "--before-context=%d",
 461                                 opt->pre_context);
 462        if (opt->post_context)
 463                argv_array_pushf(&submodule_options, "--after-context=%d",
 464                                 opt->post_context);
 465        if (opt->funcname)
 466                argv_array_push(&submodule_options, "-p");
 467        if (opt->funcbody)
 468                argv_array_push(&submodule_options, "-W");
 469        if (opt->all_match)
 470                argv_array_push(&submodule_options, "--all-match");
 471        if (opt->debug)
 472                argv_array_push(&submodule_options, "--debug");
 473        if (opt->status_only)
 474                argv_array_push(&submodule_options, "-q");
 475
 476        switch (pattern_type_arg) {
 477        case GREP_PATTERN_TYPE_BRE:
 478                argv_array_push(&submodule_options, "-G");
 479                break;
 480        case GREP_PATTERN_TYPE_ERE:
 481                argv_array_push(&submodule_options, "-E");
 482                break;
 483        case GREP_PATTERN_TYPE_FIXED:
 484                argv_array_push(&submodule_options, "-F");
 485                break;
 486        case GREP_PATTERN_TYPE_PCRE:
 487                argv_array_push(&submodule_options, "-P");
 488                break;
 489        case GREP_PATTERN_TYPE_UNSPECIFIED:
 490                break;
 491        }
 492
 493        for (pattern = opt->pattern_list; pattern != NULL;
 494             pattern = pattern->next) {
 495                switch (pattern->token) {
 496                case GREP_PATTERN:
 497                        argv_array_pushf(&submodule_options, "-e%s",
 498                                         pattern->pattern);
 499                        break;
 500                case GREP_AND:
 501                case GREP_OPEN_PAREN:
 502                case GREP_CLOSE_PAREN:
 503                case GREP_NOT:
 504                case GREP_OR:
 505                        argv_array_push(&submodule_options, pattern->pattern);
 506                        break;
 507                /* BODY and HEAD are not used by git-grep */
 508                case GREP_PATTERN_BODY:
 509                case GREP_PATTERN_HEAD:
 510                        break;
 511                }
 512        }
 513
 514        /*
 515         * Limit number of threads for child process to use.
 516         * This is to prevent potential fork-bomb behavior of git-grep as each
 517         * submodule process has its own thread pool.
 518         */
 519        argv_array_pushf(&submodule_options, "--threads=%d",
 520                         (num_threads + 1) / 2);
 521
 522        /* Add Pathspecs */
 523        argv_array_push(&submodule_options, "--");
 524        for (i = 0; i < pathspec->nr; i++)
 525                argv_array_push(&submodule_options,
 526                                pathspec->items[i].original);
 527}
 528
 529/*
 530 * Launch child process to grep contents of a submodule
 531 */
 532static int grep_submodule_launch(struct grep_opt *opt,
 533                                 const struct grep_source *gs)
 534{
 535        struct child_process cp = CHILD_PROCESS_INIT;
 536        int status, i;
 537        struct work_item *w = opt->output_priv;
 538
 539        prepare_submodule_repo_env(&cp.env_array);
 540
 541        /* Add super prefix */
 542        argv_array_pushf(&cp.args, "--super-prefix=%s%s/",
 543                         super_prefix ? super_prefix : "",
 544                         gs->name);
 545        argv_array_push(&cp.args, "grep");
 546
 547        /* Add options */
 548        for (i = 0; i < submodule_options.argc; i++)
 549                argv_array_push(&cp.args, submodule_options.argv[i]);
 550
 551        cp.git_cmd = 1;
 552        cp.dir = gs->path;
 553
 554        /*
 555         * Capture output to output buffer and check the return code from the
 556         * child process.  A '0' indicates a hit, a '1' indicates no hit and
 557         * anything else is an error.
 558         */
 559        status = capture_command(&cp, &w->out, 0);
 560        if (status && (status != 1)) {
 561                /* flush the buffer */
 562                write_or_die(1, w->out.buf, w->out.len);
 563                die("process for submodule '%s' failed with exit code: %d",
 564                    gs->name, status);
 565        }
 566
 567        /* invert the return code to make a hit equal to 1 */
 568        return !status;
 569}
 570
 571/*
 572 * Prep grep structures for a submodule grep
 573 * sha1: the sha1 of the submodule or NULL if using the working tree
 574 * filename: name of the submodule including tree name of parent
 575 * path: location of the submodule
 576 */
 577static int grep_submodule(struct grep_opt *opt, const unsigned char *sha1,
 578                          const char *filename, const char *path)
 579{
 580        if (!is_submodule_initialized(path))
 581                return 0;
 582        if (!is_submodule_populated(path))
 583                return 0;
 584
 585#ifndef NO_PTHREADS
 586        if (num_threads) {
 587                add_work(opt, GREP_SOURCE_SUBMODULE, filename, path, sha1);
 588                return 0;
 589        } else
 590#endif
 591        {
 592                struct work_item w;
 593                int hit;
 594
 595                grep_source_init(&w.source, GREP_SOURCE_SUBMODULE,
 596                                 filename, path, sha1);
 597                strbuf_init(&w.out, 0);
 598                opt->output_priv = &w;
 599                hit = grep_submodule_launch(opt, &w.source);
 600
 601                write_or_die(1, w.out.buf, w.out.len);
 602
 603                grep_source_clear(&w.source);
 604                strbuf_release(&w.out);
 605                return hit;
 606        }
 607}
 608
 609static int grep_cache(struct grep_opt *opt, const struct pathspec *pathspec,
 610                      int cached)
 611{
 612        int hit = 0;
 613        int nr;
 614        struct strbuf name = STRBUF_INIT;
 615        int name_base_len = 0;
 616        if (super_prefix) {
 617                name_base_len = strlen(super_prefix);
 618                strbuf_addstr(&name, super_prefix);
 619        }
 620
 621        read_cache();
 622
 623        for (nr = 0; nr < active_nr; nr++) {
 624                const struct cache_entry *ce = active_cache[nr];
 625                strbuf_setlen(&name, name_base_len);
 626                strbuf_addstr(&name, ce->name);
 627
 628                if (S_ISREG(ce->ce_mode) &&
 629                    match_pathspec(pathspec, name.buf, name.len, 0, NULL,
 630                                   S_ISDIR(ce->ce_mode) ||
 631                                   S_ISGITLINK(ce->ce_mode))) {
 632                        /*
 633                         * If CE_VALID is on, we assume worktree file and its
 634                         * cache entry are identical, even if worktree file has
 635                         * been modified, so use cache version instead
 636                         */
 637                        if (cached || (ce->ce_flags & CE_VALID) ||
 638                            ce_skip_worktree(ce)) {
 639                                if (ce_stage(ce) || ce_intent_to_add(ce))
 640                                        continue;
 641                                hit |= grep_sha1(opt, ce->oid.hash, ce->name,
 642                                                 0, ce->name);
 643                        } else {
 644                                hit |= grep_file(opt, ce->name);
 645                        }
 646                } else if (recurse_submodules && S_ISGITLINK(ce->ce_mode) &&
 647                           submodule_path_match(pathspec, name.buf, NULL)) {
 648                        hit |= grep_submodule(opt, NULL, ce->name, ce->name);
 649                } else {
 650                        continue;
 651                }
 652
 653                if (ce_stage(ce)) {
 654                        do {
 655                                nr++;
 656                        } while (nr < active_nr &&
 657                                 !strcmp(ce->name, active_cache[nr]->name));
 658                        nr--; /* compensate for loop control */
 659                }
 660                if (hit && opt->status_only)
 661                        break;
 662        }
 663
 664        strbuf_release(&name);
 665        return hit;
 666}
 667
 668static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
 669                     struct tree_desc *tree, struct strbuf *base, int tn_len,
 670                     int check_attr)
 671{
 672        int hit = 0;
 673        enum interesting match = entry_not_interesting;
 674        struct name_entry entry;
 675        int old_baselen = base->len;
 676
 677        while (tree_entry(tree, &entry)) {
 678                int te_len = tree_entry_len(&entry);
 679
 680                if (match != all_entries_interesting) {
 681                        match = tree_entry_interesting(&entry, base, tn_len, pathspec);
 682                        if (match == all_entries_not_interesting)
 683                                break;
 684                        if (match == entry_not_interesting)
 685                                continue;
 686                }
 687
 688                strbuf_add(base, entry.path, te_len);
 689
 690                if (S_ISREG(entry.mode)) {
 691                        hit |= grep_sha1(opt, entry.oid->hash, base->buf, tn_len,
 692                                         check_attr ? base->buf + tn_len : NULL);
 693                }
 694                else if (S_ISDIR(entry.mode)) {
 695                        enum object_type type;
 696                        struct tree_desc sub;
 697                        void *data;
 698                        unsigned long size;
 699
 700                        data = lock_and_read_sha1_file(entry.oid->hash, &type, &size);
 701                        if (!data)
 702                                die(_("unable to read tree (%s)"),
 703                                    oid_to_hex(entry.oid));
 704
 705                        strbuf_addch(base, '/');
 706                        init_tree_desc(&sub, data, size);
 707                        hit |= grep_tree(opt, pathspec, &sub, base, tn_len,
 708                                         check_attr);
 709                        free(data);
 710                }
 711                strbuf_setlen(base, old_baselen);
 712
 713                if (hit && opt->status_only)
 714                        break;
 715        }
 716        return hit;
 717}
 718
 719static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
 720                       struct object *obj, const char *name, const char *path)
 721{
 722        if (obj->type == OBJ_BLOB)
 723                return grep_sha1(opt, obj->oid.hash, name, 0, path);
 724        if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
 725                struct tree_desc tree;
 726                void *data;
 727                unsigned long size;
 728                struct strbuf base;
 729                int hit, len;
 730
 731                grep_read_lock();
 732                data = read_object_with_reference(obj->oid.hash, tree_type,
 733                                                  &size, NULL);
 734                grep_read_unlock();
 735
 736                if (!data)
 737                        die(_("unable to read tree (%s)"), oid_to_hex(&obj->oid));
 738
 739                len = name ? strlen(name) : 0;
 740                strbuf_init(&base, PATH_MAX + len + 1);
 741                if (len) {
 742                        strbuf_add(&base, name, len);
 743                        strbuf_addch(&base, ':');
 744                }
 745                init_tree_desc(&tree, data, size);
 746                hit = grep_tree(opt, pathspec, &tree, &base, base.len,
 747                                obj->type == OBJ_COMMIT);
 748                strbuf_release(&base);
 749                free(data);
 750                return hit;
 751        }
 752        die(_("unable to grep from object of type %s"), typename(obj->type));
 753}
 754
 755static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
 756                        const struct object_array *list)
 757{
 758        unsigned int i;
 759        int hit = 0;
 760        const unsigned int nr = list->nr;
 761
 762        for (i = 0; i < nr; i++) {
 763                struct object *real_obj;
 764                real_obj = deref_tag(list->objects[i].item, NULL, 0);
 765                if (grep_object(opt, pathspec, real_obj, list->objects[i].name, list->objects[i].path)) {
 766                        hit = 1;
 767                        if (opt->status_only)
 768                                break;
 769                }
 770        }
 771        return hit;
 772}
 773
 774static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
 775                          int exc_std, int use_index)
 776{
 777        struct dir_struct dir;
 778        int i, hit = 0;
 779
 780        memset(&dir, 0, sizeof(dir));
 781        if (!use_index)
 782                dir.flags |= DIR_NO_GITLINKS;
 783        if (exc_std)
 784                setup_standard_excludes(&dir);
 785
 786        fill_directory(&dir, pathspec);
 787        for (i = 0; i < dir.nr; i++) {
 788                if (!dir_path_match(dir.entries[i], pathspec, 0, NULL))
 789                        continue;
 790                hit |= grep_file(opt, dir.entries[i]->name);
 791                if (hit && opt->status_only)
 792                        break;
 793        }
 794        return hit;
 795}
 796
 797static int context_callback(const struct option *opt, const char *arg,
 798                            int unset)
 799{
 800        struct grep_opt *grep_opt = opt->value;
 801        int value;
 802        const char *endp;
 803
 804        if (unset) {
 805                grep_opt->pre_context = grep_opt->post_context = 0;
 806                return 0;
 807        }
 808        value = strtol(arg, (char **)&endp, 10);
 809        if (*endp) {
 810                return error(_("switch `%c' expects a numerical value"),
 811                             opt->short_name);
 812        }
 813        grep_opt->pre_context = grep_opt->post_context = value;
 814        return 0;
 815}
 816
 817static int file_callback(const struct option *opt, const char *arg, int unset)
 818{
 819        struct grep_opt *grep_opt = opt->value;
 820        int from_stdin = !strcmp(arg, "-");
 821        FILE *patterns;
 822        int lno = 0;
 823        struct strbuf sb = STRBUF_INIT;
 824
 825        patterns = from_stdin ? stdin : fopen(arg, "r");
 826        if (!patterns)
 827                die_errno(_("cannot open '%s'"), arg);
 828        while (strbuf_getline(&sb, patterns) == 0) {
 829                /* ignore empty line like grep does */
 830                if (sb.len == 0)
 831                        continue;
 832
 833                append_grep_pat(grep_opt, sb.buf, sb.len, arg, ++lno,
 834                                GREP_PATTERN);
 835        }
 836        if (!from_stdin)
 837                fclose(patterns);
 838        strbuf_release(&sb);
 839        return 0;
 840}
 841
 842static int not_callback(const struct option *opt, const char *arg, int unset)
 843{
 844        struct grep_opt *grep_opt = opt->value;
 845        append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
 846        return 0;
 847}
 848
 849static int and_callback(const struct option *opt, const char *arg, int unset)
 850{
 851        struct grep_opt *grep_opt = opt->value;
 852        append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
 853        return 0;
 854}
 855
 856static int open_callback(const struct option *opt, const char *arg, int unset)
 857{
 858        struct grep_opt *grep_opt = opt->value;
 859        append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
 860        return 0;
 861}
 862
 863static int close_callback(const struct option *opt, const char *arg, int unset)
 864{
 865        struct grep_opt *grep_opt = opt->value;
 866        append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
 867        return 0;
 868}
 869
 870static int pattern_callback(const struct option *opt, const char *arg,
 871                            int unset)
 872{
 873        struct grep_opt *grep_opt = opt->value;
 874        append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
 875        return 0;
 876}
 877
 878int cmd_grep(int argc, const char **argv, const char *prefix)
 879{
 880        int hit = 0;
 881        int cached = 0, untracked = 0, opt_exclude = -1;
 882        int seen_dashdash = 0;
 883        int external_grep_allowed__ignored;
 884        const char *show_in_pager = NULL, *default_pager = "dummy";
 885        struct grep_opt opt;
 886        struct object_array list = OBJECT_ARRAY_INIT;
 887        struct pathspec pathspec;
 888        struct string_list path_list = STRING_LIST_INIT_NODUP;
 889        int i;
 890        int dummy;
 891        int use_index = 1;
 892        int pattern_type_arg = GREP_PATTERN_TYPE_UNSPECIFIED;
 893
 894        struct option options[] = {
 895                OPT_BOOL(0, "cached", &cached,
 896                        N_("search in index instead of in the work tree")),
 897                OPT_NEGBIT(0, "no-index", &use_index,
 898                         N_("find in contents not managed by git"), 1),
 899                OPT_BOOL(0, "untracked", &untracked,
 900                        N_("search in both tracked and untracked files")),
 901                OPT_SET_INT(0, "exclude-standard", &opt_exclude,
 902                            N_("ignore files specified via '.gitignore'"), 1),
 903                OPT_BOOL(0, "recurse-submodules", &recurse_submodules,
 904                         N_("recursivley search in each submodule")),
 905                OPT_GROUP(""),
 906                OPT_BOOL('v', "invert-match", &opt.invert,
 907                        N_("show non-matching lines")),
 908                OPT_BOOL('i', "ignore-case", &opt.ignore_case,
 909                        N_("case insensitive matching")),
 910                OPT_BOOL('w', "word-regexp", &opt.word_regexp,
 911                        N_("match patterns only at word boundaries")),
 912                OPT_SET_INT('a', "text", &opt.binary,
 913                        N_("process binary files as text"), GREP_BINARY_TEXT),
 914                OPT_SET_INT('I', NULL, &opt.binary,
 915                        N_("don't match patterns in binary files"),
 916                        GREP_BINARY_NOMATCH),
 917                OPT_BOOL(0, "textconv", &opt.allow_textconv,
 918                         N_("process binary files with textconv filters")),
 919                { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, N_("depth"),
 920                        N_("descend at most <depth> levels"), PARSE_OPT_NONEG,
 921                        NULL, 1 },
 922                OPT_GROUP(""),
 923                OPT_SET_INT('E', "extended-regexp", &pattern_type_arg,
 924                            N_("use extended POSIX regular expressions"),
 925                            GREP_PATTERN_TYPE_ERE),
 926                OPT_SET_INT('G', "basic-regexp", &pattern_type_arg,
 927                            N_("use basic POSIX regular expressions (default)"),
 928                            GREP_PATTERN_TYPE_BRE),
 929                OPT_SET_INT('F', "fixed-strings", &pattern_type_arg,
 930                            N_("interpret patterns as fixed strings"),
 931                            GREP_PATTERN_TYPE_FIXED),
 932                OPT_SET_INT('P', "perl-regexp", &pattern_type_arg,
 933                            N_("use Perl-compatible regular expressions"),
 934                            GREP_PATTERN_TYPE_PCRE),
 935                OPT_GROUP(""),
 936                OPT_BOOL('n', "line-number", &opt.linenum, N_("show line numbers")),
 937                OPT_NEGBIT('h', NULL, &opt.pathname, N_("don't show filenames"), 1),
 938                OPT_BIT('H', NULL, &opt.pathname, N_("show filenames"), 1),
 939                OPT_NEGBIT(0, "full-name", &opt.relative,
 940                        N_("show filenames relative to top directory"), 1),
 941                OPT_BOOL('l', "files-with-matches", &opt.name_only,
 942                        N_("show only filenames instead of matching lines")),
 943                OPT_BOOL(0, "name-only", &opt.name_only,
 944                        N_("synonym for --files-with-matches")),
 945                OPT_BOOL('L', "files-without-match",
 946                        &opt.unmatch_name_only,
 947                        N_("show only the names of files without match")),
 948                OPT_BOOL('z', "null", &opt.null_following_name,
 949                        N_("print NUL after filenames")),
 950                OPT_BOOL('c', "count", &opt.count,
 951                        N_("show the number of matches instead of matching lines")),
 952                OPT__COLOR(&opt.color, N_("highlight matches")),
 953                OPT_BOOL(0, "break", &opt.file_break,
 954                        N_("print empty line between matches from different files")),
 955                OPT_BOOL(0, "heading", &opt.heading,
 956                        N_("show filename only once above matches from same file")),
 957                OPT_GROUP(""),
 958                OPT_CALLBACK('C', "context", &opt, N_("n"),
 959                        N_("show <n> context lines before and after matches"),
 960                        context_callback),
 961                OPT_INTEGER('B', "before-context", &opt.pre_context,
 962                        N_("show <n> context lines before matches")),
 963                OPT_INTEGER('A', "after-context", &opt.post_context,
 964                        N_("show <n> context lines after matches")),
 965                OPT_INTEGER(0, "threads", &num_threads,
 966                        N_("use <n> worker threads")),
 967                OPT_NUMBER_CALLBACK(&opt, N_("shortcut for -C NUM"),
 968                        context_callback),
 969                OPT_BOOL('p', "show-function", &opt.funcname,
 970                        N_("show a line with the function name before matches")),
 971                OPT_BOOL('W', "function-context", &opt.funcbody,
 972                        N_("show the surrounding function")),
 973                OPT_GROUP(""),
 974                OPT_CALLBACK('f', NULL, &opt, N_("file"),
 975                        N_("read patterns from file"), file_callback),
 976                { OPTION_CALLBACK, 'e', NULL, &opt, N_("pattern"),
 977                        N_("match <pattern>"), PARSE_OPT_NONEG, pattern_callback },
 978                { OPTION_CALLBACK, 0, "and", &opt, NULL,
 979                  N_("combine patterns specified with -e"),
 980                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
 981                OPT_BOOL(0, "or", &dummy, ""),
 982                { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
 983                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
 984                { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
 985                  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
 986                  open_callback },
 987                { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
 988                  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
 989                  close_callback },
 990                OPT__QUIET(&opt.status_only,
 991                           N_("indicate hit with exit status without output")),
 992                OPT_BOOL(0, "all-match", &opt.all_match,
 993                        N_("show only matches from files that match all patterns")),
 994                { OPTION_SET_INT, 0, "debug", &opt.debug, NULL,
 995                  N_("show parse tree for grep expression"),
 996                  PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 1 },
 997                OPT_GROUP(""),
 998                { OPTION_STRING, 'O', "open-files-in-pager", &show_in_pager,
 999                        N_("pager"), N_("show matching files in the pager"),
1000                        PARSE_OPT_OPTARG, NULL, (intptr_t)default_pager },
1001                OPT_BOOL(0, "ext-grep", &external_grep_allowed__ignored,
1002                         N_("allow calling of grep(1) (ignored by this build)")),
1003                OPT_END()
1004        };
1005
1006        init_grep_defaults();
1007        git_config(grep_cmd_config, NULL);
1008        grep_init(&opt, prefix);
1009        super_prefix = get_super_prefix();
1010
1011        /*
1012         * If there is no -- then the paths must exist in the working
1013         * tree.  If there is no explicit pattern specified with -e or
1014         * -f, we take the first unrecognized non option to be the
1015         * pattern, but then what follows it must be zero or more
1016         * valid refs up to the -- (if exists), and then existing
1017         * paths.  If there is an explicit pattern, then the first
1018         * unrecognized non option is the beginning of the refs list
1019         * that continues up to the -- (if exists), and then paths.
1020         */
1021        argc = parse_options(argc, argv, prefix, options, grep_usage,
1022                             PARSE_OPT_KEEP_DASHDASH |
1023                             PARSE_OPT_STOP_AT_NON_OPTION);
1024        grep_commit_pattern_type(pattern_type_arg, &opt);
1025
1026        if (use_index && !startup_info->have_repository) {
1027                int fallback = 0;
1028                git_config_get_bool("grep.fallbacktonoindex", &fallback);
1029                if (fallback)
1030                        use_index = 0;
1031                else
1032                        /* die the same way as if we did it at the beginning */
1033                        setup_git_directory();
1034        }
1035
1036        /*
1037         * skip a -- separator; we know it cannot be
1038         * separating revisions from pathnames if
1039         * we haven't even had any patterns yet
1040         */
1041        if (argc > 0 && !opt.pattern_list && !strcmp(argv[0], "--")) {
1042                argv++;
1043                argc--;
1044        }
1045
1046        /* First unrecognized non-option token */
1047        if (argc > 0 && !opt.pattern_list) {
1048                append_grep_pattern(&opt, argv[0], "command line", 0,
1049                                    GREP_PATTERN);
1050                argv++;
1051                argc--;
1052        }
1053
1054        if (show_in_pager == default_pager)
1055                show_in_pager = git_pager(1);
1056        if (show_in_pager) {
1057                opt.color = 0;
1058                opt.name_only = 1;
1059                opt.null_following_name = 1;
1060                opt.output_priv = &path_list;
1061                opt.output = append_path;
1062                string_list_append(&path_list, show_in_pager);
1063        }
1064
1065        if (!opt.pattern_list)
1066                die(_("no pattern given."));
1067        if (!opt.fixed && opt.ignore_case)
1068                opt.regflags |= REG_ICASE;
1069
1070        compile_grep_patterns(&opt);
1071
1072        /* Check revs and then paths */
1073        for (i = 0; i < argc; i++) {
1074                const char *arg = argv[i];
1075                unsigned char sha1[20];
1076                struct object_context oc;
1077                /* Is it a rev? */
1078                if (!get_sha1_with_context(arg, 0, sha1, &oc)) {
1079                        struct object *object = parse_object_or_die(sha1, arg);
1080                        if (!seen_dashdash)
1081                                verify_non_filename(prefix, arg);
1082                        add_object_array_with_path(object, arg, &list, oc.mode, oc.path);
1083                        continue;
1084                }
1085                if (!strcmp(arg, "--")) {
1086                        i++;
1087                        seen_dashdash = 1;
1088                }
1089                break;
1090        }
1091
1092#ifndef NO_PTHREADS
1093        if (list.nr || cached || show_in_pager)
1094                num_threads = 0;
1095        else if (num_threads == 0)
1096                num_threads = GREP_NUM_THREADS_DEFAULT;
1097        else if (num_threads < 0)
1098                die(_("invalid number of threads specified (%d)"), num_threads);
1099#else
1100        num_threads = 0;
1101#endif
1102
1103#ifndef NO_PTHREADS
1104        if (num_threads) {
1105                if (!(opt.name_only || opt.unmatch_name_only || opt.count)
1106                    && (opt.pre_context || opt.post_context ||
1107                        opt.file_break || opt.funcbody))
1108                        skip_first_line = 1;
1109                start_threads(&opt);
1110        }
1111#endif
1112
1113        /* The rest are paths */
1114        if (!seen_dashdash) {
1115                int j;
1116                for (j = i; j < argc; j++)
1117                        verify_filename(prefix, argv[j], j == i);
1118        }
1119
1120        parse_pathspec(&pathspec, 0,
1121                       PATHSPEC_PREFER_CWD |
1122                       (opt.max_depth != -1 ? PATHSPEC_MAXDEPTH_VALID : 0),
1123                       prefix, argv + i);
1124        pathspec.max_depth = opt.max_depth;
1125        pathspec.recursive = 1;
1126
1127        if (recurse_submodules) {
1128                gitmodules_config();
1129                compile_submodule_options(&opt, &pathspec, cached, untracked,
1130                                          opt_exclude, use_index,
1131                                          pattern_type_arg);
1132        }
1133
1134        if (show_in_pager && (cached || list.nr))
1135                die(_("--open-files-in-pager only works on the worktree"));
1136
1137        if (show_in_pager && opt.pattern_list && !opt.pattern_list->next) {
1138                const char *pager = path_list.items[0].string;
1139                int len = strlen(pager);
1140
1141                if (len > 4 && is_dir_sep(pager[len - 5]))
1142                        pager += len - 4;
1143
1144                if (opt.ignore_case && !strcmp("less", pager))
1145                        string_list_append(&path_list, "-I");
1146
1147                if (!strcmp("less", pager) || !strcmp("vi", pager)) {
1148                        struct strbuf buf = STRBUF_INIT;
1149                        strbuf_addf(&buf, "+/%s%s",
1150                                        strcmp("less", pager) ? "" : "*",
1151                                        opt.pattern_list->pattern);
1152                        string_list_append(&path_list, buf.buf);
1153                        strbuf_detach(&buf, NULL);
1154                }
1155        }
1156
1157        if (recurse_submodules && (!use_index || untracked || list.nr))
1158                die(_("option not supported with --recurse-submodules."));
1159
1160        if (!show_in_pager && !opt.status_only)
1161                setup_pager();
1162
1163        if (!use_index && (untracked || cached))
1164                die(_("--cached or --untracked cannot be used with --no-index."));
1165
1166        if (!use_index || untracked) {
1167                int use_exclude = (opt_exclude < 0) ? use_index : !!opt_exclude;
1168                if (list.nr)
1169                        die(_("--no-index or --untracked cannot be used with revs."));
1170                hit = grep_directory(&opt, &pathspec, use_exclude, use_index);
1171        } else if (0 <= opt_exclude) {
1172                die(_("--[no-]exclude-standard cannot be used for tracked contents."));
1173        } else if (!list.nr) {
1174                if (!cached)
1175                        setup_work_tree();
1176
1177                hit = grep_cache(&opt, &pathspec, cached);
1178        } else {
1179                if (cached)
1180                        die(_("both --cached and trees are given."));
1181                hit = grep_objects(&opt, &pathspec, &list);
1182        }
1183
1184        if (num_threads)
1185                hit |= wait_all();
1186        if (hit && show_in_pager)
1187                run_pager(&opt, prefix);
1188        free_grep_patterns(&opt);
1189        return !hit;
1190}