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