0d6115763bf3c9f409518daa000f51951a7f0c95
   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 <fnmatch.h>
  15
  16/*
  17 * git grep pathspecs are somewhat different from diff-tree pathspecs;
  18 * pathname wildcards are allowed.
  19 */
  20static int pathspec_matches(const char **paths, const char *name)
  21{
  22        int namelen, i;
  23        if (!paths || !*paths)
  24                return 1;
  25        namelen = strlen(name);
  26        for (i = 0; paths[i]; i++) {
  27                const char *match = paths[i];
  28                int matchlen = strlen(match);
  29                const char *cp, *meta;
  30
  31                if ((matchlen <= namelen) &&
  32                    !strncmp(name, match, matchlen) &&
  33                    (match[matchlen-1] == '/' ||
  34                     name[matchlen] == '\0' || name[matchlen] == '/'))
  35                        return 1;
  36                if (!fnmatch(match, name, 0))
  37                        return 1;
  38                if (name[namelen-1] != '/')
  39                        continue;
  40
  41                /* We are being asked if the directory ("name") is worth
  42                 * descending into.
  43                 *
  44                 * Find the longest leading directory name that does
  45                 * not have metacharacter in the pathspec; the name
  46                 * we are looking at must overlap with that directory.
  47                 */
  48                for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
  49                        char ch = *cp;
  50                        if (ch == '*' || ch == '[' || ch == '?') {
  51                                meta = cp;
  52                                break;
  53                        }
  54                }
  55                if (!meta)
  56                        meta = cp; /* fully literal */
  57
  58                if (namelen <= meta - match) {
  59                        /* Looking at "Documentation/" and
  60                         * the pattern says "Documentation/howto/", or
  61                         * "Documentation/diff*.txt".  The name we
  62                         * have should match prefix.
  63                         */
  64                        if (!memcmp(match, name, namelen))
  65                                return 1;
  66                        continue;
  67                }
  68
  69                if (meta - match < namelen) {
  70                        /* Looking at "Documentation/howto/" and
  71                         * the pattern says "Documentation/h*";
  72                         * match up to "Do.../h"; this avoids descending
  73                         * into "Documentation/technical/".
  74                         */
  75                        if (!memcmp(match, name, meta - match))
  76                                return 1;
  77                        continue;
  78                }
  79        }
  80        return 0;
  81}
  82
  83struct grep_pat {
  84        struct grep_pat *next;
  85        const char *pattern;
  86        regex_t regexp;
  87};
  88
  89struct grep_opt {
  90        struct grep_pat *pattern_list;
  91        struct grep_pat **pattern_tail;
  92        regex_t regexp;
  93        unsigned linenum:1;
  94        unsigned invert:1;
  95        unsigned name_only:1;
  96        unsigned count:1;
  97        unsigned word_regexp:1;
  98#define GREP_BINARY_DEFAULT     0
  99#define GREP_BINARY_NOMATCH     1
 100#define GREP_BINARY_TEXT        2
 101        unsigned binary:2;
 102        int regflags;
 103        unsigned pre_context;
 104        unsigned post_context;
 105};
 106
 107static void add_pattern(struct grep_opt *opt, const char *pat)
 108{
 109        struct grep_pat *p = xcalloc(1, sizeof(*p));
 110        p->pattern = pat;
 111        *opt->pattern_tail = p;
 112        opt->pattern_tail = &p->next;
 113        p->next = NULL;
 114}
 115
 116static void compile_patterns(struct grep_opt *opt)
 117{
 118        struct grep_pat *p;
 119        for (p = opt->pattern_list; p; p = p->next) {
 120                int err = regcomp(&p->regexp, p->pattern, opt->regflags);
 121                if (err) {
 122                        char errbuf[1024];
 123                        regerror(err, &p->regexp, errbuf, 1024);
 124                        regfree(&p->regexp);
 125                        die("'%s': %s", p->pattern, errbuf);
 126                }
 127        }
 128}
 129
 130static char *end_of_line(char *cp, unsigned long *left)
 131{
 132        unsigned long l = *left;
 133        while (l && *cp != '\n') {
 134                l--;
 135                cp++;
 136        }
 137        *left = l;
 138        return cp;
 139}
 140
 141static int word_char(char ch)
 142{
 143        return isalnum(ch) || ch == '_';
 144}
 145
 146static void show_line(struct grep_opt *opt, const char *bol, const char *eol,
 147                      const char *name, unsigned lno, char sign)
 148{
 149        printf("%s%c", name, sign);
 150        if (opt->linenum)
 151                printf("%d%c", lno, sign);
 152        printf("%.*s\n", (int)(eol-bol), bol);
 153}
 154
 155/*
 156 * NEEDSWORK: share code with diff.c
 157 */
 158#define FIRST_FEW_BYTES 8000
 159static int buffer_is_binary(const char *ptr, unsigned long size)
 160{
 161        if (FIRST_FEW_BYTES < size)
 162                size = FIRST_FEW_BYTES;
 163        if (memchr(ptr, 0, size))
 164                return 1;
 165        return 0;
 166}
 167
 168static int grep_buffer(struct grep_opt *opt, const char *name,
 169                       char *buf, unsigned long size)
 170{
 171        char *bol = buf;
 172        unsigned long left = size;
 173        unsigned lno = 1;
 174        struct pre_context_line {
 175                char *bol;
 176                char *eol;
 177        } *prev = NULL, *pcl;
 178        unsigned last_hit = 0;
 179        unsigned last_shown = 0;
 180        int binary_match_only = 0;
 181        const char *hunk_mark = "";
 182        unsigned count = 0;
 183
 184        if (buffer_is_binary(buf, size)) {
 185                switch (opt->binary) {
 186                case GREP_BINARY_DEFAULT:
 187                        binary_match_only = 1;
 188                        break;
 189                case GREP_BINARY_NOMATCH:
 190                        return 0; /* Assume unmatch */
 191                        break;
 192                default:
 193                        break;
 194                }
 195        }
 196
 197        if (opt->pre_context)
 198                prev = xcalloc(opt->pre_context, sizeof(*prev));
 199        if (opt->pre_context || opt->post_context)
 200                hunk_mark = "--\n";
 201
 202        while (left) {
 203                regmatch_t pmatch[10];
 204                char *eol, ch;
 205                int hit = 0;
 206                struct grep_pat *p;
 207
 208                eol = end_of_line(bol, &left);
 209                ch = *eol;
 210                *eol = 0;
 211
 212                for (p = opt->pattern_list; p; p = p->next) {
 213                        regex_t *exp = &p->regexp;
 214                        hit = !regexec(exp, bol, ARRAY_SIZE(pmatch),
 215                                       pmatch, 0);
 216
 217                        if (hit && opt->word_regexp) {
 218                                /* Match beginning must be either
 219                                 * beginning of the line, or at word
 220                                 * boundary (i.e. the last char must
 221                                 * not be alnum or underscore).
 222                                 */
 223                                if ((pmatch[0].rm_so < 0) ||
 224                                    (eol - bol) <= pmatch[0].rm_so ||
 225                                    (pmatch[0].rm_eo < 0) ||
 226                                    (eol - bol) < pmatch[0].rm_eo)
 227                                        die("regexp returned nonsense");
 228                                if (pmatch[0].rm_so != 0 &&
 229                                    word_char(bol[pmatch[0].rm_so-1]))
 230                                        continue; /* not a word boundary */
 231                                if ((eol-bol) < pmatch[0].rm_eo &&
 232                                    word_char(bol[pmatch[0].rm_eo]))
 233                                        continue; /* not a word boundary */
 234                        }
 235                        if (hit)
 236                                break;
 237                }
 238                /* "grep -v -e foo -e bla" should list lines
 239                 * that do not have either, so inversion should
 240                 * be done outside.
 241                 */
 242                if (opt->invert)
 243                        hit = !hit;
 244                if (hit) {
 245                        count++;
 246                        if (binary_match_only) {
 247                                printf("Binary file %s matches\n", name);
 248                                return 1;
 249                        }
 250                        if (opt->name_only) {
 251                                printf("%s\n", name);
 252                                return 1;
 253                        }
 254                        /* Hit at this line.  If we haven't shown the
 255                         * pre-context lines, we would need to show them.
 256                         * When asked to do "count", this still show
 257                         * the context which is nonsense, but the user
 258                         * deserves to get that ;-).
 259                         */
 260                        if (opt->pre_context) {
 261                                unsigned from;
 262                                if (opt->pre_context < lno)
 263                                        from = lno - opt->pre_context;
 264                                else
 265                                        from = 1;
 266                                if (from <= last_shown)
 267                                        from = last_shown + 1;
 268                                if (last_shown && from != last_shown + 1)
 269                                        printf(hunk_mark);
 270                                while (from < lno) {
 271                                        pcl = &prev[lno-from-1];
 272                                        show_line(opt, pcl->bol, pcl->eol,
 273                                                  name, from, '-');
 274                                        from++;
 275                                }
 276                                last_shown = lno-1;
 277                        }
 278                        if (last_shown && lno != last_shown + 1)
 279                                printf(hunk_mark);
 280                        if (!opt->count)
 281                                show_line(opt, bol, eol, name, lno, ':');
 282                        last_shown = last_hit = lno;
 283                }
 284                else if (last_hit &&
 285                         lno <= last_hit + opt->post_context) {
 286                        /* If the last hit is within the post context,
 287                         * we need to show this line.
 288                         */
 289                        if (last_shown && lno != last_shown + 1)
 290                                printf(hunk_mark);
 291                        show_line(opt, bol, eol, name, lno, '-');
 292                        last_shown = lno;
 293                }
 294                if (opt->pre_context) {
 295                        memmove(prev+1, prev,
 296                                (opt->pre_context-1) * sizeof(*prev));
 297                        prev->bol = bol;
 298                        prev->eol = eol;
 299                }
 300                *eol = ch;
 301                bol = eol + 1;
 302                if (!left)
 303                        break;
 304                left--;
 305                lno++;
 306        }
 307        /* NEEDSWORK:
 308         * The real "grep -c foo *.c" gives many "bar.c:0" lines,
 309         * which feels mostly useless but sometimes useful.  Maybe
 310         * make it another option?  For now suppress them.
 311         */
 312        if (opt->count && count)
 313                printf("%s:%u\n", name, count);
 314        return !!last_hit;
 315}
 316
 317static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name)
 318{
 319        unsigned long size;
 320        char *data;
 321        char type[20];
 322        int hit;
 323        data = read_sha1_file(sha1, type, &size);
 324        if (!data) {
 325                error("'%s': unable to read %s", name, sha1_to_hex(sha1));
 326                return 0;
 327        }
 328        hit = grep_buffer(opt, name, data, size);
 329        free(data);
 330        return hit;
 331}
 332
 333static int grep_file(struct grep_opt *opt, const char *filename)
 334{
 335        struct stat st;
 336        int i;
 337        char *data;
 338        if (lstat(filename, &st) < 0) {
 339        err_ret:
 340                if (errno != ENOENT)
 341                        error("'%s': %s", filename, strerror(errno));
 342                return 0;
 343        }
 344        if (!st.st_size)
 345                return 0; /* empty file -- no grep hit */
 346        if (!S_ISREG(st.st_mode))
 347                return 0;
 348        i = open(filename, O_RDONLY);
 349        if (i < 0)
 350                goto err_ret;
 351        data = xmalloc(st.st_size + 1);
 352        if (st.st_size != xread(i, data, st.st_size)) {
 353                error("'%s': short read %s", filename, strerror(errno));
 354                close(i);
 355                free(data);
 356                return 0;
 357        }
 358        close(i);
 359        i = grep_buffer(opt, filename, data, st.st_size);
 360        free(data);
 361        return i;
 362}
 363
 364static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
 365{
 366        int hit = 0;
 367        int nr;
 368        read_cache();
 369
 370        for (nr = 0; nr < active_nr; nr++) {
 371                struct cache_entry *ce = active_cache[nr];
 372                if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
 373                        continue;
 374                if (!pathspec_matches(paths, ce->name))
 375                        continue;
 376                if (cached)
 377                        hit |= grep_sha1(opt, ce->sha1, ce->name);
 378                else
 379                        hit |= grep_file(opt, ce->name);
 380        }
 381        return hit;
 382}
 383
 384static int grep_tree(struct grep_opt *opt, const char **paths,
 385                     struct tree_desc *tree,
 386                     const char *tree_name, const char *base)
 387{
 388        unsigned mode;
 389        int len;
 390        int hit = 0;
 391        const char *path;
 392        const unsigned char *sha1;
 393        char *down;
 394        char *path_buf = xmalloc(PATH_MAX + strlen(tree_name) + 100);
 395
 396        if (tree_name[0]) {
 397                int offset = sprintf(path_buf, "%s:", tree_name);
 398                down = path_buf + offset;
 399                strcat(down, base);
 400        }
 401        else {
 402                down = path_buf;
 403                strcpy(down, base);
 404        }
 405        len = strlen(path_buf);
 406
 407        while (tree->size) {
 408                int pathlen;
 409                sha1 = tree_entry_extract(tree, &path, &mode);
 410                pathlen = strlen(path);
 411                strcpy(path_buf + len, path);
 412
 413                if (S_ISDIR(mode))
 414                        /* Match "abc/" against pathspec to
 415                         * decide if we want to descend into "abc"
 416                         * directory.
 417                         */
 418                        strcpy(path_buf + len + pathlen, "/");
 419
 420                if (!pathspec_matches(paths, down))
 421                        ;
 422                else if (S_ISREG(mode))
 423                        hit |= grep_sha1(opt, sha1, path_buf);
 424                else if (S_ISDIR(mode)) {
 425                        char type[20];
 426                        struct tree_desc sub;
 427                        void *data;
 428                        data = read_sha1_file(sha1, type, &sub.size);
 429                        if (!data)
 430                                die("unable to read tree (%s)",
 431                                    sha1_to_hex(sha1));
 432                        sub.buf = data;
 433                        hit |= grep_tree(opt, paths, &sub, tree_name, down);
 434                        free(data);
 435                }
 436                update_tree_entry(tree);
 437        }
 438        return hit;
 439}
 440
 441static int grep_object(struct grep_opt *opt, const char **paths,
 442                       struct object *obj, const char *name)
 443{
 444        if (!strcmp(obj->type, blob_type))
 445                return grep_sha1(opt, obj->sha1, name);
 446        if (!strcmp(obj->type, commit_type) ||
 447            !strcmp(obj->type, tree_type)) {
 448                struct tree_desc tree;
 449                void *data;
 450                int hit;
 451                data = read_object_with_reference(obj->sha1, tree_type,
 452                                                  &tree.size, NULL);
 453                if (!data)
 454                        die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
 455                tree.buf = data;
 456                hit = grep_tree(opt, paths, &tree, name, "");
 457                free(data);
 458                return hit;
 459        }
 460        die("unable to grep from object of type %s", obj->type);
 461}
 462
 463static const char builtin_grep_usage[] =
 464"git-grep <option>* <rev>* [-e] <pattern> [<path>...]";
 465
 466int cmd_grep(int argc, const char **argv, char **envp)
 467{
 468        int hit = 0;
 469        int no_more_flags = 0;
 470        int seen_noncommit = 0;
 471        int cached = 0;
 472        struct grep_opt opt;
 473        struct object_list *list, **tail, *object_list = NULL;
 474        const char *prefix = setup_git_directory();
 475        const char **paths = NULL;
 476
 477        memset(&opt, 0, sizeof(opt));
 478        opt.pattern_tail = &opt.pattern_list;
 479        opt.regflags = REG_NEWLINE;
 480
 481        /*
 482         * No point using rev_info, really.
 483         */
 484        while (1 < argc) {
 485                const char *arg = argv[1];
 486                argc--; argv++;
 487                if (!strcmp("--cached", arg)) {
 488                        cached = 1;
 489                        continue;
 490                }
 491                if (!strcmp("-a", arg) ||
 492                    !strcmp("--text", arg)) {
 493                        opt.binary = GREP_BINARY_TEXT;
 494                        continue;
 495                }
 496                if (!strcmp("-i", arg) ||
 497                    !strcmp("--ignore-case", arg)) {
 498                        opt.regflags |= REG_ICASE;
 499                        continue;
 500                }
 501                if (!strcmp("-I", arg)) {
 502                        opt.binary = GREP_BINARY_NOMATCH;
 503                        continue;
 504                }
 505                if (!strcmp("-v", arg) ||
 506                    !strcmp("--invert-match", arg)) {
 507                        opt.invert = 1;
 508                        continue;
 509                }
 510                if (!strcmp("-E", arg) ||
 511                    !strcmp("--extended-regexp", arg)) {
 512                        opt.regflags |= REG_EXTENDED;
 513                        continue;
 514                }
 515                if (!strcmp("-G", arg) ||
 516                    !strcmp("--basic-regexp", arg)) {
 517                        opt.regflags &= ~REG_EXTENDED;
 518                        continue;
 519                }
 520                if (!strcmp("-n", arg)) {
 521                        opt.linenum = 1;
 522                        continue;
 523                }
 524                if (!strcmp("-H", arg)) {
 525                        /* We always show the pathname, so this
 526                         * is a noop.
 527                         */
 528                        continue;
 529                }
 530                if (!strcmp("-l", arg) ||
 531                    !strcmp("--files-with-matches", arg)) {
 532                        opt.name_only = 1;
 533                        continue;
 534                }
 535                if (!strcmp("-c", arg) ||
 536                    !strcmp("--count", arg)) {
 537                        opt.count = 1;
 538                        continue;
 539                }
 540                if (!strcmp("-w", arg) ||
 541                    !strcmp("--word-regexp", arg)) {
 542                        opt.word_regexp = 1;
 543                        continue;
 544                }
 545                if (!strncmp("-A", arg, 2) ||
 546                    !strncmp("-B", arg, 2) ||
 547                    !strncmp("-C", arg, 2) ||
 548                    (arg[0] == '-' && '1' <= arg[1] && arg[1] <= '9')) {
 549                        unsigned num;
 550                        const char *scan;
 551                        switch (arg[1]) {
 552                        case 'A': case 'B': case 'C':
 553                                if (!arg[2]) {
 554                                        if (argc <= 1)
 555                                                usage(builtin_grep_usage);
 556                                        scan = *++argv;
 557                                        argc--;
 558                                }
 559                                else
 560                                        scan = arg + 2;
 561                                break;
 562                        default:
 563                                scan = arg + 1;
 564                                break;
 565                        }
 566                        if (sscanf(scan, "%u", &num) != 1)
 567                                usage(builtin_grep_usage);
 568                        switch (arg[1]) {
 569                        case 'A':
 570                                opt.post_context = num;
 571                                break;
 572                        default:
 573                        case 'C':
 574                                opt.post_context = num;
 575                        case 'B':
 576                                opt.pre_context = num;
 577                                break;
 578                        }
 579                        continue;
 580                }
 581                if (!strcmp("-e", arg)) {
 582                        if (1 < argc) {
 583                                add_pattern(&opt, argv[1]);
 584                                argv++;
 585                                argc--;
 586                                continue;
 587                        }
 588                        usage(builtin_grep_usage);
 589                }
 590                if (!strcmp("--", arg)) {
 591                        no_more_flags = 1;
 592                        continue;
 593                }
 594                /* Either unrecognized option or a single pattern */
 595                if (!no_more_flags && *arg == '-')
 596                        usage(builtin_grep_usage);
 597                if (!opt.pattern_list) {
 598                        add_pattern(&opt, arg);
 599                        break;
 600                }
 601                else {
 602                        /* We are looking at the first path or rev;
 603                         * it is found at argv[0] after leaving the
 604                         * loop.
 605                         */
 606                        argc++; argv--;
 607                        break;
 608                }
 609        }
 610        if (!opt.pattern_list)
 611                die("no pattern given.");
 612        compile_patterns(&opt);
 613        tail = &object_list;
 614        while (1 < argc) {
 615                struct object *object;
 616                struct object_list *elem;
 617                const char *arg = argv[1];
 618                unsigned char sha1[20];
 619                if (get_sha1(arg, sha1) < 0)
 620                        break;
 621                object = parse_object(sha1);
 622                if (!object)
 623                        die("bad object %s", arg);
 624                elem = object_list_insert(object, tail);
 625                elem->name = arg;
 626                tail = &elem->next;
 627                argc--; argv++;
 628        }
 629        if (1 < argc)
 630                paths = get_pathspec(prefix, argv + 1);
 631        else if (prefix) {
 632                paths = xcalloc(2, sizeof(const char *));
 633                paths[0] = prefix;
 634                paths[1] = NULL;
 635        }
 636
 637        if (!object_list)
 638                return !grep_cache(&opt, paths, cached);
 639        /*
 640         * Do not walk "grep -e foo master next pu -- Documentation/"
 641         * but do walk "grep -e foo master..next -- Documentation/".
 642         * Ranged request mixed with a blob or tree object, like
 643         * "grep -e foo v1.0.0:Documentation/ master..next"
 644         * so detect that and complain.
 645         */
 646        for (list = object_list; list; list = list->next) {
 647                struct object *real_obj;
 648                real_obj = deref_tag(list->item, NULL, 0);
 649                if (strcmp(real_obj->type, commit_type))
 650                        seen_noncommit = 1;
 651        }
 652        if (cached)
 653                die("both --cached and revisions given.");
 654
 655        for (list = object_list; list; list = list->next) {
 656                struct object *real_obj;
 657                real_obj = deref_tag(list->item, NULL, 0);
 658                if (grep_object(&opt, paths, real_obj, list->name))
 659                        hit = 1;
 660        }
 661        return !hit;
 662}