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