Merge branch 'jc/revision-range-unpeel' into maint
[git] / builtin / for-each-ref.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "refs.h"
4 #include "object.h"
5 #include "tag.h"
6 #include "commit.h"
7 #include "tree.h"
8 #include "blob.h"
9 #include "quote.h"
10 #include "parse-options.h"
11 #include "remote.h"
12
13 /* Quoting styles */
14 #define QUOTE_NONE 0
15 #define QUOTE_SHELL 1
16 #define QUOTE_PERL 2
17 #define QUOTE_PYTHON 4
18 #define QUOTE_TCL 8
19
20 typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
21
22 struct atom_value {
23         const char *s;
24         unsigned long ul; /* used for sorting when not FIELD_STR */
25 };
26
27 struct ref_sort {
28         struct ref_sort *next;
29         int atom; /* index into used_atom array */
30         unsigned reverse : 1;
31 };
32
33 struct refinfo {
34         char *refname;
35         unsigned char objectname[20];
36         int flag;
37         const char *symref;
38         struct atom_value *value;
39 };
40
41 static struct {
42         const char *name;
43         cmp_type cmp_type;
44 } valid_atom[] = {
45         { "refname" },
46         { "objecttype" },
47         { "objectsize", FIELD_ULONG },
48         { "objectname" },
49         { "tree" },
50         { "parent" },
51         { "numparent", FIELD_ULONG },
52         { "object" },
53         { "type" },
54         { "tag" },
55         { "author" },
56         { "authorname" },
57         { "authoremail" },
58         { "authordate", FIELD_TIME },
59         { "committer" },
60         { "committername" },
61         { "committeremail" },
62         { "committerdate", FIELD_TIME },
63         { "tagger" },
64         { "taggername" },
65         { "taggeremail" },
66         { "taggerdate", FIELD_TIME },
67         { "creator" },
68         { "creatordate", FIELD_TIME },
69         { "subject" },
70         { "body" },
71         { "contents" },
72         { "contents:subject" },
73         { "contents:body" },
74         { "contents:signature" },
75         { "upstream" },
76         { "symref" },
77         { "flag" },
78 };
79
80 /*
81  * An atom is a valid field atom listed above, possibly prefixed with
82  * a "*" to denote deref_tag().
83  *
84  * We parse given format string and sort specifiers, and make a list
85  * of properties that we need to extract out of objects.  refinfo
86  * structure will hold an array of values extracted that can be
87  * indexed with the "atom number", which is an index into this
88  * array.
89  */
90 static const char **used_atom;
91 static cmp_type *used_atom_type;
92 static int used_atom_cnt, need_tagged, need_symref;
93
94 /*
95  * Used to parse format string and sort specifiers
96  */
97 static int parse_atom(const char *atom, const char *ep)
98 {
99         const char *sp;
100         int i, at;
101
102         sp = atom;
103         if (*sp == '*' && sp < ep)
104                 sp++; /* deref */
105         if (ep <= sp)
106                 die("malformed field name: %.*s", (int)(ep-atom), atom);
107
108         /* Do we have the atom already used elsewhere? */
109         for (i = 0; i < used_atom_cnt; i++) {
110                 int len = strlen(used_atom[i]);
111                 if (len == ep - atom && !memcmp(used_atom[i], atom, len))
112                         return i;
113         }
114
115         /* Is the atom a valid one? */
116         for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
117                 int len = strlen(valid_atom[i].name);
118                 /*
119                  * If the atom name has a colon, strip it and everything after
120                  * it off - it specifies the format for this entry, and
121                  * shouldn't be used for checking against the valid_atom
122                  * table.
123                  */
124                 const char *formatp = strchr(sp, ':');
125                 if (!formatp || ep < formatp)
126                         formatp = ep;
127                 if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
128                         break;
129         }
130
131         if (ARRAY_SIZE(valid_atom) <= i)
132                 die("unknown field name: %.*s", (int)(ep-atom), atom);
133
134         /* Add it in, including the deref prefix */
135         at = used_atom_cnt;
136         used_atom_cnt++;
137         used_atom = xrealloc(used_atom,
138                              (sizeof *used_atom) * used_atom_cnt);
139         used_atom_type = xrealloc(used_atom_type,
140                                   (sizeof(*used_atom_type) * used_atom_cnt));
141         used_atom[at] = xmemdupz(atom, ep - atom);
142         used_atom_type[at] = valid_atom[i].cmp_type;
143         if (*atom == '*')
144                 need_tagged = 1;
145         if (!strcmp(used_atom[at], "symref"))
146                 need_symref = 1;
147         return at;
148 }
149
150 /*
151  * In a format string, find the next occurrence of %(atom).
152  */
153 static const char *find_next(const char *cp)
154 {
155         while (*cp) {
156                 if (*cp == '%') {
157                         /*
158                          * %( is the start of an atom;
159                          * %% is a quoted per-cent.
160                          */
161                         if (cp[1] == '(')
162                                 return cp;
163                         else if (cp[1] == '%')
164                                 cp++; /* skip over two % */
165                         /* otherwise this is a singleton, literal % */
166                 }
167                 cp++;
168         }
169         return NULL;
170 }
171
172 /*
173  * Make sure the format string is well formed, and parse out
174  * the used atoms.
175  */
176 static int verify_format(const char *format)
177 {
178         const char *cp, *sp;
179         for (cp = format; *cp && (sp = find_next(cp)); ) {
180                 const char *ep = strchr(sp, ')');
181                 if (!ep)
182                         return error("malformed format string %s", sp);
183                 /* sp points at "%(" and ep points at the closing ")" */
184                 parse_atom(sp + 2, ep);
185                 cp = ep + 1;
186         }
187         return 0;
188 }
189
190 /*
191  * Given an object name, read the object data and size, and return a
192  * "struct object".  If the object data we are returning is also borrowed
193  * by the "struct object" representation, set *eaten as well---it is a
194  * signal from parse_object_buffer to us not to free the buffer.
195  */
196 static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
197 {
198         enum object_type type;
199         void *buf = read_sha1_file(sha1, &type, sz);
200
201         if (buf)
202                 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
203         else
204                 *obj = NULL;
205         return buf;
206 }
207
208 static int grab_objectname(const char *name, const unsigned char *sha1,
209                             struct atom_value *v)
210 {
211         if (!strcmp(name, "objectname")) {
212                 char *s = xmalloc(41);
213                 strcpy(s, sha1_to_hex(sha1));
214                 v->s = s;
215                 return 1;
216         }
217         if (!strcmp(name, "objectname:short")) {
218                 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
219                 return 1;
220         }
221         return 0;
222 }
223
224 /* See grab_values */
225 static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
226 {
227         int i;
228
229         for (i = 0; i < used_atom_cnt; i++) {
230                 const char *name = used_atom[i];
231                 struct atom_value *v = &val[i];
232                 if (!!deref != (*name == '*'))
233                         continue;
234                 if (deref)
235                         name++;
236                 if (!strcmp(name, "objecttype"))
237                         v->s = typename(obj->type);
238                 else if (!strcmp(name, "objectsize")) {
239                         char *s = xmalloc(40);
240                         sprintf(s, "%lu", sz);
241                         v->ul = sz;
242                         v->s = s;
243                 }
244                 else if (deref)
245                         grab_objectname(name, obj->sha1, v);
246         }
247 }
248
249 /* See grab_values */
250 static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
251 {
252         int i;
253         struct tag *tag = (struct tag *) obj;
254
255         for (i = 0; i < used_atom_cnt; i++) {
256                 const char *name = used_atom[i];
257                 struct atom_value *v = &val[i];
258                 if (!!deref != (*name == '*'))
259                         continue;
260                 if (deref)
261                         name++;
262                 if (!strcmp(name, "tag"))
263                         v->s = tag->tag;
264                 else if (!strcmp(name, "type") && tag->tagged)
265                         v->s = typename(tag->tagged->type);
266                 else if (!strcmp(name, "object") && tag->tagged) {
267                         char *s = xmalloc(41);
268                         strcpy(s, sha1_to_hex(tag->tagged->sha1));
269                         v->s = s;
270                 }
271         }
272 }
273
274 static int num_parents(struct commit *commit)
275 {
276         struct commit_list *parents;
277         int i;
278
279         for (i = 0, parents = commit->parents;
280              parents;
281              parents = parents->next)
282                 i++;
283         return i;
284 }
285
286 /* See grab_values */
287 static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
288 {
289         int i;
290         struct commit *commit = (struct commit *) obj;
291
292         for (i = 0; i < used_atom_cnt; i++) {
293                 const char *name = used_atom[i];
294                 struct atom_value *v = &val[i];
295                 if (!!deref != (*name == '*'))
296                         continue;
297                 if (deref)
298                         name++;
299                 if (!strcmp(name, "tree")) {
300                         char *s = xmalloc(41);
301                         strcpy(s, sha1_to_hex(commit->tree->object.sha1));
302                         v->s = s;
303                 }
304                 if (!strcmp(name, "numparent")) {
305                         char *s = xmalloc(40);
306                         v->ul = num_parents(commit);
307                         sprintf(s, "%lu", v->ul);
308                         v->s = s;
309                 }
310                 else if (!strcmp(name, "parent")) {
311                         int num = num_parents(commit);
312                         int i;
313                         struct commit_list *parents;
314                         char *s = xmalloc(41 * num + 1);
315                         v->s = s;
316                         for (i = 0, parents = commit->parents;
317                              parents;
318                              parents = parents->next, i = i + 41) {
319                                 struct commit *parent = parents->item;
320                                 strcpy(s+i, sha1_to_hex(parent->object.sha1));
321                                 if (parents->next)
322                                         s[i+40] = ' ';
323                         }
324                         if (!i)
325                                 *s = '\0';
326                 }
327         }
328 }
329
330 static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
331 {
332         const char *eol;
333         while (*buf) {
334                 if (!strncmp(buf, who, wholen) &&
335                     buf[wholen] == ' ')
336                         return buf + wholen + 1;
337                 eol = strchr(buf, '\n');
338                 if (!eol)
339                         return "";
340                 eol++;
341                 if (*eol == '\n')
342                         return ""; /* end of header */
343                 buf = eol;
344         }
345         return "";
346 }
347
348 static const char *copy_line(const char *buf)
349 {
350         const char *eol = strchrnul(buf, '\n');
351         return xmemdupz(buf, eol - buf);
352 }
353
354 static const char *copy_name(const char *buf)
355 {
356         const char *cp;
357         for (cp = buf; *cp && *cp != '\n'; cp++) {
358                 if (!strncmp(cp, " <", 2))
359                         return xmemdupz(buf, cp - buf);
360         }
361         return "";
362 }
363
364 static const char *copy_email(const char *buf)
365 {
366         const char *email = strchr(buf, '<');
367         const char *eoemail;
368         if (!email)
369                 return "";
370         eoemail = strchr(email, '>');
371         if (!eoemail)
372                 return "";
373         return xmemdupz(email, eoemail + 1 - email);
374 }
375
376 static char *copy_subject(const char *buf, unsigned long len)
377 {
378         char *r = xmemdupz(buf, len);
379         int i;
380
381         for (i = 0; i < len; i++)
382                 if (r[i] == '\n')
383                         r[i] = ' ';
384
385         return r;
386 }
387
388 static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
389 {
390         const char *eoemail = strstr(buf, "> ");
391         char *zone;
392         unsigned long timestamp;
393         long tz;
394         enum date_mode date_mode = DATE_NORMAL;
395         const char *formatp;
396
397         /*
398          * We got here because atomname ends in "date" or "date<something>";
399          * it's not possible that <something> is not ":<format>" because
400          * parse_atom() wouldn't have allowed it, so we can assume that no
401          * ":" means no format is specified, and use the default.
402          */
403         formatp = strchr(atomname, ':');
404         if (formatp != NULL) {
405                 formatp++;
406                 date_mode = parse_date_format(formatp);
407         }
408
409         if (!eoemail)
410                 goto bad;
411         timestamp = strtoul(eoemail + 2, &zone, 10);
412         if (timestamp == ULONG_MAX)
413                 goto bad;
414         tz = strtol(zone, NULL, 10);
415         if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
416                 goto bad;
417         v->s = xstrdup(show_date(timestamp, tz, date_mode));
418         v->ul = timestamp;
419         return;
420  bad:
421         v->s = "";
422         v->ul = 0;
423 }
424
425 /* See grab_values */
426 static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
427 {
428         int i;
429         int wholen = strlen(who);
430         const char *wholine = NULL;
431
432         for (i = 0; i < used_atom_cnt; i++) {
433                 const char *name = used_atom[i];
434                 struct atom_value *v = &val[i];
435                 if (!!deref != (*name == '*'))
436                         continue;
437                 if (deref)
438                         name++;
439                 if (strncmp(who, name, wholen))
440                         continue;
441                 if (name[wholen] != 0 &&
442                     strcmp(name + wholen, "name") &&
443                     strcmp(name + wholen, "email") &&
444                     prefixcmp(name + wholen, "date"))
445                         continue;
446                 if (!wholine)
447                         wholine = find_wholine(who, wholen, buf, sz);
448                 if (!wholine)
449                         return; /* no point looking for it */
450                 if (name[wholen] == 0)
451                         v->s = copy_line(wholine);
452                 else if (!strcmp(name + wholen, "name"))
453                         v->s = copy_name(wholine);
454                 else if (!strcmp(name + wholen, "email"))
455                         v->s = copy_email(wholine);
456                 else if (!prefixcmp(name + wholen, "date"))
457                         grab_date(wholine, v, name);
458         }
459
460         /*
461          * For a tag or a commit object, if "creator" or "creatordate" is
462          * requested, do something special.
463          */
464         if (strcmp(who, "tagger") && strcmp(who, "committer"))
465                 return; /* "author" for commit object is not wanted */
466         if (!wholine)
467                 wholine = find_wholine(who, wholen, buf, sz);
468         if (!wholine)
469                 return;
470         for (i = 0; i < used_atom_cnt; i++) {
471                 const char *name = used_atom[i];
472                 struct atom_value *v = &val[i];
473                 if (!!deref != (*name == '*'))
474                         continue;
475                 if (deref)
476                         name++;
477
478                 if (!prefixcmp(name, "creatordate"))
479                         grab_date(wholine, v, name);
480                 else if (!strcmp(name, "creator"))
481                         v->s = copy_line(wholine);
482         }
483 }
484
485 static void find_subpos(const char *buf, unsigned long sz,
486                         const char **sub, unsigned long *sublen,
487                         const char **body, unsigned long *bodylen,
488                         unsigned long *nonsiglen,
489                         const char **sig, unsigned long *siglen)
490 {
491         const char *eol;
492         /* skip past header until we hit empty line */
493         while (*buf && *buf != '\n') {
494                 eol = strchrnul(buf, '\n');
495                 if (*eol)
496                         eol++;
497                 buf = eol;
498         }
499         /* skip any empty lines */
500         while (*buf == '\n')
501                 buf++;
502
503         /* parse signature first; we might not even have a subject line */
504         *sig = buf + parse_signature(buf, strlen(buf));
505         *siglen = strlen(*sig);
506
507         /* subject is first non-empty line */
508         *sub = buf;
509         /* subject goes to first empty line */
510         while (buf < *sig && *buf && *buf != '\n') {
511                 eol = strchrnul(buf, '\n');
512                 if (*eol)
513                         eol++;
514                 buf = eol;
515         }
516         *sublen = buf - *sub;
517         /* drop trailing newline, if present */
518         if (*sublen && (*sub)[*sublen - 1] == '\n')
519                 *sublen -= 1;
520
521         /* skip any empty lines */
522         while (*buf == '\n')
523                 buf++;
524         *body = buf;
525         *bodylen = strlen(buf);
526         *nonsiglen = *sig - buf;
527 }
528
529 /* See grab_values */
530 static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
531 {
532         int i;
533         const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
534         unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
535
536         for (i = 0; i < used_atom_cnt; i++) {
537                 const char *name = used_atom[i];
538                 struct atom_value *v = &val[i];
539                 if (!!deref != (*name == '*'))
540                         continue;
541                 if (deref)
542                         name++;
543                 if (strcmp(name, "subject") &&
544                     strcmp(name, "body") &&
545                     strcmp(name, "contents") &&
546                     strcmp(name, "contents:subject") &&
547                     strcmp(name, "contents:body") &&
548                     strcmp(name, "contents:signature"))
549                         continue;
550                 if (!subpos)
551                         find_subpos(buf, sz,
552                                     &subpos, &sublen,
553                                     &bodypos, &bodylen, &nonsiglen,
554                                     &sigpos, &siglen);
555
556                 if (!strcmp(name, "subject"))
557                         v->s = copy_subject(subpos, sublen);
558                 else if (!strcmp(name, "contents:subject"))
559                         v->s = copy_subject(subpos, sublen);
560                 else if (!strcmp(name, "body"))
561                         v->s = xmemdupz(bodypos, bodylen);
562                 else if (!strcmp(name, "contents:body"))
563                         v->s = xmemdupz(bodypos, nonsiglen);
564                 else if (!strcmp(name, "contents:signature"))
565                         v->s = xmemdupz(sigpos, siglen);
566                 else if (!strcmp(name, "contents"))
567                         v->s = xstrdup(subpos);
568         }
569 }
570
571 /*
572  * We want to have empty print-string for field requests
573  * that do not apply (e.g. "authordate" for a tag object)
574  */
575 static void fill_missing_values(struct atom_value *val)
576 {
577         int i;
578         for (i = 0; i < used_atom_cnt; i++) {
579                 struct atom_value *v = &val[i];
580                 if (v->s == NULL)
581                         v->s = "";
582         }
583 }
584
585 /*
586  * val is a list of atom_value to hold returned values.  Extract
587  * the values for atoms in used_atom array out of (obj, buf, sz).
588  * when deref is false, (obj, buf, sz) is the object that is
589  * pointed at by the ref itself; otherwise it is the object the
590  * ref (which is a tag) refers to.
591  */
592 static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
593 {
594         grab_common_values(val, deref, obj, buf, sz);
595         switch (obj->type) {
596         case OBJ_TAG:
597                 grab_tag_values(val, deref, obj, buf, sz);
598                 grab_sub_body_contents(val, deref, obj, buf, sz);
599                 grab_person("tagger", val, deref, obj, buf, sz);
600                 break;
601         case OBJ_COMMIT:
602                 grab_commit_values(val, deref, obj, buf, sz);
603                 grab_sub_body_contents(val, deref, obj, buf, sz);
604                 grab_person("author", val, deref, obj, buf, sz);
605                 grab_person("committer", val, deref, obj, buf, sz);
606                 break;
607         case OBJ_TREE:
608                 /* grab_tree_values(val, deref, obj, buf, sz); */
609                 break;
610         case OBJ_BLOB:
611                 /* grab_blob_values(val, deref, obj, buf, sz); */
612                 break;
613         default:
614                 die("Eh?  Object of type %d?", obj->type);
615         }
616 }
617
618 static inline char *copy_advance(char *dst, const char *src)
619 {
620         while (*src)
621                 *dst++ = *src++;
622         return dst;
623 }
624
625 /*
626  * Parse the object referred by ref, and grab needed value.
627  */
628 static void populate_value(struct refinfo *ref)
629 {
630         void *buf;
631         struct object *obj;
632         int eaten, i;
633         unsigned long size;
634         const unsigned char *tagged;
635
636         ref->value = xcalloc(sizeof(struct atom_value), used_atom_cnt);
637
638         if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
639                 unsigned char unused1[20];
640                 ref->symref = resolve_refdup(ref->refname, unused1, 1, NULL);
641                 if (!ref->symref)
642                         ref->symref = "";
643         }
644
645         /* Fill in specials first */
646         for (i = 0; i < used_atom_cnt; i++) {
647                 const char *name = used_atom[i];
648                 struct atom_value *v = &ref->value[i];
649                 int deref = 0;
650                 const char *refname;
651                 const char *formatp;
652
653                 if (*name == '*') {
654                         deref = 1;
655                         name++;
656                 }
657
658                 if (!prefixcmp(name, "refname"))
659                         refname = ref->refname;
660                 else if (!prefixcmp(name, "symref"))
661                         refname = ref->symref ? ref->symref : "";
662                 else if (!prefixcmp(name, "upstream")) {
663                         struct branch *branch;
664                         /* only local branches may have an upstream */
665                         if (prefixcmp(ref->refname, "refs/heads/"))
666                                 continue;
667                         branch = branch_get(ref->refname + 11);
668
669                         if (!branch || !branch->merge || !branch->merge[0] ||
670                             !branch->merge[0]->dst)
671                                 continue;
672                         refname = branch->merge[0]->dst;
673                 }
674                 else if (!strcmp(name, "flag")) {
675                         char buf[256], *cp = buf;
676                         if (ref->flag & REF_ISSYMREF)
677                                 cp = copy_advance(cp, ",symref");
678                         if (ref->flag & REF_ISPACKED)
679                                 cp = copy_advance(cp, ",packed");
680                         if (cp == buf)
681                                 v->s = "";
682                         else {
683                                 *cp = '\0';
684                                 v->s = xstrdup(buf + 1);
685                         }
686                         continue;
687                 }
688                 else if (!deref && grab_objectname(name, ref->objectname, v))
689                         continue;
690                 else
691                         continue;
692
693                 formatp = strchr(name, ':');
694                 /* look for "short" refname format */
695                 if (formatp) {
696                         formatp++;
697                         if (!strcmp(formatp, "short"))
698                                 refname = shorten_unambiguous_ref(refname,
699                                                       warn_ambiguous_refs);
700                         else
701                                 die("unknown %.*s format %s",
702                                     (int)(formatp - name), name, formatp);
703                 }
704
705                 if (!deref)
706                         v->s = refname;
707                 else {
708                         int len = strlen(refname);
709                         char *s = xmalloc(len + 4);
710                         sprintf(s, "%s^{}", refname);
711                         v->s = s;
712                 }
713         }
714
715         for (i = 0; i < used_atom_cnt; i++) {
716                 struct atom_value *v = &ref->value[i];
717                 if (v->s == NULL)
718                         goto need_obj;
719         }
720         return;
721
722  need_obj:
723         buf = get_obj(ref->objectname, &obj, &size, &eaten);
724         if (!buf)
725                 die("missing object %s for %s",
726                     sha1_to_hex(ref->objectname), ref->refname);
727         if (!obj)
728                 die("parse_object_buffer failed on %s for %s",
729                     sha1_to_hex(ref->objectname), ref->refname);
730
731         grab_values(ref->value, 0, obj, buf, size);
732         if (!eaten)
733                 free(buf);
734
735         /*
736          * If there is no atom that wants to know about tagged
737          * object, we are done.
738          */
739         if (!need_tagged || (obj->type != OBJ_TAG))
740                 return;
741
742         /*
743          * If it is a tag object, see if we use a value that derefs
744          * the object, and if we do grab the object it refers to.
745          */
746         tagged = ((struct tag *)obj)->tagged->sha1;
747
748         /*
749          * NEEDSWORK: This derefs tag only once, which
750          * is good to deal with chains of trust, but
751          * is not consistent with what deref_tag() does
752          * which peels the onion to the core.
753          */
754         buf = get_obj(tagged, &obj, &size, &eaten);
755         if (!buf)
756                 die("missing object %s for %s",
757                     sha1_to_hex(tagged), ref->refname);
758         if (!obj)
759                 die("parse_object_buffer failed on %s for %s",
760                     sha1_to_hex(tagged), ref->refname);
761         grab_values(ref->value, 1, obj, buf, size);
762         if (!eaten)
763                 free(buf);
764 }
765
766 /*
767  * Given a ref, return the value for the atom.  This lazily gets value
768  * out of the object by calling populate value.
769  */
770 static void get_value(struct refinfo *ref, int atom, struct atom_value **v)
771 {
772         if (!ref->value) {
773                 populate_value(ref);
774                 fill_missing_values(ref->value);
775         }
776         *v = &ref->value[atom];
777 }
778
779 struct grab_ref_cbdata {
780         struct refinfo **grab_array;
781         const char **grab_pattern;
782         int grab_cnt;
783 };
784
785 /*
786  * A call-back given to for_each_ref().  Filter refs and keep them for
787  * later object processing.
788  */
789 static int grab_single_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
790 {
791         struct grab_ref_cbdata *cb = cb_data;
792         struct refinfo *ref;
793         int cnt;
794
795         if (*cb->grab_pattern) {
796                 const char **pattern;
797                 int namelen = strlen(refname);
798                 for (pattern = cb->grab_pattern; *pattern; pattern++) {
799                         const char *p = *pattern;
800                         int plen = strlen(p);
801
802                         if ((plen <= namelen) &&
803                             !strncmp(refname, p, plen) &&
804                             (refname[plen] == '\0' ||
805                              refname[plen] == '/' ||
806                              p[plen-1] == '/'))
807                                 break;
808                         if (!fnmatch(p, refname, FNM_PATHNAME))
809                                 break;
810                 }
811                 if (!*pattern)
812                         return 0;
813         }
814
815         /*
816          * We do not open the object yet; sort may only need refname
817          * to do its job and the resulting list may yet to be pruned
818          * by maxcount logic.
819          */
820         ref = xcalloc(1, sizeof(*ref));
821         ref->refname = xstrdup(refname);
822         hashcpy(ref->objectname, sha1);
823         ref->flag = flag;
824
825         cnt = cb->grab_cnt;
826         cb->grab_array = xrealloc(cb->grab_array,
827                                   sizeof(*cb->grab_array) * (cnt + 1));
828         cb->grab_array[cnt++] = ref;
829         cb->grab_cnt = cnt;
830         return 0;
831 }
832
833 static int cmp_ref_sort(struct ref_sort *s, struct refinfo *a, struct refinfo *b)
834 {
835         struct atom_value *va, *vb;
836         int cmp;
837         cmp_type cmp_type = used_atom_type[s->atom];
838
839         get_value(a, s->atom, &va);
840         get_value(b, s->atom, &vb);
841         switch (cmp_type) {
842         case FIELD_STR:
843                 cmp = strcmp(va->s, vb->s);
844                 break;
845         default:
846                 if (va->ul < vb->ul)
847                         cmp = -1;
848                 else if (va->ul == vb->ul)
849                         cmp = 0;
850                 else
851                         cmp = 1;
852                 break;
853         }
854         return (s->reverse) ? -cmp : cmp;
855 }
856
857 static struct ref_sort *ref_sort;
858 static int compare_refs(const void *a_, const void *b_)
859 {
860         struct refinfo *a = *((struct refinfo **)a_);
861         struct refinfo *b = *((struct refinfo **)b_);
862         struct ref_sort *s;
863
864         for (s = ref_sort; s; s = s->next) {
865                 int cmp = cmp_ref_sort(s, a, b);
866                 if (cmp)
867                         return cmp;
868         }
869         return 0;
870 }
871
872 static void sort_refs(struct ref_sort *sort, struct refinfo **refs, int num_refs)
873 {
874         ref_sort = sort;
875         qsort(refs, num_refs, sizeof(struct refinfo *), compare_refs);
876 }
877
878 static void print_value(struct refinfo *ref, int atom, int quote_style)
879 {
880         struct atom_value *v;
881         struct strbuf sb = STRBUF_INIT;
882         get_value(ref, atom, &v);
883         switch (quote_style) {
884         case QUOTE_NONE:
885                 fputs(v->s, stdout);
886                 break;
887         case QUOTE_SHELL:
888                 sq_quote_buf(&sb, v->s);
889                 break;
890         case QUOTE_PERL:
891                 perl_quote_buf(&sb, v->s);
892                 break;
893         case QUOTE_PYTHON:
894                 python_quote_buf(&sb, v->s);
895                 break;
896         case QUOTE_TCL:
897                 tcl_quote_buf(&sb, v->s);
898                 break;
899         }
900         if (quote_style != QUOTE_NONE) {
901                 fputs(sb.buf, stdout);
902                 strbuf_release(&sb);
903         }
904 }
905
906 static int hex1(char ch)
907 {
908         if ('0' <= ch && ch <= '9')
909                 return ch - '0';
910         else if ('a' <= ch && ch <= 'f')
911                 return ch - 'a' + 10;
912         else if ('A' <= ch && ch <= 'F')
913                 return ch - 'A' + 10;
914         return -1;
915 }
916 static int hex2(const char *cp)
917 {
918         if (cp[0] && cp[1])
919                 return (hex1(cp[0]) << 4) | hex1(cp[1]);
920         else
921                 return -1;
922 }
923
924 static void emit(const char *cp, const char *ep)
925 {
926         while (*cp && (!ep || cp < ep)) {
927                 if (*cp == '%') {
928                         if (cp[1] == '%')
929                                 cp++;
930                         else {
931                                 int ch = hex2(cp + 1);
932                                 if (0 <= ch) {
933                                         putchar(ch);
934                                         cp += 3;
935                                         continue;
936                                 }
937                         }
938                 }
939                 putchar(*cp);
940                 cp++;
941         }
942 }
943
944 static void show_ref(struct refinfo *info, const char *format, int quote_style)
945 {
946         const char *cp, *sp, *ep;
947
948         for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
949                 ep = strchr(sp, ')');
950                 if (cp < sp)
951                         emit(cp, sp);
952                 print_value(info, parse_atom(sp + 2, ep), quote_style);
953         }
954         if (*cp) {
955                 sp = cp + strlen(cp);
956                 emit(cp, sp);
957         }
958         putchar('\n');
959 }
960
961 static struct ref_sort *default_sort(void)
962 {
963         static const char cstr_name[] = "refname";
964
965         struct ref_sort *sort = xcalloc(1, sizeof(*sort));
966
967         sort->next = NULL;
968         sort->atom = parse_atom(cstr_name, cstr_name + strlen(cstr_name));
969         return sort;
970 }
971
972 static int opt_parse_sort(const struct option *opt, const char *arg, int unset)
973 {
974         struct ref_sort **sort_tail = opt->value;
975         struct ref_sort *s;
976         int len;
977
978         if (!arg) /* should --no-sort void the list ? */
979                 return -1;
980
981         s = xcalloc(1, sizeof(*s));
982         s->next = *sort_tail;
983         *sort_tail = s;
984
985         if (*arg == '-') {
986                 s->reverse = 1;
987                 arg++;
988         }
989         len = strlen(arg);
990         s->atom = parse_atom(arg, arg+len);
991         return 0;
992 }
993
994 static char const * const for_each_ref_usage[] = {
995         N_("git for-each-ref [options] [<pattern>]"),
996         NULL
997 };
998
999 int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
1000 {
1001         int i, num_refs;
1002         const char *format = "%(objectname) %(objecttype)\t%(refname)";
1003         struct ref_sort *sort = NULL, **sort_tail = &sort;
1004         int maxcount = 0, quote_style = 0;
1005         struct refinfo **refs;
1006         struct grab_ref_cbdata cbdata;
1007
1008         struct option opts[] = {
1009                 OPT_BIT('s', "shell", &quote_style,
1010                         N_("quote placeholders suitably for shells"), QUOTE_SHELL),
1011                 OPT_BIT('p', "perl",  &quote_style,
1012                         N_("quote placeholders suitably for perl"), QUOTE_PERL),
1013                 OPT_BIT(0 , "python", &quote_style,
1014                         N_("quote placeholders suitably for python"), QUOTE_PYTHON),
1015                 OPT_BIT(0 , "tcl",  &quote_style,
1016                         N_("quote placeholders suitably for tcl"), QUOTE_TCL),
1017
1018                 OPT_GROUP(""),
1019                 OPT_INTEGER( 0 , "count", &maxcount, N_("show only <n> matched refs")),
1020                 OPT_STRING(  0 , "format", &format, N_("format"), N_("format to use for the output")),
1021                 OPT_CALLBACK(0 , "sort", sort_tail, N_("key"),
1022                             N_("field name to sort on"), &opt_parse_sort),
1023                 OPT_END(),
1024         };
1025
1026         parse_options(argc, argv, prefix, opts, for_each_ref_usage, 0);
1027         if (maxcount < 0) {
1028                 error("invalid --count argument: `%d'", maxcount);
1029                 usage_with_options(for_each_ref_usage, opts);
1030         }
1031         if (HAS_MULTI_BITS(quote_style)) {
1032                 error("more than one quoting style?");
1033                 usage_with_options(for_each_ref_usage, opts);
1034         }
1035         if (verify_format(format))
1036                 usage_with_options(for_each_ref_usage, opts);
1037
1038         if (!sort)
1039                 sort = default_sort();
1040
1041         /* for warn_ambiguous_refs */
1042         git_config(git_default_config, NULL);
1043
1044         memset(&cbdata, 0, sizeof(cbdata));
1045         cbdata.grab_pattern = argv;
1046         for_each_rawref(grab_single_ref, &cbdata);
1047         refs = cbdata.grab_array;
1048         num_refs = cbdata.grab_cnt;
1049
1050         sort_refs(sort, refs, num_refs);
1051
1052         if (!maxcount || num_refs < maxcount)
1053                 maxcount = num_refs;
1054         for (i = 0; i < maxcount; i++)
1055                 show_ref(refs[i], format, quote_style);
1056         return 0;
1057 }