Merge branch 'jc/fetch-sorted' into next
[gitweb.git] / builtin-grep.c
index 36512d8a17abccb67654b5bcfcd74a441b3e4586..53de8a883607157c88d02a30f0320aa9e5c0581a 100644 (file)
@@ -503,22 +503,34 @@ static int external_grep(struct grep_opt *opt, const char **paths, int cached)
                push_arg(p->pattern);
        }
 
-       if (NO_H_OPTION_IN_GREP)
+       /*
+        * To make sure we get the header printed out when we want it,
+        * add /dev/null to the paths to grep.  This is unnecessary
+        * (and wrong) with "-l" or "-L", which always print out the
+        * name anyway.
+        *
+        * GNU grep has "-H", but this is portable.
+        */
+       if (!opt->name_only && !opt->unmatch_name_only)
                push_arg("/dev/null");
-       else {
-               push_arg("-H");
-               push_arg("--");
-       }
 
        hit = 0;
        argc = nr;
        for (i = 0; i < active_nr; i++) {
                struct cache_entry *ce = active_cache[i];
+               char *name;
                if (ce_stage(ce) || !S_ISREG(ntohl(ce->ce_mode)))
                        continue;
                if (!pathspec_matches(paths, ce->name))
                        continue;
-               argv[argc++] = ce->name;
+               name = ce->name;
+               if (name[0] == '-') {
+                       int len = ce_namelen(ce);
+                       name = xmalloc(len + 3);
+                       memcpy(name, "./", 2);
+                       memcpy(name + 2, ce->name, len + 1);
+               }
+               argv[argc++] = name;
                if (argc < MAXARGS)
                        continue;
                hit += exec_grep(argc, argv);
@@ -540,19 +552,8 @@ static int grep_cache(struct grep_opt *opt, const char **paths, int cached)
         * Use the external "grep" command for the case where
         * we grep through the checked-out files. It tends to
         * be a lot more optimized
-        *
-        * Some grep implementations do not understand -H nor --
-        * but /dev/null can be used as a substitution in most
-        * cases.
-        *
-        * However -L and -c would slightly misbehave (-L would
-        * list /dev/null as a hit, and -c would report 0 hits
-        * from /dev/null); so do not use the external one on
-        * such platforms.
         */
-       if (!cached &&
-           (!NO_H_OPTION_IN_GREP ||
-            (!opt->count && !opt->unmatch_name_only))) {
+       if (!cached) {
                hit = external_grep(opt, paths, cached);
                if (hit >= 0)
                        return hit;