builtin-grep.con commit Merge branch 'maint-1.6.1' into maint (9d51564)
   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 "grep.h"
  14
  15#ifndef NO_EXTERNAL_GREP
  16#ifdef __unix__
  17#define NO_EXTERNAL_GREP 0
  18#else
  19#define NO_EXTERNAL_GREP 1
  20#endif
  21#endif
  22
  23static int builtin_grep;
  24
  25/*
  26 * git grep pathspecs are somewhat different from diff-tree pathspecs;
  27 * pathname wildcards are allowed.
  28 */
  29static int pathspec_matches(const char **paths, const char *name)
  30{
  31        int namelen, i;
  32        if (!paths || !*paths)
  33                return 1;
  34        namelen = strlen(name);
  35        for (i = 0; paths[i]; i++) {
  36                const char *match = paths[i];
  37                int matchlen = strlen(match);
  38                const char *cp, *meta;
  39
  40                if (!matchlen ||
  41                    ((matchlen <= namelen) &&
  42                     !strncmp(name, match, matchlen) &&
  43                     (match[matchlen-1] == '/' ||
  44                      name[matchlen] == '\0' || name[matchlen] == '/')))
  45                        return 1;
  46                if (!fnmatch(match, name, 0))
  47                        return 1;
  48                if (name[namelen-1] != '/')
  49                        continue;
  50
  51                /* We are being asked if the directory ("name") is worth
  52                 * descending into.
  53                 *
  54                 * Find the longest leading directory name that does
  55                 * not have metacharacter in the pathspec; the name
  56                 * we are looking at must overlap with that directory.
  57                 */
  58                for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
  59                        char ch = *cp;
  60                        if (ch == '*' || ch == '[' || ch == '?') {
  61                                meta = cp;
  62                                break;
  63                        }
  64                }
  65                if (!meta)
  66                        meta = cp; /* fully literal */
  67
  68                if (namelen <= meta - match) {
  69                        /* Looking at "Documentation/" and
  70                         * the pattern says "Documentation/howto/", or
  71                         * "Documentation/diff*.txt".  The name we
  72                         * have should match prefix.
  73                         */
  74                        if (!memcmp(match, name, namelen))
  75                                return 1;
  76                        continue;
  77                }
  78
  79                if (meta - match < namelen) {
  80                        /* Looking at "Documentation/howto/" and
  81                         * the pattern says "Documentation/h*";
  82                         * match up to "Do.../h"; this avoids descending
  83                         * into "Documentation/technical/".
  84                         */
  85                        if (!memcmp(match, name, meta - match))
  86                                return 1;
  87                        continue;
  88                }
  89        }
  90        return 0;
  91}
  92
  93static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
  94{
  95        unsigned long size;
  96        char *data;
  97        enum object_type type;
  98        char *to_free = NULL;
  99        int hit;
 100
 101        data = read_sha1_file(sha1, &type, &size);
 102        if (!data) {
 103                error("'%s': unable to read %s", name, sha1_to_hex(sha1));
 104                return 0;
 105        }
 106        if (opt->relative && opt->prefix_length) {
 107                static char name_buf[PATH_MAX];
 108                char *cp;
 109                int name_len = strlen(name) - opt->prefix_length + 1;
 110
 111                if (!tree_name_len)
 112                        name += opt->prefix_length;
 113                else {
 114                        if (ARRAY_SIZE(name_buf) <= name_len)
 115                                cp = to_free = xmalloc(name_len);
 116                        else
 117                                cp = name_buf;
 118                        memcpy(cp, name, tree_name_len);
 119                        strcpy(cp + tree_name_len,
 120                               name + tree_name_len + opt->prefix_length);
 121                        name = cp;
 122                }
 123        }
 124        hit = grep_buffer(opt, name, data, size);
 125        free(data);
 126        free(to_free);
 127        return hit;
 128}
 129
 130static int grep_file(struct grep_opt *opt, const char *filename)
 131{
 132        struct stat st;
 133        int i;
 134        char *data;
 135        size_t sz;
 136
 137        if (lstat(filename, &st) < 0) {
 138        err_ret:
 139                if (errno != ENOENT)
 140                        error("'%s': %s", filename, strerror(errno));
 141                return 0;
 142        }
 143        if (!st.st_size)
 144                return 0; /* empty file -- no grep hit */
 145        if (!S_ISREG(st.st_mode))
 146                return 0;
 147        sz = xsize_t(st.st_size);
 148        i = open(filename, O_RDONLY);
 149        if (i < 0)
 150                goto err_ret;
 151        data = xmalloc(sz + 1);
 152        if (st.st_size != read_in_full(i, data, sz)) {
 153                error("'%s': short read %s", filename, strerror(errno));
 154                close(i);
 155                free(data);
 156                return 0;
 157        }
 158        close(i);
 159        if (opt->relative && opt->prefix_length)
 160                filename += opt->prefix_length;
 161        i = grep_buffer(opt, filename, data, sz);
 162        free(data);
 163        return i;
 164}
 165
 166#if !NO_EXTERNAL_GREP
 167static int exec_grep(int argc, const char **argv)
 168{
 169        pid_t pid;
 170        int status;
 171
 172        argv[argc] = NULL;
 173        pid = fork();
 174        if (pid < 0)
 175                return pid;
 176        if (!pid) {
 177                execvp("grep", (char **) argv);
 178                exit(255);
 179        }
 180        while (waitpid(pid, &status, 0) < 0) {
 181                if (errno == EINTR)
 182                        continue;
 183                return -1;
 184        }
 185        if (WIFEXITED(status)) {
 186                if (!WEXITSTATUS(status))
 187                        return 1;
 188                return 0;
 189        }
 190        return -1;
 191}
 192
 193#define MAXARGS 1000
 194#define ARGBUF 4096
 195#define push_arg(a) do { \
 196        if (nr < MAXARGS) argv[nr++] = (a); \
 197        else die("maximum number of args exceeded"); \
 198        } while (0)
 199
 200/*
 201 * If you send a singleton filename to grep, it does not give
 202 * the name of the file.  GNU grep has "-H" but we would want
 203 * that behaviour in a portable way.
 204 *
 205 * So we keep two pathnames in argv buffer unsent to grep in
 206 * the main loop if we need to do more than one grep.
 207 */
 208static int flush_grep(struct grep_opt *opt,
 209                      int argc, int arg0, const char **argv, int *kept)
 210{
 211        int status;
 212        int count = argc - arg0;
 213        const char *kept_0 = NULL;
 214
 215        if (count <= 2) {
 216                /*
 217                 * Because we keep at least 2 paths in the call from
 218                 * the main loop (i.e. kept != NULL), and MAXARGS is
 219                 * far greater than 2, this usually is a call to
 220                 * conclude the grep.  However, the user could attempt
 221                 * to overflow the argv buffer by giving too many
 222                 * options to leave very small number of real
 223                 * arguments even for the call in the main loop.
 224                 */
 225                if (kept)
 226                        die("insanely many options to grep");
 227
 228                /*
 229                 * If we have two or more paths, we do not have to do
 230                 * anything special, but we need to push /dev/null to
 231                 * get "-H" behaviour of GNU grep portably but when we
 232                 * are not doing "-l" nor "-L" nor "-c".
 233                 */
 234                if (count == 1 &&
 235                    !opt->name_only &&
 236                    !opt->unmatch_name_only &&
 237                    !opt->count) {
 238                        argv[argc++] = "/dev/null";
 239                        argv[argc] = NULL;
 240                }
 241        }
 242
 243        else if (kept) {
 244                /*
 245                 * Called because we found many paths and haven't finished
 246                 * iterating over the cache yet.  We keep two paths
 247                 * for the concluding call.  argv[argc-2] and argv[argc-1]
 248                 * has the last two paths, so save the first one away,
 249                 * replace it with NULL while sending the list to grep,
 250                 * and recover them after we are done.
 251                 */
 252                *kept = 2;
 253                kept_0 = argv[argc-2];
 254                argv[argc-2] = NULL;
 255                argc -= 2;
 256        }
 257
 258        status = exec_grep(argc, argv);
 259
 260        if (kept_0) {
 261                /*
 262                 * Then recover them.  Now the last arg is beyond the
 263                 * terminating NULL which is at argc, and the second
 264                 * from the last is what we saved away in kept_0
 265                 */
 266                argv[arg0++] = kept_0;
 267                argv[arg0] = argv[argc+1];
 268        }
 269        return status;
 270}
 271
 272static int external_grep(struct grep_opt *opt, const char **paths, int cached)
 273{
 274        int i, nr, argc, hit, len, status;
 275        const char *argv[MAXARGS+1];
 276        char randarg[ARGBUF];
 277        char *argptr = randarg;
 278        struct grep_pat *p;
 279
 280        if (opt->extended || (opt->relative && opt->prefix_length))
 281                return -1;
 282        len = nr = 0;
 283        push_arg("grep");
 284        if (opt->fixed)
 285                push_arg("-F");
 286        if (opt->linenum)
 287                push_arg("-n");
 288        if (!opt->pathname)
 289                push_arg("-h");
 290        if (opt->regflags & REG_EXTENDED)
 291                push_arg("-E");
 292        if (opt->regflags & REG_ICASE)
 293                push_arg("-i");
 294        if (opt->binary == GREP_BINARY_NOMATCH)
 295                push_arg("-I");
 296        if (opt->word_regexp)
 297                push_arg("-w");
 298        if (opt->name_only)
 299                push_arg("-l");
 300        if (opt->unmatch_name_only)
 301                push_arg("-L");
 302        if (opt->null_following_name)
 303                /* in GNU grep git's "-z" translates to "-Z" */
 304                push_arg("-Z");
 305        if (opt->count)
 306                push_arg("-c");
 307        if (opt->post_context || opt->pre_context) {
 308                if (opt->post_context != opt->pre_context) {
 309                        if (opt->pre_context) {
 310                                push_arg("-B");
 311                                len += snprintf(argptr, sizeof(randarg)-len,
 312                                                "%u", opt->pre_context) + 1;
 313                                if (sizeof(randarg) <= len)
 314                                        die("maximum length of args exceeded");
 315                                push_arg(argptr);
 316                                argptr += len;
 317                        }
 318                        if (opt->post_context) {
 319                                push_arg("-A");
 320                                len += snprintf(argptr, sizeof(randarg)-len,
 321                                                "%u", opt->post_context) + 1;
 322                                if (sizeof(randarg) <= len)
 323                                        die("maximum length of args exceeded");
 324                                push_arg(argptr);
 325                                argptr += len;
 326                        }
 327                }
 328                else {
 329                        push_arg("-C");
 330                        len += snprintf(argptr, sizeof(randarg)-len,
 331                                        "%u", opt->post_context) + 1;
 332                        if (sizeof(randarg) <= len)
 333                                die("maximum length of args exceeded");
 334                        push_arg(argptr);
 335                        argptr += len;
 336                }
 337        }
 338        for (p = opt->pattern_list; p; p = p->next) {
 339                push_arg("-e");
 340                push_arg(p->pattern);
 341        }
 342
 343        hit = 0;
 344        argc = nr;
 345        for (i = 0; i < active_nr; i++) {
 346                struct cache_entry *ce = active_cache[i];
 347                char *name;
 348                int kept;
 349                if (!S_ISREG(ce->ce_mode))
 350                        continue;
 351                if (!pathspec_matches(paths, ce->name))
 352                        continue;
 353                name = ce->name;
 354                if (name[0] == '-') {
 355                        int len = ce_namelen(ce);
 356                        name = xmalloc(len + 3);
 357                        memcpy(name, "./", 2);
 358                        memcpy(name + 2, ce->name, len + 1);
 359                }
 360                argv[argc++] = name;
 361                if (MAXARGS <= argc) {
 362                        status = flush_grep(opt, argc, nr, argv, &kept);
 363                        if (0 < status)
 364                                hit = 1;
 365                        argc = nr + kept;
 366                }
 367                if (ce_stage(ce)) {
 368                        do {
 369                                i++;
 370                        } while (i < active_nr &&
 371                                 !strcmp(ce->name, active_cache[i]->name));
 372                        i--; /* compensate for loop control */
 373                }
 374        }
 375        if (argc > nr) {
 376                status = flush_grep(opt, argc, nr, argv, NULL);
 377                if (0 < status)
 378                        hit = 1;
 379        }
 380        return hit;
 381}
 382#endif
 383
 384static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
 385{
 386        int hit = 0;
 387        int nr;
 388        read_cache();
 389
 390#if !NO_EXTERNAL_GREP
 391        /*
 392         * Use the external "grep" command for the case where
 393         * we grep through the checked-out files. It tends to
 394         * be a lot more optimized
 395         */
 396        if (!cached && !builtin_grep) {
 397                hit = external_grep(opt, paths, cached);
 398                if (hit >= 0)
 399                        return hit;
 400        }
 401#endif
 402
 403        for (nr = 0; nr < active_nr; nr++) {
 404                struct cache_entry *ce = active_cache[nr];
 405                if (!S_ISREG(ce->ce_mode))
 406                        continue;
 407                if (!pathspec_matches(paths, ce->name))
 408                        continue;
 409                /*
 410                 * If CE_VALID is on, we assume worktree file and its cache entry
 411                 * are identical, even if worktree file has been modified, so use
 412                 * cache version instead
 413                 */
 414                if (cached || (ce->ce_flags & CE_VALID)) {
 415                        if (ce_stage(ce))
 416                                continue;
 417                        hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
 418                }
 419                else
 420                        hit |= grep_file(opt, ce->name);
 421                if (ce_stage(ce)) {
 422                        do {
 423                                nr++;
 424                        } while (nr < active_nr &&
 425                                 !strcmp(ce->name, active_cache[nr]->name));
 426                        nr--; /* compensate for loop control */
 427                }
 428        }
 429        free_grep_patterns(opt);
 430        return hit;
 431}
 432
 433static int grep_tree(struct grep_opt *opt, const char **paths,
 434                     struct tree_desc *tree,
 435                     const char *tree_name, const char *base)
 436{
 437        int len;
 438        int hit = 0;
 439        struct name_entry entry;
 440        char *down;
 441        int tn_len = strlen(tree_name);
 442        struct strbuf pathbuf;
 443
 444        strbuf_init(&pathbuf, PATH_MAX + tn_len);
 445
 446        if (tn_len) {
 447                strbuf_add(&pathbuf, tree_name, tn_len);
 448                strbuf_addch(&pathbuf, ':');
 449                tn_len = pathbuf.len;
 450        }
 451        strbuf_addstr(&pathbuf, base);
 452        len = pathbuf.len;
 453
 454        while (tree_entry(tree, &entry)) {
 455                int te_len = tree_entry_len(entry.path, entry.sha1);
 456                pathbuf.len = len;
 457                strbuf_add(&pathbuf, entry.path, te_len);
 458
 459                if (S_ISDIR(entry.mode))
 460                        /* Match "abc/" against pathspec to
 461                         * decide if we want to descend into "abc"
 462                         * directory.
 463                         */
 464                        strbuf_addch(&pathbuf, '/');
 465
 466                down = pathbuf.buf + tn_len;
 467                if (!pathspec_matches(paths, down))
 468                        ;
 469                else if (S_ISREG(entry.mode))
 470                        hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
 471                else if (S_ISDIR(entry.mode)) {
 472                        enum object_type type;
 473                        struct tree_desc sub;
 474                        void *data;
 475                        unsigned long size;
 476
 477                        data = read_sha1_file(entry.sha1, &type, &size);
 478                        if (!data)
 479                                die("unable to read tree (%s)",
 480                                    sha1_to_hex(entry.sha1));
 481                        init_tree_desc(&sub, data, size);
 482                        hit |= grep_tree(opt, paths, &sub, tree_name, down);
 483                        free(data);
 484                }
 485        }
 486        strbuf_release(&pathbuf);
 487        return hit;
 488}
 489
 490static int grep_object(struct grep_opt *opt, const char **paths,
 491                       struct object *obj, const char *name)
 492{
 493        if (obj->type == OBJ_BLOB)
 494                return grep_sha1(opt, obj->sha1, name, 0);
 495        if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
 496                struct tree_desc tree;
 497                void *data;
 498                unsigned long size;
 499                int hit;
 500                data = read_object_with_reference(obj->sha1, tree_type,
 501                                                  &size, NULL);
 502                if (!data)
 503                        die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
 504                init_tree_desc(&tree, data, size);
 505                hit = grep_tree(opt, paths, &tree, name, "");
 506                free(data);
 507                return hit;
 508        }
 509        die("unable to grep from object of type %s", typename(obj->type));
 510}
 511
 512static const char builtin_grep_usage[] =
 513"git grep <option>* [-e] <pattern> <rev>* [[--] <path>...]";
 514
 515static const char emsg_invalid_context_len[] =
 516"%s: invalid context length argument";
 517static const char emsg_missing_context_len[] =
 518"missing context length argument";
 519static const char emsg_missing_argument[] =
 520"option requires an argument -%s";
 521
 522int cmd_grep(int argc, const char **argv, const char *prefix)
 523{
 524        int hit = 0;
 525        int cached = 0;
 526        int seen_dashdash = 0;
 527        struct grep_opt opt;
 528        struct object_array list = { 0, 0, NULL };
 529        const char **paths = NULL;
 530        int i;
 531
 532        memset(&opt, 0, sizeof(opt));
 533        opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
 534        opt.relative = 1;
 535        opt.pathname = 1;
 536        opt.pattern_tail = &opt.pattern_list;
 537        opt.regflags = REG_NEWLINE;
 538
 539        /*
 540         * If there is no -- then the paths must exist in the working
 541         * tree.  If there is no explicit pattern specified with -e or
 542         * -f, we take the first unrecognized non option to be the
 543         * pattern, but then what follows it must be zero or more
 544         * valid refs up to the -- (if exists), and then existing
 545         * paths.  If there is an explicit pattern, then the first
 546         * unrecognized non option is the beginning of the refs list
 547         * that continues up to the -- (if exists), and then paths.
 548         */
 549
 550        while (1 < argc) {
 551                const char *arg = argv[1];
 552                argc--; argv++;
 553                if (!strcmp("--cached", arg)) {
 554                        cached = 1;
 555                        continue;
 556                }
 557                if (!strcmp("--no-ext-grep", arg)) {
 558                        builtin_grep = 1;
 559                        continue;
 560                }
 561                if (!strcmp("-a", arg) ||
 562                    !strcmp("--text", arg)) {
 563                        opt.binary = GREP_BINARY_TEXT;
 564                        continue;
 565                }
 566                if (!strcmp("-i", arg) ||
 567                    !strcmp("--ignore-case", arg)) {
 568                        opt.regflags |= REG_ICASE;
 569                        continue;
 570                }
 571                if (!strcmp("-I", arg)) {
 572                        opt.binary = GREP_BINARY_NOMATCH;
 573                        continue;
 574                }
 575                if (!strcmp("-v", arg) ||
 576                    !strcmp("--invert-match", arg)) {
 577                        opt.invert = 1;
 578                        continue;
 579                }
 580                if (!strcmp("-E", arg) ||
 581                    !strcmp("--extended-regexp", arg)) {
 582                        opt.regflags |= REG_EXTENDED;
 583                        continue;
 584                }
 585                if (!strcmp("-F", arg) ||
 586                    !strcmp("--fixed-strings", arg)) {
 587                        opt.fixed = 1;
 588                        continue;
 589                }
 590                if (!strcmp("-G", arg) ||
 591                    !strcmp("--basic-regexp", arg)) {
 592                        opt.regflags &= ~REG_EXTENDED;
 593                        continue;
 594                }
 595                if (!strcmp("-n", arg)) {
 596                        opt.linenum = 1;
 597                        continue;
 598                }
 599                if (!strcmp("-h", arg)) {
 600                        opt.pathname = 0;
 601                        continue;
 602                }
 603                if (!strcmp("-H", arg)) {
 604                        opt.pathname = 1;
 605                        continue;
 606                }
 607                if (!strcmp("-l", arg) ||
 608                    !strcmp("--name-only", arg) ||
 609                    !strcmp("--files-with-matches", arg)) {
 610                        opt.name_only = 1;
 611                        continue;
 612                }
 613                if (!strcmp("-L", arg) ||
 614                    !strcmp("--files-without-match", arg)) {
 615                        opt.unmatch_name_only = 1;
 616                        continue;
 617                }
 618                if (!strcmp("-z", arg) ||
 619                    !strcmp("--null", arg)) {
 620                        opt.null_following_name = 1;
 621                        continue;
 622                }
 623                if (!strcmp("-c", arg) ||
 624                    !strcmp("--count", arg)) {
 625                        opt.count = 1;
 626                        continue;
 627                }
 628                if (!strcmp("-w", arg) ||
 629                    !strcmp("--word-regexp", arg)) {
 630                        opt.word_regexp = 1;
 631                        continue;
 632                }
 633                if (!prefixcmp(arg, "-A") ||
 634                    !prefixcmp(arg, "-B") ||
 635                    !prefixcmp(arg, "-C") ||
 636                    (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
 637                        unsigned num;
 638                        const char *scan;
 639                        switch (arg[1]) {
 640                        case 'A': case 'B': case 'C':
 641                                if (!arg[2]) {
 642                                        if (argc <= 1)
 643                                                die(emsg_missing_context_len);
 644                                        scan = *++argv;
 645                                        argc--;
 646                                }
 647                                else
 648                                        scan = arg + 2;
 649                                break;
 650                        default:
 651                                scan = arg + 1;
 652                                break;
 653                        }
 654                        if (strtoul_ui(scan, 10, &num))
 655                                die(emsg_invalid_context_len, scan);
 656                        switch (arg[1]) {
 657                        case 'A':
 658                                opt.post_context = num;
 659                                break;
 660                        default:
 661                        case 'C':
 662                                opt.post_context = num;
 663                        case 'B':
 664                                opt.pre_context = num;
 665                                break;
 666                        }
 667                        continue;
 668                }
 669                if (!strcmp("-f", arg)) {
 670                        FILE *patterns;
 671                        int lno = 0;
 672                        char buf[1024];
 673                        if (argc <= 1)
 674                                die(emsg_missing_argument, arg);
 675                        patterns = fopen(argv[1], "r");
 676                        if (!patterns)
 677                                die("'%s': %s", argv[1], strerror(errno));
 678                        while (fgets(buf, sizeof(buf), patterns)) {
 679                                int len = strlen(buf);
 680                                if (len && buf[len-1] == '\n')
 681                                        buf[len-1] = 0;
 682                                /* ignore empty line like grep does */
 683                                if (!buf[0])
 684                                        continue;
 685                                append_grep_pattern(&opt, xstrdup(buf),
 686                                                    argv[1], ++lno,
 687                                                    GREP_PATTERN);
 688                        }
 689                        fclose(patterns);
 690                        argv++;
 691                        argc--;
 692                        continue;
 693                }
 694                if (!strcmp("--not", arg)) {
 695                        append_grep_pattern(&opt, arg, "command line", 0,
 696                                            GREP_NOT);
 697                        continue;
 698                }
 699                if (!strcmp("--and", arg)) {
 700                        append_grep_pattern(&opt, arg, "command line", 0,
 701                                            GREP_AND);
 702                        continue;
 703                }
 704                if (!strcmp("--or", arg))
 705                        continue; /* no-op */
 706                if (!strcmp("(", arg)) {
 707                        append_grep_pattern(&opt, arg, "command line", 0,
 708                                            GREP_OPEN_PAREN);
 709                        continue;
 710                }
 711                if (!strcmp(")", arg)) {
 712                        append_grep_pattern(&opt, arg, "command line", 0,
 713                                            GREP_CLOSE_PAREN);
 714                        continue;
 715                }
 716                if (!strcmp("--all-match", arg)) {
 717                        opt.all_match = 1;
 718                        continue;
 719                }
 720                if (!strcmp("-e", arg)) {
 721                        if (1 < argc) {
 722                                append_grep_pattern(&opt, argv[1],
 723                                                    "-e option", 0,
 724                                                    GREP_PATTERN);
 725                                argv++;
 726                                argc--;
 727                                continue;
 728                        }
 729                        die(emsg_missing_argument, arg);
 730                }
 731                if (!strcmp("--full-name", arg)) {
 732                        opt.relative = 0;
 733                        continue;
 734                }
 735                if (!strcmp("--", arg)) {
 736                        /* later processing wants to have this at argv[1] */
 737                        argv--;
 738                        argc++;
 739                        break;
 740                }
 741                if (*arg == '-')
 742                        usage(builtin_grep_usage);
 743
 744                /* First unrecognized non-option token */
 745                if (!opt.pattern_list) {
 746                        append_grep_pattern(&opt, arg, "command line", 0,
 747                                            GREP_PATTERN);
 748                        break;
 749                }
 750                else {
 751                        /* We are looking at the first path or rev;
 752                         * it is found at argv[1] after leaving the
 753                         * loop.
 754                         */
 755                        argc++; argv--;
 756                        break;
 757                }
 758        }
 759
 760        if (!opt.pattern_list)
 761                die("no pattern given.");
 762        if ((opt.regflags != REG_NEWLINE) && opt.fixed)
 763                die("cannot mix --fixed-strings and regexp");
 764        compile_grep_patterns(&opt);
 765
 766        /* Check revs and then paths */
 767        for (i = 1; i < argc; i++) {
 768                const char *arg = argv[i];
 769                unsigned char sha1[20];
 770                /* Is it a rev? */
 771                if (!get_sha1(arg, sha1)) {
 772                        struct object *object = parse_object(sha1);
 773                        if (!object)
 774                                die("bad object %s", arg);
 775                        add_object_array(object, arg, &list);
 776                        continue;
 777                }
 778                if (!strcmp(arg, "--")) {
 779                        i++;
 780                        seen_dashdash = 1;
 781                }
 782                break;
 783        }
 784
 785        /* The rest are paths */
 786        if (!seen_dashdash) {
 787                int j;
 788                for (j = i; j < argc; j++)
 789                        verify_filename(prefix, argv[j]);
 790        }
 791
 792        if (i < argc) {
 793                paths = get_pathspec(prefix, argv + i);
 794                if (opt.prefix_length && opt.relative) {
 795                        /* Make sure we do not get outside of paths */
 796                        for (i = 0; paths[i]; i++)
 797                                if (strncmp(prefix, paths[i], opt.prefix_length))
 798                                        die("git grep: cannot generate relative filenames containing '..'");
 799                }
 800        }
 801        else if (prefix) {
 802                paths = xcalloc(2, sizeof(const char *));
 803                paths[0] = prefix;
 804                paths[1] = NULL;
 805        }
 806
 807        if (!list.nr) {
 808                if (!cached)
 809                        setup_work_tree();
 810                return !grep_cache(&opt, paths, cached);
 811        }
 812
 813        if (cached)
 814                die("both --cached and trees are given.");
 815
 816        for (i = 0; i < list.nr; i++) {
 817                struct object *real_obj;
 818                real_obj = deref_tag(list.objects[i].item, NULL, 0);
 819                if (grep_object(&opt, paths, real_obj, list.objects[i].name))
 820                        hit = 1;
 821        }
 822        free_grep_patterns(&opt);
 823        return !hit;
 824}