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