builtin-grep.con commit grep: expose "status-only" feature via -q (c8610a2)
   1/*
   2 * Builtin "git grep"
   3 *
   4 * Copyright (c) 2006 Junio C Hamano
   5 */
   6#include "cache.h"
   7#include "blob.h"
   8#include "tree.h"
   9#include "commit.h"
  10#include "tag.h"
  11#include "tree-walk.h"
  12#include "builtin.h"
  13#include "parse-options.h"
  14#include "userdiff.h"
  15#include "grep.h"
  16#include "quote.h"
  17#include "dir.h"
  18
  19static char const * const grep_usage[] = {
  20        "git grep [options] [-e] <pattern> [<rev>...] [[--] path...]",
  21        NULL
  22};
  23
  24static int grep_config(const char *var, const char *value, void *cb)
  25{
  26        struct grep_opt *opt = cb;
  27
  28        switch (userdiff_config(var, value)) {
  29        case 0: break;
  30        case -1: return -1;
  31        default: return 0;
  32        }
  33
  34        if (!strcmp(var, "color.grep")) {
  35                opt->color = git_config_colorbool(var, value, -1);
  36                return 0;
  37        }
  38        if (!strcmp(var, "color.grep.match")) {
  39                if (!value)
  40                        return config_error_nonbool(var);
  41                color_parse(value, var, opt->color_match);
  42                return 0;
  43        }
  44        return git_color_default_config(var, value, cb);
  45}
  46
  47/*
  48 * Return non-zero if max_depth is negative or path has no more then max_depth
  49 * slashes.
  50 */
  51static int accept_subdir(const char *path, int max_depth)
  52{
  53        if (max_depth < 0)
  54                return 1;
  55
  56        while ((path = strchr(path, '/')) != NULL) {
  57                max_depth--;
  58                if (max_depth < 0)
  59                        return 0;
  60                path++;
  61        }
  62        return 1;
  63}
  64
  65/*
  66 * Return non-zero if name is a subdirectory of match and is not too deep.
  67 */
  68static int is_subdir(const char *name, int namelen,
  69                const char *match, int matchlen, int max_depth)
  70{
  71        if (matchlen > namelen || strncmp(name, match, matchlen))
  72                return 0;
  73
  74        if (name[matchlen] == '\0') /* exact match */
  75                return 1;
  76
  77        if (!matchlen || match[matchlen-1] == '/' || name[matchlen] == '/')
  78                return accept_subdir(name + matchlen + 1, max_depth);
  79
  80        return 0;
  81}
  82
  83/*
  84 * git grep pathspecs are somewhat different from diff-tree pathspecs;
  85 * pathname wildcards are allowed.
  86 */
  87static int pathspec_matches(const char **paths, const char *name, int max_depth)
  88{
  89        int namelen, i;
  90        if (!paths || !*paths)
  91                return accept_subdir(name, max_depth);
  92        namelen = strlen(name);
  93        for (i = 0; paths[i]; i++) {
  94                const char *match = paths[i];
  95                int matchlen = strlen(match);
  96                const char *cp, *meta;
  97
  98                if (is_subdir(name, namelen, match, matchlen, max_depth))
  99                        return 1;
 100                if (!fnmatch(match, name, 0))
 101                        return 1;
 102                if (name[namelen-1] != '/')
 103                        continue;
 104
 105                /* We are being asked if the directory ("name") is worth
 106                 * descending into.
 107                 *
 108                 * Find the longest leading directory name that does
 109                 * not have metacharacter in the pathspec; the name
 110                 * we are looking at must overlap with that directory.
 111                 */
 112                for (cp = match, meta = NULL; cp - match < matchlen; cp++) {
 113                        char ch = *cp;
 114                        if (ch == '*' || ch == '[' || ch == '?') {
 115                                meta = cp;
 116                                break;
 117                        }
 118                }
 119                if (!meta)
 120                        meta = cp; /* fully literal */
 121
 122                if (namelen <= meta - match) {
 123                        /* Looking at "Documentation/" and
 124                         * the pattern says "Documentation/howto/", or
 125                         * "Documentation/diff*.txt".  The name we
 126                         * have should match prefix.
 127                         */
 128                        if (!memcmp(match, name, namelen))
 129                                return 1;
 130                        continue;
 131                }
 132
 133                if (meta - match < namelen) {
 134                        /* Looking at "Documentation/howto/" and
 135                         * the pattern says "Documentation/h*";
 136                         * match up to "Do.../h"; this avoids descending
 137                         * into "Documentation/technical/".
 138                         */
 139                        if (!memcmp(match, name, meta - match))
 140                                return 1;
 141                        continue;
 142                }
 143        }
 144        return 0;
 145}
 146
 147static int grep_sha1(struct grep_opt *opt, const unsigned char *sha1, const char *name, int tree_name_len)
 148{
 149        unsigned long size;
 150        char *data;
 151        enum object_type type;
 152        int hit;
 153        struct strbuf pathbuf = STRBUF_INIT;
 154
 155        data = read_sha1_file(sha1, &type, &size);
 156        if (!data) {
 157                error("'%s': unable to read %s", name, sha1_to_hex(sha1));
 158                return 0;
 159        }
 160        if (opt->relative && opt->prefix_length) {
 161                quote_path_relative(name + tree_name_len, -1, &pathbuf, opt->prefix);
 162                strbuf_insert(&pathbuf, 0, name, tree_name_len);
 163                name = pathbuf.buf;
 164        }
 165        hit = grep_buffer(opt, name, data, size);
 166        strbuf_release(&pathbuf);
 167        free(data);
 168        return hit;
 169}
 170
 171static int grep_file(struct grep_opt *opt, const char *filename)
 172{
 173        struct stat st;
 174        int i;
 175        char *data;
 176        size_t sz;
 177        struct strbuf buf = STRBUF_INIT;
 178
 179        if (lstat(filename, &st) < 0) {
 180        err_ret:
 181                if (errno != ENOENT)
 182                        error("'%s': %s", filename, strerror(errno));
 183                return 0;
 184        }
 185        if (!S_ISREG(st.st_mode))
 186                return 0;
 187        sz = xsize_t(st.st_size);
 188        i = open(filename, O_RDONLY);
 189        if (i < 0)
 190                goto err_ret;
 191        data = xmalloc(sz + 1);
 192        if (st.st_size != read_in_full(i, data, sz)) {
 193                error("'%s': short read %s", filename, strerror(errno));
 194                close(i);
 195                free(data);
 196                return 0;
 197        }
 198        close(i);
 199        data[sz] = 0;
 200        if (opt->relative && opt->prefix_length)
 201                filename = quote_path_relative(filename, -1, &buf, opt->prefix);
 202        i = grep_buffer(opt, filename, data, sz);
 203        strbuf_release(&buf);
 204        free(data);
 205        return i;
 206}
 207
 208static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
 209{
 210        int hit = 0;
 211        int nr;
 212        read_cache();
 213
 214        for (nr = 0; nr < active_nr; nr++) {
 215                struct cache_entry *ce = active_cache[nr];
 216                if (!S_ISREG(ce->ce_mode))
 217                        continue;
 218                if (!pathspec_matches(paths, ce->name, opt->max_depth))
 219                        continue;
 220                /*
 221                 * If CE_VALID is on, we assume worktree file and its cache entry
 222                 * are identical, even if worktree file has been modified, so use
 223                 * cache version instead
 224                 */
 225                if (cached || (ce->ce_flags & CE_VALID) || ce_skip_worktree(ce)) {
 226                        if (ce_stage(ce))
 227                                continue;
 228                        hit |= grep_sha1(opt, ce->sha1, ce->name, 0);
 229                }
 230                else
 231                        hit |= grep_file(opt, ce->name);
 232                if (ce_stage(ce)) {
 233                        do {
 234                                nr++;
 235                        } while (nr < active_nr &&
 236                                 !strcmp(ce->name, active_cache[nr]->name));
 237                        nr--; /* compensate for loop control */
 238                }
 239                if (hit && opt->status_only)
 240                        break;
 241        }
 242        free_grep_patterns(opt);
 243        return hit;
 244}
 245
 246static int grep_tree(struct grep_opt *opt, const char **paths,
 247                     struct tree_desc *tree,
 248                     const char *tree_name, const char *base)
 249{
 250        int len;
 251        int hit = 0;
 252        struct name_entry entry;
 253        char *down;
 254        int tn_len = strlen(tree_name);
 255        struct strbuf pathbuf;
 256
 257        strbuf_init(&pathbuf, PATH_MAX + tn_len);
 258
 259        if (tn_len) {
 260                strbuf_add(&pathbuf, tree_name, tn_len);
 261                strbuf_addch(&pathbuf, ':');
 262                tn_len = pathbuf.len;
 263        }
 264        strbuf_addstr(&pathbuf, base);
 265        len = pathbuf.len;
 266
 267        while (tree_entry(tree, &entry)) {
 268                int te_len = tree_entry_len(entry.path, entry.sha1);
 269                pathbuf.len = len;
 270                strbuf_add(&pathbuf, entry.path, te_len);
 271
 272                if (S_ISDIR(entry.mode))
 273                        /* Match "abc/" against pathspec to
 274                         * decide if we want to descend into "abc"
 275                         * directory.
 276                         */
 277                        strbuf_addch(&pathbuf, '/');
 278
 279                down = pathbuf.buf + tn_len;
 280                if (!pathspec_matches(paths, down, opt->max_depth))
 281                        ;
 282                else if (S_ISREG(entry.mode))
 283                        hit |= grep_sha1(opt, entry.sha1, pathbuf.buf, tn_len);
 284                else if (S_ISDIR(entry.mode)) {
 285                        enum object_type type;
 286                        struct tree_desc sub;
 287                        void *data;
 288                        unsigned long size;
 289
 290                        data = read_sha1_file(entry.sha1, &type, &size);
 291                        if (!data)
 292                                die("unable to read tree (%s)",
 293                                    sha1_to_hex(entry.sha1));
 294                        init_tree_desc(&sub, data, size);
 295                        hit |= grep_tree(opt, paths, &sub, tree_name, down);
 296                        free(data);
 297                }
 298                if (hit && opt->status_only)
 299                        break;
 300        }
 301        strbuf_release(&pathbuf);
 302        return hit;
 303}
 304
 305static int grep_object(struct grep_opt *opt, const char **paths,
 306                       struct object *obj, const char *name)
 307{
 308        if (obj->type == OBJ_BLOB)
 309                return grep_sha1(opt, obj->sha1, name, 0);
 310        if (obj->type == OBJ_COMMIT || obj->type == OBJ_TREE) {
 311                struct tree_desc tree;
 312                void *data;
 313                unsigned long size;
 314                int hit;
 315                data = read_object_with_reference(obj->sha1, tree_type,
 316                                                  &size, NULL);
 317                if (!data)
 318                        die("unable to read tree (%s)", sha1_to_hex(obj->sha1));
 319                init_tree_desc(&tree, data, size);
 320                hit = grep_tree(opt, paths, &tree, name, "");
 321                free(data);
 322                return hit;
 323        }
 324        die("unable to grep from object of type %s", typename(obj->type));
 325}
 326
 327static int grep_directory(struct grep_opt *opt, const char **paths)
 328{
 329        struct dir_struct dir;
 330        int i, hit = 0;
 331
 332        memset(&dir, 0, sizeof(dir));
 333        setup_standard_excludes(&dir);
 334
 335        fill_directory(&dir, paths);
 336        for (i = 0; i < dir.nr; i++) {
 337                hit |= grep_file(opt, dir.entries[i]->name);
 338                if (hit && opt->status_only)
 339                        break;
 340        }
 341        free_grep_patterns(opt);
 342        return hit;
 343}
 344
 345static int context_callback(const struct option *opt, const char *arg,
 346                            int unset)
 347{
 348        struct grep_opt *grep_opt = opt->value;
 349        int value;
 350        const char *endp;
 351
 352        if (unset) {
 353                grep_opt->pre_context = grep_opt->post_context = 0;
 354                return 0;
 355        }
 356        value = strtol(arg, (char **)&endp, 10);
 357        if (*endp) {
 358                return error("switch `%c' expects a numerical value",
 359                             opt->short_name);
 360        }
 361        grep_opt->pre_context = grep_opt->post_context = value;
 362        return 0;
 363}
 364
 365static int file_callback(const struct option *opt, const char *arg, int unset)
 366{
 367        struct grep_opt *grep_opt = opt->value;
 368        FILE *patterns;
 369        int lno = 0;
 370        struct strbuf sb = STRBUF_INIT;
 371
 372        patterns = fopen(arg, "r");
 373        if (!patterns)
 374                die_errno("cannot open '%s'", arg);
 375        while (strbuf_getline(&sb, patterns, '\n') == 0) {
 376                /* ignore empty line like grep does */
 377                if (sb.len == 0)
 378                        continue;
 379                append_grep_pattern(grep_opt, strbuf_detach(&sb, NULL), arg,
 380                                    ++lno, GREP_PATTERN);
 381        }
 382        fclose(patterns);
 383        strbuf_release(&sb);
 384        return 0;
 385}
 386
 387static int not_callback(const struct option *opt, const char *arg, int unset)
 388{
 389        struct grep_opt *grep_opt = opt->value;
 390        append_grep_pattern(grep_opt, "--not", "command line", 0, GREP_NOT);
 391        return 0;
 392}
 393
 394static int and_callback(const struct option *opt, const char *arg, int unset)
 395{
 396        struct grep_opt *grep_opt = opt->value;
 397        append_grep_pattern(grep_opt, "--and", "command line", 0, GREP_AND);
 398        return 0;
 399}
 400
 401static int open_callback(const struct option *opt, const char *arg, int unset)
 402{
 403        struct grep_opt *grep_opt = opt->value;
 404        append_grep_pattern(grep_opt, "(", "command line", 0, GREP_OPEN_PAREN);
 405        return 0;
 406}
 407
 408static int close_callback(const struct option *opt, const char *arg, int unset)
 409{
 410        struct grep_opt *grep_opt = opt->value;
 411        append_grep_pattern(grep_opt, ")", "command line", 0, GREP_CLOSE_PAREN);
 412        return 0;
 413}
 414
 415static int pattern_callback(const struct option *opt, const char *arg,
 416                            int unset)
 417{
 418        struct grep_opt *grep_opt = opt->value;
 419        append_grep_pattern(grep_opt, arg, "-e option", 0, GREP_PATTERN);
 420        return 0;
 421}
 422
 423static int help_callback(const struct option *opt, const char *arg, int unset)
 424{
 425        return -1;
 426}
 427
 428int cmd_grep(int argc, const char **argv, const char *prefix)
 429{
 430        int hit = 0;
 431        int cached = 0;
 432        int seen_dashdash = 0;
 433        int external_grep_allowed__ignored;
 434        struct grep_opt opt;
 435        struct object_array list = { 0, 0, NULL };
 436        const char **paths = NULL;
 437        int i;
 438        int dummy;
 439        int nongit = 0, use_index = 1;
 440        struct option options[] = {
 441                OPT_BOOLEAN(0, "cached", &cached,
 442                        "search in index instead of in the work tree"),
 443                OPT_BOOLEAN(0, "index", &use_index,
 444                        "--no-index finds in contents not managed by git"),
 445                OPT_GROUP(""),
 446                OPT_BOOLEAN('v', "invert-match", &opt.invert,
 447                        "show non-matching lines"),
 448                OPT_BOOLEAN('i', "ignore-case", &opt.ignore_case,
 449                        "case insensitive matching"),
 450                OPT_BOOLEAN('w', "word-regexp", &opt.word_regexp,
 451                        "match patterns only at word boundaries"),
 452                OPT_SET_INT('a', "text", &opt.binary,
 453                        "process binary files as text", GREP_BINARY_TEXT),
 454                OPT_SET_INT('I', NULL, &opt.binary,
 455                        "don't match patterns in binary files",
 456                        GREP_BINARY_NOMATCH),
 457                { OPTION_INTEGER, 0, "max-depth", &opt.max_depth, "depth",
 458                        "descend at most <depth> levels", PARSE_OPT_NONEG,
 459                        NULL, 1 },
 460                OPT_GROUP(""),
 461                OPT_BIT('E', "extended-regexp", &opt.regflags,
 462                        "use extended POSIX regular expressions", REG_EXTENDED),
 463                OPT_NEGBIT('G', "basic-regexp", &opt.regflags,
 464                        "use basic POSIX regular expressions (default)",
 465                        REG_EXTENDED),
 466                OPT_BOOLEAN('F', "fixed-strings", &opt.fixed,
 467                        "interpret patterns as fixed strings"),
 468                OPT_GROUP(""),
 469                OPT_BOOLEAN('n', NULL, &opt.linenum, "show line numbers"),
 470                OPT_NEGBIT('h', NULL, &opt.pathname, "don't show filenames", 1),
 471                OPT_BIT('H', NULL, &opt.pathname, "show filenames", 1),
 472                OPT_NEGBIT(0, "full-name", &opt.relative,
 473                        "show filenames relative to top directory", 1),
 474                OPT_BOOLEAN('l', "files-with-matches", &opt.name_only,
 475                        "show only filenames instead of matching lines"),
 476                OPT_BOOLEAN(0, "name-only", &opt.name_only,
 477                        "synonym for --files-with-matches"),
 478                OPT_BOOLEAN('L', "files-without-match",
 479                        &opt.unmatch_name_only,
 480                        "show only the names of files without match"),
 481                OPT_BOOLEAN('z', "null", &opt.null_following_name,
 482                        "print NUL after filenames"),
 483                OPT_BOOLEAN('c', "count", &opt.count,
 484                        "show the number of matches instead of matching lines"),
 485                OPT_SET_INT(0, "color", &opt.color, "highlight matches", 1),
 486                OPT_GROUP(""),
 487                OPT_CALLBACK('C', NULL, &opt, "n",
 488                        "show <n> context lines before and after matches",
 489                        context_callback),
 490                OPT_INTEGER('B', NULL, &opt.pre_context,
 491                        "show <n> context lines before matches"),
 492                OPT_INTEGER('A', NULL, &opt.post_context,
 493                        "show <n> context lines after matches"),
 494                OPT_NUMBER_CALLBACK(&opt, "shortcut for -C NUM",
 495                        context_callback),
 496                OPT_BOOLEAN('p', "show-function", &opt.funcname,
 497                        "show a line with the function name before matches"),
 498                OPT_GROUP(""),
 499                OPT_CALLBACK('f', NULL, &opt, "file",
 500                        "read patterns from file", file_callback),
 501                { OPTION_CALLBACK, 'e', NULL, &opt, "pattern",
 502                        "match <pattern>", PARSE_OPT_NONEG, pattern_callback },
 503                { OPTION_CALLBACK, 0, "and", &opt, NULL,
 504                  "combine patterns specified with -e",
 505                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, and_callback },
 506                OPT_BOOLEAN(0, "or", &dummy, ""),
 507                { OPTION_CALLBACK, 0, "not", &opt, NULL, "",
 508                  PARSE_OPT_NOARG | PARSE_OPT_NONEG, not_callback },
 509                { OPTION_CALLBACK, '(', NULL, &opt, NULL, "",
 510                  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
 511                  open_callback },
 512                { OPTION_CALLBACK, ')', NULL, &opt, NULL, "",
 513                  PARSE_OPT_NOARG | PARSE_OPT_NONEG | PARSE_OPT_NODASH,
 514                  close_callback },
 515                OPT_BOOLEAN('q', "quick", &opt.status_only,
 516                            "indicate hit with exit status without output"),
 517                OPT_BOOLEAN(0, "all-match", &opt.all_match,
 518                        "show only matches from files that match all patterns"),
 519                OPT_GROUP(""),
 520                OPT_BOOLEAN(0, "ext-grep", &external_grep_allowed__ignored,
 521                            "allow calling of grep(1) (ignored by this build)"),
 522                { OPTION_CALLBACK, 0, "help-all", &options, NULL, "show usage",
 523                  PARSE_OPT_HIDDEN | PARSE_OPT_NOARG, help_callback },
 524                OPT_END()
 525        };
 526
 527        prefix = setup_git_directory_gently(&nongit);
 528
 529        /*
 530         * 'git grep -h', unlike 'git grep -h <pattern>', is a request
 531         * to show usage information and exit.
 532         */
 533        if (argc == 2 && !strcmp(argv[1], "-h"))
 534                usage_with_options(grep_usage, options);
 535
 536        memset(&opt, 0, sizeof(opt));
 537        opt.prefix = prefix;
 538        opt.prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
 539        opt.relative = 1;
 540        opt.pathname = 1;
 541        opt.pattern_tail = &opt.pattern_list;
 542        opt.regflags = REG_NEWLINE;
 543        opt.max_depth = -1;
 544
 545        strcpy(opt.color_match, GIT_COLOR_RED GIT_COLOR_BOLD);
 546        opt.color = -1;
 547        git_config(grep_config, &opt);
 548        if (opt.color == -1)
 549                opt.color = git_use_color_default;
 550
 551        /*
 552         * If there is no -- then the paths must exist in the working
 553         * tree.  If there is no explicit pattern specified with -e or
 554         * -f, we take the first unrecognized non option to be the
 555         * pattern, but then what follows it must be zero or more
 556         * valid refs up to the -- (if exists), and then existing
 557         * paths.  If there is an explicit pattern, then the first
 558         * unrecognized non option is the beginning of the refs list
 559         * that continues up to the -- (if exists), and then paths.
 560         */
 561        argc = parse_options(argc, argv, prefix, options, grep_usage,
 562                             PARSE_OPT_KEEP_DASHDASH |
 563                             PARSE_OPT_STOP_AT_NON_OPTION |
 564                             PARSE_OPT_NO_INTERNAL_HELP);
 565
 566        if (use_index && nongit)
 567                /* die the same way as if we did it at the beginning */
 568                setup_git_directory();
 569
 570        /* First unrecognized non-option token */
 571        if (argc > 0 && !opt.pattern_list) {
 572                append_grep_pattern(&opt, argv[0], "command line", 0,
 573                                    GREP_PATTERN);
 574                argv++;
 575                argc--;
 576        }
 577
 578        if (!opt.pattern_list)
 579                die("no pattern given.");
 580        if (!opt.fixed && opt.ignore_case)
 581                opt.regflags |= REG_ICASE;
 582        if ((opt.regflags != REG_NEWLINE) && opt.fixed)
 583                die("cannot mix --fixed-strings and regexp");
 584        compile_grep_patterns(&opt);
 585
 586        /* Check revs and then paths */
 587        for (i = 0; i < argc; i++) {
 588                const char *arg = argv[i];
 589                unsigned char sha1[20];
 590                /* Is it a rev? */
 591                if (!get_sha1(arg, sha1)) {
 592                        struct object *object = parse_object(sha1);
 593                        if (!object)
 594                                die("bad object %s", arg);
 595                        add_object_array(object, arg, &list);
 596                        continue;
 597                }
 598                if (!strcmp(arg, "--")) {
 599                        i++;
 600                        seen_dashdash = 1;
 601                }
 602                break;
 603        }
 604
 605        /* The rest are paths */
 606        if (!seen_dashdash) {
 607                int j;
 608                for (j = i; j < argc; j++)
 609                        verify_filename(prefix, argv[j]);
 610        }
 611
 612        if (i < argc)
 613                paths = get_pathspec(prefix, argv + i);
 614        else if (prefix) {
 615                paths = xcalloc(2, sizeof(const char *));
 616                paths[0] = prefix;
 617                paths[1] = NULL;
 618        }
 619
 620        if (!use_index) {
 621                if (cached)
 622                        die("--cached cannot be used with --no-index.");
 623                if (list.nr)
 624                        die("--no-index cannot be used with revs.");
 625                return !grep_directory(&opt, paths);
 626        }
 627
 628        if (!list.nr) {
 629                if (!cached)
 630                        setup_work_tree();
 631                return !grep_cache(&opt, paths, cached);
 632        }
 633
 634        if (cached)
 635                die("both --cached and trees are given.");
 636
 637        for (i = 0; i < list.nr; i++) {
 638                struct object *real_obj;
 639                real_obj = deref_tag(list.objects[i].item, NULL, 0);
 640                if (grep_object(&opt, paths, real_obj, list.objects[i].name)) {
 641                        hit = 1;
 642                        if (opt.status_only)
 643                                break;
 644                }
 645        }
 646        free_grep_patterns(&opt);
 647        return !hit;
 648}