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