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