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