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