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